Optimization of shuffle node that can fit to the register form of VBROADCAST instruct...
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
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 "X86ISelLowering.h"
17 #include "X86.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 using namespace llvm;
53
54 STATISTIC(NumTailCalls, "Number of tail calls");
55
56 // Forward declarations.
57 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
58                        SDValue V2);
59
60 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
61 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
62 /// simple subregister reference.  Idx is an index in the 128 bits we
63 /// want.  It need not be aligned to a 128-bit bounday.  That makes
64 /// lowering EXTRACT_VECTOR_ELT operations easier.
65 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
66                                    SelectionDAG &DAG, DebugLoc dl) {
67   EVT VT = Vec.getValueType();
68   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
69   EVT ElVT = VT.getVectorElementType();
70   unsigned Factor = VT.getSizeInBits()/128;
71   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72                                   VT.getVectorNumElements()/Factor);
73
74   // Extract from UNDEF is UNDEF.
75   if (Vec.getOpcode() == ISD::UNDEF)
76     return DAG.getUNDEF(ResultVT);
77
78   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
79   // we can match to VEXTRACTF128.
80   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
81
82   // This is the index of the first element of the 128-bit chunk
83   // we want.
84   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
85                                * ElemsPerChunk);
86
87   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
88   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
89                                VecIdx);
90
91   return Result;
92 }
93
94 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
95 /// sets things up to match to an AVX VINSERTF128 instruction or a
96 /// simple superregister reference.  Idx is an index in the 128 bits
97 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
98 /// lowering INSERT_VECTOR_ELT operations easier.
99 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
100                                   unsigned IdxVal, SelectionDAG &DAG,
101                                   DebugLoc dl) {
102   // Inserting UNDEF is Result
103   if (Vec.getOpcode() == ISD::UNDEF)
104     return Result;
105
106   EVT VT = Vec.getValueType();
107   assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
108
109   EVT ElVT = VT.getVectorElementType();
110   EVT ResultVT = Result.getValueType();
111
112   // Insert the relevant 128 bits.
113   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
114
115   // This is the index of the first element of the 128-bit chunk
116   // we want.
117   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
118                                * ElemsPerChunk);
119
120   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
121   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
122                      VecIdx);
123 }
124
125 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
126 /// instructions. This is used because creating CONCAT_VECTOR nodes of
127 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
128 /// large BUILD_VECTORS.
129 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
130                                    unsigned NumElems, SelectionDAG &DAG,
131                                    DebugLoc dl) {
132   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
133   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
134 }
135
136 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
137   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
138   bool is64Bit = Subtarget->is64Bit();
139
140   if (Subtarget->isTargetEnvMacho()) {
141     if (is64Bit)
142       return new X86_64MachoTargetObjectFile();
143     return new TargetLoweringObjectFileMachO();
144   }
145
146   if (Subtarget->isTargetLinux())
147     return new X86LinuxTargetObjectFile();
148   if (Subtarget->isTargetELF())
149     return new TargetLoweringObjectFileELF();
150   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
151     return new TargetLoweringObjectFileCOFF();
152   llvm_unreachable("unknown subtarget type");
153 }
154
155 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
156   : TargetLowering(TM, createTLOF(TM)) {
157   Subtarget = &TM.getSubtarget<X86Subtarget>();
158   X86ScalarSSEf64 = Subtarget->hasSSE2();
159   X86ScalarSSEf32 = Subtarget->hasSSE1();
160   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
161
162   RegInfo = TM.getRegisterInfo();
163   TD = getTargetData();
164
165   // Set up the TargetLowering object.
166   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
167
168   // X86 is weird, it always uses i8 for shift amounts and setcc results.
169   setBooleanContents(ZeroOrOneBooleanContent);
170   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
172
173   // For 64-bit since we have so many registers use the ILP scheduler, for
174   // 32-bit code use the register pressure specific scheduling.
175   // For Atom, always use ILP scheduling.
176   if (Subtarget->isAtom()) 
177     setSchedulingPreference(Sched::ILP);
178   else if (Subtarget->is64Bit())
179     setSchedulingPreference(Sched::ILP);
180   else
181     setSchedulingPreference(Sched::RegPressure);
182   setStackPointerRegisterToSaveRestore(X86StackPtr);
183
184   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
185     // Setup Windows compiler runtime calls.
186     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
187     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
188     setLibcallName(RTLIB::SREM_I64, "_allrem");
189     setLibcallName(RTLIB::UREM_I64, "_aullrem");
190     setLibcallName(RTLIB::MUL_I64, "_allmul");
191     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
192     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
193     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
194     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
195     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
196
197     // The _ftol2 runtime function has an unusual calling conv, which
198     // is modeled by a special pseudo-instruction.
199     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
200     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
201     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
202     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
203   }
204
205   if (Subtarget->isTargetDarwin()) {
206     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
207     setUseUnderscoreSetJmp(false);
208     setUseUnderscoreLongJmp(false);
209   } else if (Subtarget->isTargetMingw()) {
210     // MS runtime is weird: it exports _setjmp, but longjmp!
211     setUseUnderscoreSetJmp(true);
212     setUseUnderscoreLongJmp(false);
213   } else {
214     setUseUnderscoreSetJmp(true);
215     setUseUnderscoreLongJmp(true);
216   }
217
218   // Set up the register classes.
219   addRegisterClass(MVT::i8, &X86::GR8RegClass);
220   addRegisterClass(MVT::i16, &X86::GR16RegClass);
221   addRegisterClass(MVT::i32, &X86::GR32RegClass);
222   if (Subtarget->is64Bit())
223     addRegisterClass(MVT::i64, &X86::GR64RegClass);
224
225   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
226
227   // We don't accept any truncstore of integer registers.
228   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
229   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
230   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
231   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
232   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
233   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
234
235   // SETOEQ and SETUNE require checking two conditions.
236   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
237   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
238   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
239   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
240   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
241   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
242
243   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
244   // operation.
245   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
246   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
247   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
248
249   if (Subtarget->is64Bit()) {
250     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
251     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
252   } else if (!TM.Options.UseSoftFloat) {
253     // We have an algorithm for SSE2->double, and we turn this into a
254     // 64-bit FILD followed by conditional FADD for other targets.
255     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
256     // We have an algorithm for SSE2, and we turn this into a 64-bit
257     // FILD for other targets.
258     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
259   }
260
261   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
262   // this operation.
263   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
264   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
265
266   if (!TM.Options.UseSoftFloat) {
267     // SSE has no i16 to fp conversion, only i32
268     if (X86ScalarSSEf32) {
269       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
270       // f32 and f64 cases are Legal, f80 case is not
271       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
272     } else {
273       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
274       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
275     }
276   } else {
277     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
278     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
279   }
280
281   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
282   // are Legal, f80 is custom lowered.
283   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
284   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
285
286   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
287   // this operation.
288   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
289   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
290
291   if (X86ScalarSSEf32) {
292     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
293     // f32 and f64 cases are Legal, f80 case is not
294     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
295   } else {
296     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
297     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
298   }
299
300   // Handle FP_TO_UINT by promoting the destination to a larger signed
301   // conversion.
302   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
303   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
304   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
305
306   if (Subtarget->is64Bit()) {
307     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
308     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
309   } else if (!TM.Options.UseSoftFloat) {
310     // Since AVX is a superset of SSE3, only check for SSE here.
311     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
312       // Expand FP_TO_UINT into a select.
313       // FIXME: We would like to use a Custom expander here eventually to do
314       // the optimal thing for SSE vs. the default expansion in the legalizer.
315       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
316     else
317       // With SSE3 we can use fisttpll to convert to a signed i64; without
318       // SSE, we're stuck with a fistpll.
319       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
320   }
321
322   if (isTargetFTOL()) {
323     // Use the _ftol2 runtime function, which has a pseudo-instruction
324     // to handle its weird calling convention.
325     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
326   }
327
328   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
329   if (!X86ScalarSSEf64) {
330     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
331     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
332     if (Subtarget->is64Bit()) {
333       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
334       // Without SSE, i64->f64 goes through memory.
335       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
336     }
337   }
338
339   // Scalar integer divide and remainder are lowered to use operations that
340   // produce two results, to match the available instructions. This exposes
341   // the two-result form to trivial CSE, which is able to combine x/y and x%y
342   // into a single instruction.
343   //
344   // Scalar integer multiply-high is also lowered to use two-result
345   // operations, to match the available instructions. However, plain multiply
346   // (low) operations are left as Legal, as there are single-result
347   // instructions for this in x86. Using the two-result multiply instructions
348   // when both high and low results are needed must be arranged by dagcombine.
349   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
350     MVT VT = IntVTs[i];
351     setOperationAction(ISD::MULHS, VT, Expand);
352     setOperationAction(ISD::MULHU, VT, Expand);
353     setOperationAction(ISD::SDIV, VT, Expand);
354     setOperationAction(ISD::UDIV, VT, Expand);
355     setOperationAction(ISD::SREM, VT, Expand);
356     setOperationAction(ISD::UREM, VT, Expand);
357
358     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
359     setOperationAction(ISD::ADDC, VT, Custom);
360     setOperationAction(ISD::ADDE, VT, Custom);
361     setOperationAction(ISD::SUBC, VT, Custom);
362     setOperationAction(ISD::SUBE, VT, Custom);
363   }
364
365   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
366   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
367   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
368   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
369   if (Subtarget->is64Bit())
370     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
371   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
372   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
374   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
375   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
376   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
378   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
379
380   // Promote the i8 variants and force them on up to i32 which has a shorter
381   // encoding.
382   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
383   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
384   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
385   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
386   if (Subtarget->hasBMI()) {
387     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
388     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
391   } else {
392     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
393     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
394     if (Subtarget->is64Bit())
395       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
396   }
397
398   if (Subtarget->hasLZCNT()) {
399     // When promoting the i8 variants, force them to i32 for a shorter
400     // encoding.
401     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
402     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
403     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
404     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
405     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
406     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
407     if (Subtarget->is64Bit())
408       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
409   } else {
410     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
411     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
412     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
413     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
414     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
415     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
418       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
419     }
420   }
421
422   if (Subtarget->hasPOPCNT()) {
423     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
424   } else {
425     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
426     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
427     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
428     if (Subtarget->is64Bit())
429       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
430   }
431
432   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
433   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
434
435   // These should be promoted to a larger select which is supported.
436   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
437   // X86 wants to expand cmov itself.
438   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
439   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
440   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
441   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
442   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
443   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
444   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
445   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
446   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
447   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
448   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
450   if (Subtarget->is64Bit()) {
451     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
452     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
453   }
454   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
455
456   // Darwin ABI issue.
457   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
458   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
459   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
460   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
461   if (Subtarget->is64Bit())
462     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
463   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
464   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
465   if (Subtarget->is64Bit()) {
466     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
467     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
468     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
469     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
470     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
471   }
472   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
473   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
474   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
475   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
476   if (Subtarget->is64Bit()) {
477     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
478     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
479     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
480   }
481
482   if (Subtarget->hasSSE1())
483     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
484
485   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
486   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
487
488   // On X86 and X86-64, atomic operations are lowered to locked instructions.
489   // Locked instructions, in turn, have implicit fence semantics (all memory
490   // operations are flushed before issuing the locked instruction, and they
491   // are not buffered), so we can fold away the common pattern of
492   // fence-atomic-fence.
493   setShouldFoldAtomicFences(true);
494
495   // Expand certain atomics
496   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
497     MVT VT = IntVTs[i];
498     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
499     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
500     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
501   }
502
503   if (!Subtarget->is64Bit()) {
504     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
505     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
512   }
513
514   if (Subtarget->hasCmpxchg16b()) {
515     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
516   }
517
518   // FIXME - use subtarget debug flags
519   if (!Subtarget->isTargetDarwin() &&
520       !Subtarget->isTargetELF() &&
521       !Subtarget->isTargetCygMing()) {
522     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
523   }
524
525   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
526   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
527   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
528   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
529   if (Subtarget->is64Bit()) {
530     setExceptionPointerRegister(X86::RAX);
531     setExceptionSelectorRegister(X86::RDX);
532   } else {
533     setExceptionPointerRegister(X86::EAX);
534     setExceptionSelectorRegister(X86::EDX);
535   }
536   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
537   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
538
539   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
540   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
541
542   setOperationAction(ISD::TRAP, MVT::Other, Legal);
543
544   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
545   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
546   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
547   if (Subtarget->is64Bit()) {
548     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
549     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
550   } else {
551     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
552     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
553   }
554
555   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
556   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
557
558   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
559     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
560                        MVT::i64 : MVT::i32, Custom);
561   else if (TM.Options.EnableSegmentedStacks)
562     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
563                        MVT::i64 : MVT::i32, Custom);
564   else
565     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
566                        MVT::i64 : MVT::i32, Expand);
567
568   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
569     // f32 and f64 use SSE.
570     // Set up the FP register classes.
571     addRegisterClass(MVT::f32, &X86::FR32RegClass);
572     addRegisterClass(MVT::f64, &X86::FR64RegClass);
573
574     // Use ANDPD to simulate FABS.
575     setOperationAction(ISD::FABS , MVT::f64, Custom);
576     setOperationAction(ISD::FABS , MVT::f32, Custom);
577
578     // Use XORP to simulate FNEG.
579     setOperationAction(ISD::FNEG , MVT::f64, Custom);
580     setOperationAction(ISD::FNEG , MVT::f32, Custom);
581
582     // Use ANDPD and ORPD to simulate FCOPYSIGN.
583     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
584     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
585
586     // Lower this to FGETSIGNx86 plus an AND.
587     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
588     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
589
590     // We don't support sin/cos/fmod
591     setOperationAction(ISD::FSIN , MVT::f64, Expand);
592     setOperationAction(ISD::FCOS , MVT::f64, Expand);
593     setOperationAction(ISD::FSIN , MVT::f32, Expand);
594     setOperationAction(ISD::FCOS , MVT::f32, Expand);
595
596     // Expand FP immediates into loads from the stack, except for the special
597     // cases we handle.
598     addLegalFPImmediate(APFloat(+0.0)); // xorpd
599     addLegalFPImmediate(APFloat(+0.0f)); // xorps
600   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
601     // Use SSE for f32, x87 for f64.
602     // Set up the FP register classes.
603     addRegisterClass(MVT::f32, &X86::FR32RegClass);
604     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
605
606     // Use ANDPS to simulate FABS.
607     setOperationAction(ISD::FABS , MVT::f32, Custom);
608
609     // Use XORP to simulate FNEG.
610     setOperationAction(ISD::FNEG , MVT::f32, Custom);
611
612     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
613
614     // Use ANDPS and ORPS to simulate FCOPYSIGN.
615     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
616     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
617
618     // We don't support sin/cos/fmod
619     setOperationAction(ISD::FSIN , MVT::f32, Expand);
620     setOperationAction(ISD::FCOS , MVT::f32, Expand);
621
622     // Special cases we handle for FP constants.
623     addLegalFPImmediate(APFloat(+0.0f)); // xorps
624     addLegalFPImmediate(APFloat(+0.0)); // FLD0
625     addLegalFPImmediate(APFloat(+1.0)); // FLD1
626     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
627     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
628
629     if (!TM.Options.UnsafeFPMath) {
630       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
631       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
632     }
633   } else if (!TM.Options.UseSoftFloat) {
634     // f32 and f64 in x87.
635     // Set up the FP register classes.
636     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
637     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
638
639     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
640     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
641     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
642     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
643
644     if (!TM.Options.UnsafeFPMath) {
645       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
646       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
647     }
648     addLegalFPImmediate(APFloat(+0.0)); // FLD0
649     addLegalFPImmediate(APFloat(+1.0)); // FLD1
650     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
651     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
652     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
653     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
654     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
655     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
656   }
657
658   // We don't support FMA.
659   setOperationAction(ISD::FMA, MVT::f64, Expand);
660   setOperationAction(ISD::FMA, MVT::f32, Expand);
661
662   // Long double always uses X87.
663   if (!TM.Options.UseSoftFloat) {
664     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
665     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
666     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
667     {
668       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
669       addLegalFPImmediate(TmpFlt);  // FLD0
670       TmpFlt.changeSign();
671       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
672
673       bool ignored;
674       APFloat TmpFlt2(+1.0);
675       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
676                       &ignored);
677       addLegalFPImmediate(TmpFlt2);  // FLD1
678       TmpFlt2.changeSign();
679       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
680     }
681
682     if (!TM.Options.UnsafeFPMath) {
683       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
684       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
685     }
686
687     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
688     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
689     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
690     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
691     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
692     setOperationAction(ISD::FMA, MVT::f80, Expand);
693   }
694
695   // Always use a library call for pow.
696   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
697   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
698   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
699
700   setOperationAction(ISD::FLOG, MVT::f80, Expand);
701   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
702   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
703   setOperationAction(ISD::FEXP, MVT::f80, Expand);
704   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
705
706   // First set operation action for all vector types to either promote
707   // (for widening) or expand (for scalarization). Then we will selectively
708   // turn on ones that can be effectively codegen'd.
709   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
710            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
711     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
726     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
728     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
729     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
763     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
768     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
769              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
770       setTruncStoreAction((MVT::SimpleValueType)VT,
771                           (MVT::SimpleValueType)InnerVT, Expand);
772     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
773     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
774     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
775   }
776
777   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
778   // with -msoft-float, disable use of MMX as well.
779   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
780     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
781     // No operations on x86mmx supported, everything uses intrinsics.
782   }
783
784   // MMX-sized vectors (other than x86mmx) are expected to be expanded
785   // into smaller operations.
786   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
787   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
788   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
789   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
790   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
791   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
792   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
793   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
794   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
795   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
796   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
797   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
798   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
799   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
800   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
801   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
802   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
803   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
804   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
805   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
806   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
807   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
808   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
809   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
810   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
811   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
812   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
813   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
814   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
815
816   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
817     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
818
819     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
820     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
821     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
822     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
823     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
824     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
825     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
826     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
827     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
828     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
829     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
830     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
831   }
832
833   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
834     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
835
836     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
837     // registers cannot be used even for integer operations.
838     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
839     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
840     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
841     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
842
843     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
844     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
845     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
846     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
847     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
848     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
849     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
850     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
851     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
852     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
853     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
854     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
855     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
856     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
857     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
858     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
859
860     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
861     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
862     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
863     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
864
865     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
866     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
867     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
868     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
869     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
870
871     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
872     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
873     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
874     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
875     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
876
877     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
878     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
879       EVT VT = (MVT::SimpleValueType)i;
880       // Do not attempt to custom lower non-power-of-2 vectors
881       if (!isPowerOf2_32(VT.getVectorNumElements()))
882         continue;
883       // Do not attempt to custom lower non-128-bit vectors
884       if (!VT.is128BitVector())
885         continue;
886       setOperationAction(ISD::BUILD_VECTOR,
887                          VT.getSimpleVT().SimpleTy, Custom);
888       setOperationAction(ISD::VECTOR_SHUFFLE,
889                          VT.getSimpleVT().SimpleTy, Custom);
890       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
891                          VT.getSimpleVT().SimpleTy, Custom);
892     }
893
894     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
895     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
896     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
897     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
898     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
899     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
900
901     if (Subtarget->is64Bit()) {
902       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
903       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
904     }
905
906     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
907     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
908       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
909       EVT VT = SVT;
910
911       // Do not attempt to promote non-128-bit vectors
912       if (!VT.is128BitVector())
913         continue;
914
915       setOperationAction(ISD::AND,    SVT, Promote);
916       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
917       setOperationAction(ISD::OR,     SVT, Promote);
918       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
919       setOperationAction(ISD::XOR,    SVT, Promote);
920       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
921       setOperationAction(ISD::LOAD,   SVT, Promote);
922       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
923       setOperationAction(ISD::SELECT, SVT, Promote);
924       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
925     }
926
927     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
928
929     // Custom lower v2i64 and v2f64 selects.
930     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
931     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
932     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
933     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
934
935     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
936     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
937   }
938
939   if (Subtarget->hasSSE41()) {
940     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
941     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
942     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
943     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
944     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
945     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
946     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
947     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
948     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
949     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
950
951     // FIXME: Do we need to handle scalar-to-vector here?
952     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
953
954     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
955     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
956     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
957     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
958     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
959
960     // i8 and i16 vectors are custom , because the source register and source
961     // source memory operand types are not the same width.  f32 vectors are
962     // custom since the immediate controlling the insert encodes additional
963     // information.
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
966     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
967     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
968
969     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
970     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
971     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
972     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
973
974     // FIXME: these should be Legal but thats only for the case where
975     // the index is constant.  For now custom expand to deal with that.
976     if (Subtarget->is64Bit()) {
977       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
978       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
979     }
980   }
981
982   if (Subtarget->hasSSE2()) {
983     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
984     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
985
986     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
987     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
988
989     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
990     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
991
992     if (Subtarget->hasAVX2()) {
993       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
994       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
995
996       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
997       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
998
999       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1000     } else {
1001       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1002       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1003
1004       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1005       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1006
1007       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1008     }
1009   }
1010
1011   if (Subtarget->hasSSE42())
1012     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
1013
1014   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1015     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1016     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1017     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1018     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1019     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1020     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1021
1022     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1023     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1024     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1025
1026     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1027     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1028     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1029     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1030     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1031     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1032
1033     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1034     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1035     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1036     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1037     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1038     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1039
1040     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1041     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1042     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1043
1044     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1045     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1046     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1047     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1048     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1049     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1050
1051     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1052     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1053
1054     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1055     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1056
1057     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1058     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1059
1060     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1061     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1062     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1063     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1064
1065     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1066     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1067     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1068
1069     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1070     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1071     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1072     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1073
1074     if (Subtarget->hasAVX2()) {
1075       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1076       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1077       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1078       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1079
1080       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1081       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1082       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1083       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1084
1085       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1086       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1087       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1088       // Don't lower v32i8 because there is no 128-bit byte mul
1089
1090       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1091
1092       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1093       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1094
1095       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1096       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1097
1098       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1099     } else {
1100       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1101       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1102       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1103       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1104
1105       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1106       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1107       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1108       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1109
1110       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1111       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1112       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1113       // Don't lower v32i8 because there is no 128-bit byte mul
1114
1115       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1116       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1117
1118       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1119       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1120
1121       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1122     }
1123
1124     // Custom lower several nodes for 256-bit types.
1125     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1126              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1127       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1128       EVT VT = SVT;
1129
1130       // Extract subvector is special because the value type
1131       // (result) is 128-bit but the source is 256-bit wide.
1132       if (VT.is128BitVector())
1133         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1134
1135       // Do not attempt to custom lower other non-256-bit vectors
1136       if (!VT.is256BitVector())
1137         continue;
1138
1139       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1140       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1141       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1142       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1143       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1144       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1145     }
1146
1147     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1148     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1149       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1150       EVT VT = SVT;
1151
1152       // Do not attempt to promote non-256-bit vectors
1153       if (!VT.is256BitVector())
1154         continue;
1155
1156       setOperationAction(ISD::AND,    SVT, Promote);
1157       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1158       setOperationAction(ISD::OR,     SVT, Promote);
1159       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1160       setOperationAction(ISD::XOR,    SVT, Promote);
1161       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1162       setOperationAction(ISD::LOAD,   SVT, Promote);
1163       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1164       setOperationAction(ISD::SELECT, SVT, Promote);
1165       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1166     }
1167   }
1168
1169   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1170   // of this type with custom code.
1171   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1172            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1173     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1174                        Custom);
1175   }
1176
1177   // We want to custom lower some of our intrinsics.
1178   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1179
1180
1181   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1182   // handle type legalization for these operations here.
1183   //
1184   // FIXME: We really should do custom legalization for addition and
1185   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1186   // than generic legalization for 64-bit multiplication-with-overflow, though.
1187   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1188     // Add/Sub/Mul with overflow operations are custom lowered.
1189     MVT VT = IntVTs[i];
1190     setOperationAction(ISD::SADDO, VT, Custom);
1191     setOperationAction(ISD::UADDO, VT, Custom);
1192     setOperationAction(ISD::SSUBO, VT, Custom);
1193     setOperationAction(ISD::USUBO, VT, Custom);
1194     setOperationAction(ISD::SMULO, VT, Custom);
1195     setOperationAction(ISD::UMULO, VT, Custom);
1196   }
1197
1198   // There are no 8-bit 3-address imul/mul instructions
1199   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1200   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1201
1202   if (!Subtarget->is64Bit()) {
1203     // These libcalls are not available in 32-bit.
1204     setLibcallName(RTLIB::SHL_I128, 0);
1205     setLibcallName(RTLIB::SRL_I128, 0);
1206     setLibcallName(RTLIB::SRA_I128, 0);
1207   }
1208
1209   // We have target-specific dag combine patterns for the following nodes:
1210   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1211   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1212   setTargetDAGCombine(ISD::VSELECT);
1213   setTargetDAGCombine(ISD::SELECT);
1214   setTargetDAGCombine(ISD::SHL);
1215   setTargetDAGCombine(ISD::SRA);
1216   setTargetDAGCombine(ISD::SRL);
1217   setTargetDAGCombine(ISD::OR);
1218   setTargetDAGCombine(ISD::AND);
1219   setTargetDAGCombine(ISD::ADD);
1220   setTargetDAGCombine(ISD::FADD);
1221   setTargetDAGCombine(ISD::FSUB);
1222   setTargetDAGCombine(ISD::SUB);
1223   setTargetDAGCombine(ISD::LOAD);
1224   setTargetDAGCombine(ISD::STORE);
1225   setTargetDAGCombine(ISD::ZERO_EXTEND);
1226   setTargetDAGCombine(ISD::ANY_EXTEND);
1227   setTargetDAGCombine(ISD::SIGN_EXTEND);
1228   setTargetDAGCombine(ISD::TRUNCATE);
1229   setTargetDAGCombine(ISD::UINT_TO_FP);
1230   setTargetDAGCombine(ISD::SINT_TO_FP);
1231   setTargetDAGCombine(ISD::SETCC);
1232   setTargetDAGCombine(ISD::FP_TO_SINT);
1233   if (Subtarget->is64Bit())
1234     setTargetDAGCombine(ISD::MUL);
1235   setTargetDAGCombine(ISD::XOR);
1236
1237   computeRegisterProperties();
1238
1239   // On Darwin, -Os means optimize for size without hurting performance,
1240   // do not reduce the limit.
1241   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1242   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1243   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1244   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1245   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1246   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1247   setPrefLoopAlignment(4); // 2^4 bytes.
1248   benefitFromCodePlacementOpt = true;
1249
1250   // Predictable cmov don't hurt on atom because it's in-order.
1251   predictableSelectIsExpensive = !Subtarget->isAtom();
1252
1253   setPrefFunctionAlignment(4); // 2^4 bytes.
1254 }
1255
1256
1257 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1258   if (!VT.isVector()) return MVT::i8;
1259   return VT.changeVectorElementTypeToInteger();
1260 }
1261
1262
1263 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1264 /// the desired ByVal argument alignment.
1265 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1266   if (MaxAlign == 16)
1267     return;
1268   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1269     if (VTy->getBitWidth() == 128)
1270       MaxAlign = 16;
1271   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1272     unsigned EltAlign = 0;
1273     getMaxByValAlign(ATy->getElementType(), EltAlign);
1274     if (EltAlign > MaxAlign)
1275       MaxAlign = EltAlign;
1276   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1277     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1278       unsigned EltAlign = 0;
1279       getMaxByValAlign(STy->getElementType(i), EltAlign);
1280       if (EltAlign > MaxAlign)
1281         MaxAlign = EltAlign;
1282       if (MaxAlign == 16)
1283         break;
1284     }
1285   }
1286 }
1287
1288 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1289 /// function arguments in the caller parameter area. For X86, aggregates
1290 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1291 /// are at 4-byte boundaries.
1292 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1293   if (Subtarget->is64Bit()) {
1294     // Max of 8 and alignment of type.
1295     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1296     if (TyAlign > 8)
1297       return TyAlign;
1298     return 8;
1299   }
1300
1301   unsigned Align = 4;
1302   if (Subtarget->hasSSE1())
1303     getMaxByValAlign(Ty, Align);
1304   return Align;
1305 }
1306
1307 /// getOptimalMemOpType - Returns the target specific optimal type for load
1308 /// and store operations as a result of memset, memcpy, and memmove
1309 /// lowering. If DstAlign is zero that means it's safe to destination
1310 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1311 /// means there isn't a need to check it against alignment requirement,
1312 /// probably because the source does not need to be loaded. If
1313 /// 'IsZeroVal' is true, that means it's safe to return a
1314 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1315 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1316 /// constant so it does not need to be loaded.
1317 /// It returns EVT::Other if the type should be determined using generic
1318 /// target-independent logic.
1319 EVT
1320 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1321                                        unsigned DstAlign, unsigned SrcAlign,
1322                                        bool IsZeroVal,
1323                                        bool MemcpyStrSrc,
1324                                        MachineFunction &MF) const {
1325   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1326   // linux.  This is because the stack realignment code can't handle certain
1327   // cases like PR2962.  This should be removed when PR2962 is fixed.
1328   const Function *F = MF.getFunction();
1329   if (IsZeroVal &&
1330       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1331     if (Size >= 16 &&
1332         (Subtarget->isUnalignedMemAccessFast() ||
1333          ((DstAlign == 0 || DstAlign >= 16) &&
1334           (SrcAlign == 0 || SrcAlign >= 16))) &&
1335         Subtarget->getStackAlignment() >= 16) {
1336       if (Subtarget->getStackAlignment() >= 32) {
1337         if (Subtarget->hasAVX2())
1338           return MVT::v8i32;
1339         if (Subtarget->hasAVX())
1340           return MVT::v8f32;
1341       }
1342       if (Subtarget->hasSSE2())
1343         return MVT::v4i32;
1344       if (Subtarget->hasSSE1())
1345         return MVT::v4f32;
1346     } else if (!MemcpyStrSrc && Size >= 8 &&
1347                !Subtarget->is64Bit() &&
1348                Subtarget->getStackAlignment() >= 8 &&
1349                Subtarget->hasSSE2()) {
1350       // Do not use f64 to lower memcpy if source is string constant. It's
1351       // better to use i32 to avoid the loads.
1352       return MVT::f64;
1353     }
1354   }
1355   if (Subtarget->is64Bit() && Size >= 8)
1356     return MVT::i64;
1357   return MVT::i32;
1358 }
1359
1360 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1361 /// current function.  The returned value is a member of the
1362 /// MachineJumpTableInfo::JTEntryKind enum.
1363 unsigned X86TargetLowering::getJumpTableEncoding() const {
1364   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1365   // symbol.
1366   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1367       Subtarget->isPICStyleGOT())
1368     return MachineJumpTableInfo::EK_Custom32;
1369
1370   // Otherwise, use the normal jump table encoding heuristics.
1371   return TargetLowering::getJumpTableEncoding();
1372 }
1373
1374 const MCExpr *
1375 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1376                                              const MachineBasicBlock *MBB,
1377                                              unsigned uid,MCContext &Ctx) const{
1378   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1379          Subtarget->isPICStyleGOT());
1380   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1381   // entries.
1382   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1383                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1384 }
1385
1386 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1387 /// jumptable.
1388 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1389                                                     SelectionDAG &DAG) const {
1390   if (!Subtarget->is64Bit())
1391     // This doesn't have DebugLoc associated with it, but is not really the
1392     // same as a Register.
1393     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1394   return Table;
1395 }
1396
1397 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1398 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1399 /// MCExpr.
1400 const MCExpr *X86TargetLowering::
1401 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1402                              MCContext &Ctx) const {
1403   // X86-64 uses RIP relative addressing based on the jump table label.
1404   if (Subtarget->isPICStyleRIPRel())
1405     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1406
1407   // Otherwise, the reference is relative to the PIC base.
1408   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1409 }
1410
1411 // FIXME: Why this routine is here? Move to RegInfo!
1412 std::pair<const TargetRegisterClass*, uint8_t>
1413 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1414   const TargetRegisterClass *RRC = 0;
1415   uint8_t Cost = 1;
1416   switch (VT.getSimpleVT().SimpleTy) {
1417   default:
1418     return TargetLowering::findRepresentativeClass(VT);
1419   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1420     RRC = Subtarget->is64Bit() ?
1421       (const TargetRegisterClass*)&X86::GR64RegClass :
1422       (const TargetRegisterClass*)&X86::GR32RegClass;
1423     break;
1424   case MVT::x86mmx:
1425     RRC = &X86::VR64RegClass;
1426     break;
1427   case MVT::f32: case MVT::f64:
1428   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1429   case MVT::v4f32: case MVT::v2f64:
1430   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1431   case MVT::v4f64:
1432     RRC = &X86::VR128RegClass;
1433     break;
1434   }
1435   return std::make_pair(RRC, Cost);
1436 }
1437
1438 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1439                                                unsigned &Offset) const {
1440   if (!Subtarget->isTargetLinux())
1441     return false;
1442
1443   if (Subtarget->is64Bit()) {
1444     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1445     Offset = 0x28;
1446     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1447       AddressSpace = 256;
1448     else
1449       AddressSpace = 257;
1450   } else {
1451     // %gs:0x14 on i386
1452     Offset = 0x14;
1453     AddressSpace = 256;
1454   }
1455   return true;
1456 }
1457
1458
1459 //===----------------------------------------------------------------------===//
1460 //               Return Value Calling Convention Implementation
1461 //===----------------------------------------------------------------------===//
1462
1463 #include "X86GenCallingConv.inc"
1464
1465 bool
1466 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1467                                   MachineFunction &MF, bool isVarArg,
1468                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1469                         LLVMContext &Context) const {
1470   SmallVector<CCValAssign, 16> RVLocs;
1471   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1472                  RVLocs, Context);
1473   return CCInfo.CheckReturn(Outs, RetCC_X86);
1474 }
1475
1476 SDValue
1477 X86TargetLowering::LowerReturn(SDValue Chain,
1478                                CallingConv::ID CallConv, bool isVarArg,
1479                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1480                                const SmallVectorImpl<SDValue> &OutVals,
1481                                DebugLoc dl, SelectionDAG &DAG) const {
1482   MachineFunction &MF = DAG.getMachineFunction();
1483   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1484
1485   SmallVector<CCValAssign, 16> RVLocs;
1486   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1487                  RVLocs, *DAG.getContext());
1488   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1489
1490   // Add the regs to the liveout set for the function.
1491   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1492   for (unsigned i = 0; i != RVLocs.size(); ++i)
1493     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1494       MRI.addLiveOut(RVLocs[i].getLocReg());
1495
1496   SDValue Flag;
1497
1498   SmallVector<SDValue, 6> RetOps;
1499   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1500   // Operand #1 = Bytes To Pop
1501   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1502                    MVT::i16));
1503
1504   // Copy the result values into the output registers.
1505   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1506     CCValAssign &VA = RVLocs[i];
1507     assert(VA.isRegLoc() && "Can only return in registers!");
1508     SDValue ValToCopy = OutVals[i];
1509     EVT ValVT = ValToCopy.getValueType();
1510
1511     // Promote values to the appropriate types
1512     if (VA.getLocInfo() == CCValAssign::SExt)
1513       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1514     else if (VA.getLocInfo() == CCValAssign::ZExt)
1515       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1516     else if (VA.getLocInfo() == CCValAssign::AExt)
1517       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1518     else if (VA.getLocInfo() == CCValAssign::BCvt)
1519       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1520
1521     // If this is x86-64, and we disabled SSE, we can't return FP values,
1522     // or SSE or MMX vectors.
1523     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1524          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1525           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1526       report_fatal_error("SSE register return with SSE disabled");
1527     }
1528     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1529     // llvm-gcc has never done it right and no one has noticed, so this
1530     // should be OK for now.
1531     if (ValVT == MVT::f64 &&
1532         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1533       report_fatal_error("SSE2 register return with SSE2 disabled");
1534
1535     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1536     // the RET instruction and handled by the FP Stackifier.
1537     if (VA.getLocReg() == X86::ST0 ||
1538         VA.getLocReg() == X86::ST1) {
1539       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1540       // change the value to the FP stack register class.
1541       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1542         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1543       RetOps.push_back(ValToCopy);
1544       // Don't emit a copytoreg.
1545       continue;
1546     }
1547
1548     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1549     // which is returned in RAX / RDX.
1550     if (Subtarget->is64Bit()) {
1551       if (ValVT == MVT::x86mmx) {
1552         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1553           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1554           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1555                                   ValToCopy);
1556           // If we don't have SSE2 available, convert to v4f32 so the generated
1557           // register is legal.
1558           if (!Subtarget->hasSSE2())
1559             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1560         }
1561       }
1562     }
1563
1564     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1565     Flag = Chain.getValue(1);
1566   }
1567
1568   // The x86-64 ABI for returning structs by value requires that we copy
1569   // the sret argument into %rax for the return. We saved the argument into
1570   // a virtual register in the entry block, so now we copy the value out
1571   // and into %rax.
1572   if (Subtarget->is64Bit() &&
1573       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1574     MachineFunction &MF = DAG.getMachineFunction();
1575     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1576     unsigned Reg = FuncInfo->getSRetReturnReg();
1577     assert(Reg &&
1578            "SRetReturnReg should have been set in LowerFormalArguments().");
1579     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1580
1581     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1582     Flag = Chain.getValue(1);
1583
1584     // RAX now acts like a return value.
1585     MRI.addLiveOut(X86::RAX);
1586   }
1587
1588   RetOps[0] = Chain;  // Update chain.
1589
1590   // Add the flag if we have it.
1591   if (Flag.getNode())
1592     RetOps.push_back(Flag);
1593
1594   return DAG.getNode(X86ISD::RET_FLAG, dl,
1595                      MVT::Other, &RetOps[0], RetOps.size());
1596 }
1597
1598 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1599   if (N->getNumValues() != 1)
1600     return false;
1601   if (!N->hasNUsesOfValue(1, 0))
1602     return false;
1603
1604   SDValue TCChain = Chain;
1605   SDNode *Copy = *N->use_begin();
1606   if (Copy->getOpcode() == ISD::CopyToReg) {
1607     // If the copy has a glue operand, we conservatively assume it isn't safe to
1608     // perform a tail call.
1609     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1610       return false;
1611     TCChain = Copy->getOperand(0);
1612   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1613     return false;
1614
1615   bool HasRet = false;
1616   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1617        UI != UE; ++UI) {
1618     if (UI->getOpcode() != X86ISD::RET_FLAG)
1619       return false;
1620     HasRet = true;
1621   }
1622
1623   if (!HasRet)
1624     return false;
1625
1626   Chain = TCChain;
1627   return true;
1628 }
1629
1630 EVT
1631 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1632                                             ISD::NodeType ExtendKind) const {
1633   MVT ReturnMVT;
1634   // TODO: Is this also valid on 32-bit?
1635   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1636     ReturnMVT = MVT::i8;
1637   else
1638     ReturnMVT = MVT::i32;
1639
1640   EVT MinVT = getRegisterType(Context, ReturnMVT);
1641   return VT.bitsLT(MinVT) ? MinVT : VT;
1642 }
1643
1644 /// LowerCallResult - Lower the result values of a call into the
1645 /// appropriate copies out of appropriate physical registers.
1646 ///
1647 SDValue
1648 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1649                                    CallingConv::ID CallConv, bool isVarArg,
1650                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1651                                    DebugLoc dl, SelectionDAG &DAG,
1652                                    SmallVectorImpl<SDValue> &InVals) const {
1653
1654   // Assign locations to each value returned by this call.
1655   SmallVector<CCValAssign, 16> RVLocs;
1656   bool Is64Bit = Subtarget->is64Bit();
1657   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1658                  getTargetMachine(), RVLocs, *DAG.getContext());
1659   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1660
1661   // Copy all of the result registers out of their specified physreg.
1662   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1663     CCValAssign &VA = RVLocs[i];
1664     EVT CopyVT = VA.getValVT();
1665
1666     // If this is x86-64, and we disabled SSE, we can't return FP values
1667     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1668         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1669       report_fatal_error("SSE register return with SSE disabled");
1670     }
1671
1672     SDValue Val;
1673
1674     // If this is a call to a function that returns an fp value on the floating
1675     // point stack, we must guarantee the the value is popped from the stack, so
1676     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1677     // if the return value is not used. We use the FpPOP_RETVAL instruction
1678     // instead.
1679     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1680       // If we prefer to use the value in xmm registers, copy it out as f80 and
1681       // use a truncate to move it from fp stack reg to xmm reg.
1682       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1683       SDValue Ops[] = { Chain, InFlag };
1684       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1685                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1686       Val = Chain.getValue(0);
1687
1688       // Round the f80 to the right size, which also moves it to the appropriate
1689       // xmm register.
1690       if (CopyVT != VA.getValVT())
1691         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1692                           // This truncation won't change the value.
1693                           DAG.getIntPtrConstant(1));
1694     } else {
1695       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1696                                  CopyVT, InFlag).getValue(1);
1697       Val = Chain.getValue(0);
1698     }
1699     InFlag = Chain.getValue(2);
1700     InVals.push_back(Val);
1701   }
1702
1703   return Chain;
1704 }
1705
1706
1707 //===----------------------------------------------------------------------===//
1708 //                C & StdCall & Fast Calling Convention implementation
1709 //===----------------------------------------------------------------------===//
1710 //  StdCall calling convention seems to be standard for many Windows' API
1711 //  routines and around. It differs from C calling convention just a little:
1712 //  callee should clean up the stack, not caller. Symbols should be also
1713 //  decorated in some fancy way :) It doesn't support any vector arguments.
1714 //  For info on fast calling convention see Fast Calling Convention (tail call)
1715 //  implementation LowerX86_32FastCCCallTo.
1716
1717 /// CallIsStructReturn - Determines whether a call uses struct return
1718 /// semantics.
1719 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1720   if (Outs.empty())
1721     return false;
1722
1723   return Outs[0].Flags.isSRet();
1724 }
1725
1726 /// ArgsAreStructReturn - Determines whether a function uses struct
1727 /// return semantics.
1728 static bool
1729 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1730   if (Ins.empty())
1731     return false;
1732
1733   return Ins[0].Flags.isSRet();
1734 }
1735
1736 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1737 /// by "Src" to address "Dst" with size and alignment information specified by
1738 /// the specific parameter attribute. The copy will be passed as a byval
1739 /// function parameter.
1740 static SDValue
1741 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1742                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1743                           DebugLoc dl) {
1744   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1745
1746   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1747                        /*isVolatile*/false, /*AlwaysInline=*/true,
1748                        MachinePointerInfo(), MachinePointerInfo());
1749 }
1750
1751 /// IsTailCallConvention - Return true if the calling convention is one that
1752 /// supports tail call optimization.
1753 static bool IsTailCallConvention(CallingConv::ID CC) {
1754   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1755 }
1756
1757 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1758   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1759     return false;
1760
1761   CallSite CS(CI);
1762   CallingConv::ID CalleeCC = CS.getCallingConv();
1763   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1764     return false;
1765
1766   return true;
1767 }
1768
1769 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1770 /// a tailcall target by changing its ABI.
1771 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1772                                    bool GuaranteedTailCallOpt) {
1773   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1774 }
1775
1776 SDValue
1777 X86TargetLowering::LowerMemArgument(SDValue Chain,
1778                                     CallingConv::ID CallConv,
1779                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1780                                     DebugLoc dl, SelectionDAG &DAG,
1781                                     const CCValAssign &VA,
1782                                     MachineFrameInfo *MFI,
1783                                     unsigned i) const {
1784   // Create the nodes corresponding to a load from this parameter slot.
1785   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1786   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1787                               getTargetMachine().Options.GuaranteedTailCallOpt);
1788   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1789   EVT ValVT;
1790
1791   // If value is passed by pointer we have address passed instead of the value
1792   // itself.
1793   if (VA.getLocInfo() == CCValAssign::Indirect)
1794     ValVT = VA.getLocVT();
1795   else
1796     ValVT = VA.getValVT();
1797
1798   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1799   // changed with more analysis.
1800   // In case of tail call optimization mark all arguments mutable. Since they
1801   // could be overwritten by lowering of arguments in case of a tail call.
1802   if (Flags.isByVal()) {
1803     unsigned Bytes = Flags.getByValSize();
1804     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1805     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1806     return DAG.getFrameIndex(FI, getPointerTy());
1807   } else {
1808     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1809                                     VA.getLocMemOffset(), isImmutable);
1810     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1811     return DAG.getLoad(ValVT, dl, Chain, FIN,
1812                        MachinePointerInfo::getFixedStack(FI),
1813                        false, false, false, 0);
1814   }
1815 }
1816
1817 SDValue
1818 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1819                                         CallingConv::ID CallConv,
1820                                         bool isVarArg,
1821                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1822                                         DebugLoc dl,
1823                                         SelectionDAG &DAG,
1824                                         SmallVectorImpl<SDValue> &InVals)
1825                                           const {
1826   MachineFunction &MF = DAG.getMachineFunction();
1827   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1828
1829   const Function* Fn = MF.getFunction();
1830   if (Fn->hasExternalLinkage() &&
1831       Subtarget->isTargetCygMing() &&
1832       Fn->getName() == "main")
1833     FuncInfo->setForceFramePointer(true);
1834
1835   MachineFrameInfo *MFI = MF.getFrameInfo();
1836   bool Is64Bit = Subtarget->is64Bit();
1837   bool IsWindows = Subtarget->isTargetWindows();
1838   bool IsWin64 = Subtarget->isTargetWin64();
1839
1840   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1841          "Var args not supported with calling convention fastcc or ghc");
1842
1843   // Assign locations to all of the incoming arguments.
1844   SmallVector<CCValAssign, 16> ArgLocs;
1845   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1846                  ArgLocs, *DAG.getContext());
1847
1848   // Allocate shadow area for Win64
1849   if (IsWin64) {
1850     CCInfo.AllocateStack(32, 8);
1851   }
1852
1853   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1854
1855   unsigned LastVal = ~0U;
1856   SDValue ArgValue;
1857   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1858     CCValAssign &VA = ArgLocs[i];
1859     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1860     // places.
1861     assert(VA.getValNo() != LastVal &&
1862            "Don't support value assigned to multiple locs yet");
1863     (void)LastVal;
1864     LastVal = VA.getValNo();
1865
1866     if (VA.isRegLoc()) {
1867       EVT RegVT = VA.getLocVT();
1868       const TargetRegisterClass *RC;
1869       if (RegVT == MVT::i32)
1870         RC = &X86::GR32RegClass;
1871       else if (Is64Bit && RegVT == MVT::i64)
1872         RC = &X86::GR64RegClass;
1873       else if (RegVT == MVT::f32)
1874         RC = &X86::FR32RegClass;
1875       else if (RegVT == MVT::f64)
1876         RC = &X86::FR64RegClass;
1877       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1878         RC = &X86::VR256RegClass;
1879       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1880         RC = &X86::VR128RegClass;
1881       else if (RegVT == MVT::x86mmx)
1882         RC = &X86::VR64RegClass;
1883       else
1884         llvm_unreachable("Unknown argument type!");
1885
1886       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1887       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1888
1889       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1890       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1891       // right size.
1892       if (VA.getLocInfo() == CCValAssign::SExt)
1893         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1894                                DAG.getValueType(VA.getValVT()));
1895       else if (VA.getLocInfo() == CCValAssign::ZExt)
1896         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1897                                DAG.getValueType(VA.getValVT()));
1898       else if (VA.getLocInfo() == CCValAssign::BCvt)
1899         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1900
1901       if (VA.isExtInLoc()) {
1902         // Handle MMX values passed in XMM regs.
1903         if (RegVT.isVector()) {
1904           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1905                                  ArgValue);
1906         } else
1907           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1908       }
1909     } else {
1910       assert(VA.isMemLoc());
1911       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1912     }
1913
1914     // If value is passed via pointer - do a load.
1915     if (VA.getLocInfo() == CCValAssign::Indirect)
1916       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1917                              MachinePointerInfo(), false, false, false, 0);
1918
1919     InVals.push_back(ArgValue);
1920   }
1921
1922   // The x86-64 ABI for returning structs by value requires that we copy
1923   // the sret argument into %rax for the return. Save the argument into
1924   // a virtual register so that we can access it from the return points.
1925   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1926     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1927     unsigned Reg = FuncInfo->getSRetReturnReg();
1928     if (!Reg) {
1929       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1930       FuncInfo->setSRetReturnReg(Reg);
1931     }
1932     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1933     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1934   }
1935
1936   unsigned StackSize = CCInfo.getNextStackOffset();
1937   // Align stack specially for tail calls.
1938   if (FuncIsMadeTailCallSafe(CallConv,
1939                              MF.getTarget().Options.GuaranteedTailCallOpt))
1940     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1941
1942   // If the function takes variable number of arguments, make a frame index for
1943   // the start of the first vararg value... for expansion of llvm.va_start.
1944   if (isVarArg) {
1945     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1946                     CallConv != CallingConv::X86_ThisCall)) {
1947       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1948     }
1949     if (Is64Bit) {
1950       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1951
1952       // FIXME: We should really autogenerate these arrays
1953       static const uint16_t GPR64ArgRegsWin64[] = {
1954         X86::RCX, X86::RDX, X86::R8,  X86::R9
1955       };
1956       static const uint16_t GPR64ArgRegs64Bit[] = {
1957         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1958       };
1959       static const uint16_t XMMArgRegs64Bit[] = {
1960         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1961         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1962       };
1963       const uint16_t *GPR64ArgRegs;
1964       unsigned NumXMMRegs = 0;
1965
1966       if (IsWin64) {
1967         // The XMM registers which might contain var arg parameters are shadowed
1968         // in their paired GPR.  So we only need to save the GPR to their home
1969         // slots.
1970         TotalNumIntRegs = 4;
1971         GPR64ArgRegs = GPR64ArgRegsWin64;
1972       } else {
1973         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1974         GPR64ArgRegs = GPR64ArgRegs64Bit;
1975
1976         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1977                                                 TotalNumXMMRegs);
1978       }
1979       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1980                                                        TotalNumIntRegs);
1981
1982       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1983       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1984              "SSE register cannot be used when SSE is disabled!");
1985       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1986                NoImplicitFloatOps) &&
1987              "SSE register cannot be used when SSE is disabled!");
1988       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1989           !Subtarget->hasSSE1())
1990         // Kernel mode asks for SSE to be disabled, so don't push them
1991         // on the stack.
1992         TotalNumXMMRegs = 0;
1993
1994       if (IsWin64) {
1995         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1996         // Get to the caller-allocated home save location.  Add 8 to account
1997         // for the return address.
1998         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1999         FuncInfo->setRegSaveFrameIndex(
2000           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2001         // Fixup to set vararg frame on shadow area (4 x i64).
2002         if (NumIntRegs < 4)
2003           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2004       } else {
2005         // For X86-64, if there are vararg parameters that are passed via
2006         // registers, then we must store them to their spots on the stack so
2007         // they may be loaded by deferencing the result of va_next.
2008         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2009         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2010         FuncInfo->setRegSaveFrameIndex(
2011           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2012                                false));
2013       }
2014
2015       // Store the integer parameter registers.
2016       SmallVector<SDValue, 8> MemOps;
2017       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2018                                         getPointerTy());
2019       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2020       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2021         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2022                                   DAG.getIntPtrConstant(Offset));
2023         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2024                                      &X86::GR64RegClass);
2025         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2026         SDValue Store =
2027           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2028                        MachinePointerInfo::getFixedStack(
2029                          FuncInfo->getRegSaveFrameIndex(), Offset),
2030                        false, false, 0);
2031         MemOps.push_back(Store);
2032         Offset += 8;
2033       }
2034
2035       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2036         // Now store the XMM (fp + vector) parameter registers.
2037         SmallVector<SDValue, 11> SaveXMMOps;
2038         SaveXMMOps.push_back(Chain);
2039
2040         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2041         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2042         SaveXMMOps.push_back(ALVal);
2043
2044         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2045                                FuncInfo->getRegSaveFrameIndex()));
2046         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2047                                FuncInfo->getVarArgsFPOffset()));
2048
2049         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2050           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2051                                        &X86::VR128RegClass);
2052           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2053           SaveXMMOps.push_back(Val);
2054         }
2055         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2056                                      MVT::Other,
2057                                      &SaveXMMOps[0], SaveXMMOps.size()));
2058       }
2059
2060       if (!MemOps.empty())
2061         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2062                             &MemOps[0], MemOps.size());
2063     }
2064   }
2065
2066   // Some CCs need callee pop.
2067   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2068                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2069     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2070   } else {
2071     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2072     // If this is an sret function, the return should pop the hidden pointer.
2073     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2074         ArgsAreStructReturn(Ins))
2075       FuncInfo->setBytesToPopOnReturn(4);
2076   }
2077
2078   if (!Is64Bit) {
2079     // RegSaveFrameIndex is X86-64 only.
2080     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2081     if (CallConv == CallingConv::X86_FastCall ||
2082         CallConv == CallingConv::X86_ThisCall)
2083       // fastcc functions can't have varargs.
2084       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2085   }
2086
2087   FuncInfo->setArgumentStackSize(StackSize);
2088
2089   return Chain;
2090 }
2091
2092 SDValue
2093 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2094                                     SDValue StackPtr, SDValue Arg,
2095                                     DebugLoc dl, SelectionDAG &DAG,
2096                                     const CCValAssign &VA,
2097                                     ISD::ArgFlagsTy Flags) const {
2098   unsigned LocMemOffset = VA.getLocMemOffset();
2099   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2100   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2101   if (Flags.isByVal())
2102     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2103
2104   return DAG.getStore(Chain, dl, Arg, PtrOff,
2105                       MachinePointerInfo::getStack(LocMemOffset),
2106                       false, false, 0);
2107 }
2108
2109 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2110 /// optimization is performed and it is required.
2111 SDValue
2112 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2113                                            SDValue &OutRetAddr, SDValue Chain,
2114                                            bool IsTailCall, bool Is64Bit,
2115                                            int FPDiff, DebugLoc dl) const {
2116   // Adjust the Return address stack slot.
2117   EVT VT = getPointerTy();
2118   OutRetAddr = getReturnAddressFrameIndex(DAG);
2119
2120   // Load the "old" Return address.
2121   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2122                            false, false, false, 0);
2123   return SDValue(OutRetAddr.getNode(), 1);
2124 }
2125
2126 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2127 /// optimization is performed and it is required (FPDiff!=0).
2128 static SDValue
2129 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2130                          SDValue Chain, SDValue RetAddrFrIdx,
2131                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2132   // Store the return address to the appropriate stack slot.
2133   if (!FPDiff) return Chain;
2134   // Calculate the new stack slot for the return address.
2135   int SlotSize = Is64Bit ? 8 : 4;
2136   int NewReturnAddrFI =
2137     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2138   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2139   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2140   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2141                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2142                        false, false, 0);
2143   return Chain;
2144 }
2145
2146 SDValue
2147 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2148                              SmallVectorImpl<SDValue> &InVals) const {
2149   SelectionDAG &DAG                     = CLI.DAG;
2150   DebugLoc &dl                          = CLI.DL;
2151   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2152   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2153   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2154   SDValue Chain                         = CLI.Chain;
2155   SDValue Callee                        = CLI.Callee;
2156   CallingConv::ID CallConv              = CLI.CallConv;
2157   bool &isTailCall                      = CLI.IsTailCall;
2158   bool isVarArg                         = CLI.IsVarArg;
2159
2160   MachineFunction &MF = DAG.getMachineFunction();
2161   bool Is64Bit        = Subtarget->is64Bit();
2162   bool IsWin64        = Subtarget->isTargetWin64();
2163   bool IsWindows      = Subtarget->isTargetWindows();
2164   bool IsStructRet    = CallIsStructReturn(Outs);
2165   bool IsSibcall      = false;
2166
2167   if (MF.getTarget().Options.DisableTailCalls)
2168     isTailCall = false;
2169
2170   if (isTailCall) {
2171     // Check if it's really possible to do a tail call.
2172     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2173                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2174                                                    Outs, OutVals, Ins, DAG);
2175
2176     // Sibcalls are automatically detected tailcalls which do not require
2177     // ABI changes.
2178     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2179       IsSibcall = true;
2180
2181     if (isTailCall)
2182       ++NumTailCalls;
2183   }
2184
2185   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2186          "Var args not supported with calling convention fastcc or ghc");
2187
2188   // Analyze operands of the call, assigning locations to each operand.
2189   SmallVector<CCValAssign, 16> ArgLocs;
2190   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2191                  ArgLocs, *DAG.getContext());
2192
2193   // Allocate shadow area for Win64
2194   if (IsWin64) {
2195     CCInfo.AllocateStack(32, 8);
2196   }
2197
2198   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2199
2200   // Get a count of how many bytes are to be pushed on the stack.
2201   unsigned NumBytes = CCInfo.getNextStackOffset();
2202   if (IsSibcall)
2203     // This is a sibcall. The memory operands are available in caller's
2204     // own caller's stack.
2205     NumBytes = 0;
2206   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2207            IsTailCallConvention(CallConv))
2208     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2209
2210   int FPDiff = 0;
2211   if (isTailCall && !IsSibcall) {
2212     // Lower arguments at fp - stackoffset + fpdiff.
2213     unsigned NumBytesCallerPushed =
2214       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2215     FPDiff = NumBytesCallerPushed - NumBytes;
2216
2217     // Set the delta of movement of the returnaddr stackslot.
2218     // But only set if delta is greater than previous delta.
2219     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2220       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2221   }
2222
2223   if (!IsSibcall)
2224     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2225
2226   SDValue RetAddrFrIdx;
2227   // Load return address for tail calls.
2228   if (isTailCall && FPDiff)
2229     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2230                                     Is64Bit, FPDiff, dl);
2231
2232   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2233   SmallVector<SDValue, 8> MemOpChains;
2234   SDValue StackPtr;
2235
2236   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2237   // of tail call optimization arguments are handle later.
2238   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2239     CCValAssign &VA = ArgLocs[i];
2240     EVT RegVT = VA.getLocVT();
2241     SDValue Arg = OutVals[i];
2242     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2243     bool isByVal = Flags.isByVal();
2244
2245     // Promote the value if needed.
2246     switch (VA.getLocInfo()) {
2247     default: llvm_unreachable("Unknown loc info!");
2248     case CCValAssign::Full: break;
2249     case CCValAssign::SExt:
2250       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2251       break;
2252     case CCValAssign::ZExt:
2253       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2254       break;
2255     case CCValAssign::AExt:
2256       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2257         // Special case: passing MMX values in XMM registers.
2258         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2259         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2260         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2261       } else
2262         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2263       break;
2264     case CCValAssign::BCvt:
2265       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2266       break;
2267     case CCValAssign::Indirect: {
2268       // Store the argument.
2269       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2270       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2271       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2272                            MachinePointerInfo::getFixedStack(FI),
2273                            false, false, 0);
2274       Arg = SpillSlot;
2275       break;
2276     }
2277     }
2278
2279     if (VA.isRegLoc()) {
2280       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2281       if (isVarArg && IsWin64) {
2282         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2283         // shadow reg if callee is a varargs function.
2284         unsigned ShadowReg = 0;
2285         switch (VA.getLocReg()) {
2286         case X86::XMM0: ShadowReg = X86::RCX; break;
2287         case X86::XMM1: ShadowReg = X86::RDX; break;
2288         case X86::XMM2: ShadowReg = X86::R8; break;
2289         case X86::XMM3: ShadowReg = X86::R9; break;
2290         }
2291         if (ShadowReg)
2292           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2293       }
2294     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2295       assert(VA.isMemLoc());
2296       if (StackPtr.getNode() == 0)
2297         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2298       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2299                                              dl, DAG, VA, Flags));
2300     }
2301   }
2302
2303   if (!MemOpChains.empty())
2304     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2305                         &MemOpChains[0], MemOpChains.size());
2306
2307   // Build a sequence of copy-to-reg nodes chained together with token chain
2308   // and flag operands which copy the outgoing args into registers.
2309   SDValue InFlag;
2310   // Tail call byval lowering might overwrite argument registers so in case of
2311   // tail call optimization the copies to registers are lowered later.
2312   if (!isTailCall)
2313     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2314       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2315                                RegsToPass[i].second, InFlag);
2316       InFlag = Chain.getValue(1);
2317     }
2318
2319   if (Subtarget->isPICStyleGOT()) {
2320     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2321     // GOT pointer.
2322     if (!isTailCall) {
2323       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2324                                DAG.getNode(X86ISD::GlobalBaseReg,
2325                                            DebugLoc(), getPointerTy()),
2326                                InFlag);
2327       InFlag = Chain.getValue(1);
2328     } else {
2329       // If we are tail calling and generating PIC/GOT style code load the
2330       // address of the callee into ECX. The value in ecx is used as target of
2331       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2332       // for tail calls on PIC/GOT architectures. Normally we would just put the
2333       // address of GOT into ebx and then call target@PLT. But for tail calls
2334       // ebx would be restored (since ebx is callee saved) before jumping to the
2335       // target@PLT.
2336
2337       // Note: The actual moving to ECX is done further down.
2338       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2339       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2340           !G->getGlobal()->hasProtectedVisibility())
2341         Callee = LowerGlobalAddress(Callee, DAG);
2342       else if (isa<ExternalSymbolSDNode>(Callee))
2343         Callee = LowerExternalSymbol(Callee, DAG);
2344     }
2345   }
2346
2347   if (Is64Bit && isVarArg && !IsWin64) {
2348     // From AMD64 ABI document:
2349     // For calls that may call functions that use varargs or stdargs
2350     // (prototype-less calls or calls to functions containing ellipsis (...) in
2351     // the declaration) %al is used as hidden argument to specify the number
2352     // of SSE registers used. The contents of %al do not need to match exactly
2353     // the number of registers, but must be an ubound on the number of SSE
2354     // registers used and is in the range 0 - 8 inclusive.
2355
2356     // Count the number of XMM registers allocated.
2357     static const uint16_t XMMArgRegs[] = {
2358       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2359       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2360     };
2361     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2362     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2363            && "SSE registers cannot be used when SSE is disabled");
2364
2365     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2366                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2367     InFlag = Chain.getValue(1);
2368   }
2369
2370
2371   // For tail calls lower the arguments to the 'real' stack slot.
2372   if (isTailCall) {
2373     // Force all the incoming stack arguments to be loaded from the stack
2374     // before any new outgoing arguments are stored to the stack, because the
2375     // outgoing stack slots may alias the incoming argument stack slots, and
2376     // the alias isn't otherwise explicit. This is slightly more conservative
2377     // than necessary, because it means that each store effectively depends
2378     // on every argument instead of just those arguments it would clobber.
2379     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2380
2381     SmallVector<SDValue, 8> MemOpChains2;
2382     SDValue FIN;
2383     int FI = 0;
2384     // Do not flag preceding copytoreg stuff together with the following stuff.
2385     InFlag = SDValue();
2386     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2387       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2388         CCValAssign &VA = ArgLocs[i];
2389         if (VA.isRegLoc())
2390           continue;
2391         assert(VA.isMemLoc());
2392         SDValue Arg = OutVals[i];
2393         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2394         // Create frame index.
2395         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2396         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2397         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2398         FIN = DAG.getFrameIndex(FI, getPointerTy());
2399
2400         if (Flags.isByVal()) {
2401           // Copy relative to framepointer.
2402           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2403           if (StackPtr.getNode() == 0)
2404             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2405                                           getPointerTy());
2406           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2407
2408           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2409                                                            ArgChain,
2410                                                            Flags, DAG, dl));
2411         } else {
2412           // Store relative to framepointer.
2413           MemOpChains2.push_back(
2414             DAG.getStore(ArgChain, dl, Arg, FIN,
2415                          MachinePointerInfo::getFixedStack(FI),
2416                          false, false, 0));
2417         }
2418       }
2419     }
2420
2421     if (!MemOpChains2.empty())
2422       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2423                           &MemOpChains2[0], MemOpChains2.size());
2424
2425     // Copy arguments to their registers.
2426     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2427       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2428                                RegsToPass[i].second, InFlag);
2429       InFlag = Chain.getValue(1);
2430     }
2431     InFlag =SDValue();
2432
2433     // Store the return address to the appropriate stack slot.
2434     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2435                                      FPDiff, dl);
2436   }
2437
2438   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2439     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2440     // In the 64-bit large code model, we have to make all calls
2441     // through a register, since the call instruction's 32-bit
2442     // pc-relative offset may not be large enough to hold the whole
2443     // address.
2444   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2445     // If the callee is a GlobalAddress node (quite common, every direct call
2446     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2447     // it.
2448
2449     // We should use extra load for direct calls to dllimported functions in
2450     // non-JIT mode.
2451     const GlobalValue *GV = G->getGlobal();
2452     if (!GV->hasDLLImportLinkage()) {
2453       unsigned char OpFlags = 0;
2454       bool ExtraLoad = false;
2455       unsigned WrapperKind = ISD::DELETED_NODE;
2456
2457       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2458       // external symbols most go through the PLT in PIC mode.  If the symbol
2459       // has hidden or protected visibility, or if it is static or local, then
2460       // we don't need to use the PLT - we can directly call it.
2461       if (Subtarget->isTargetELF() &&
2462           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2463           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2464         OpFlags = X86II::MO_PLT;
2465       } else if (Subtarget->isPICStyleStubAny() &&
2466                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2467                  (!Subtarget->getTargetTriple().isMacOSX() ||
2468                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2469         // PC-relative references to external symbols should go through $stub,
2470         // unless we're building with the leopard linker or later, which
2471         // automatically synthesizes these stubs.
2472         OpFlags = X86II::MO_DARWIN_STUB;
2473       } else if (Subtarget->isPICStyleRIPRel() &&
2474                  isa<Function>(GV) &&
2475                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2476         // If the function is marked as non-lazy, generate an indirect call
2477         // which loads from the GOT directly. This avoids runtime overhead
2478         // at the cost of eager binding (and one extra byte of encoding).
2479         OpFlags = X86II::MO_GOTPCREL;
2480         WrapperKind = X86ISD::WrapperRIP;
2481         ExtraLoad = true;
2482       }
2483
2484       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2485                                           G->getOffset(), OpFlags);
2486
2487       // Add a wrapper if needed.
2488       if (WrapperKind != ISD::DELETED_NODE)
2489         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2490       // Add extra indirection if needed.
2491       if (ExtraLoad)
2492         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2493                              MachinePointerInfo::getGOT(),
2494                              false, false, false, 0);
2495     }
2496   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2497     unsigned char OpFlags = 0;
2498
2499     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2500     // external symbols should go through the PLT.
2501     if (Subtarget->isTargetELF() &&
2502         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2503       OpFlags = X86II::MO_PLT;
2504     } else if (Subtarget->isPICStyleStubAny() &&
2505                (!Subtarget->getTargetTriple().isMacOSX() ||
2506                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2507       // PC-relative references to external symbols should go through $stub,
2508       // unless we're building with the leopard linker or later, which
2509       // automatically synthesizes these stubs.
2510       OpFlags = X86II::MO_DARWIN_STUB;
2511     }
2512
2513     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2514                                          OpFlags);
2515   }
2516
2517   // Returns a chain & a flag for retval copy to use.
2518   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2519   SmallVector<SDValue, 8> Ops;
2520
2521   if (!IsSibcall && isTailCall) {
2522     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2523                            DAG.getIntPtrConstant(0, true), InFlag);
2524     InFlag = Chain.getValue(1);
2525   }
2526
2527   Ops.push_back(Chain);
2528   Ops.push_back(Callee);
2529
2530   if (isTailCall)
2531     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2532
2533   // Add argument registers to the end of the list so that they are known live
2534   // into the call.
2535   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2536     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2537                                   RegsToPass[i].second.getValueType()));
2538
2539   // Add an implicit use GOT pointer in EBX.
2540   if (!isTailCall && Subtarget->isPICStyleGOT())
2541     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2542
2543   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2544   if (Is64Bit && isVarArg && !IsWin64)
2545     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2546
2547   // Add a register mask operand representing the call-preserved registers.
2548   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2549   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2550   assert(Mask && "Missing call preserved mask for calling convention");
2551   Ops.push_back(DAG.getRegisterMask(Mask));
2552
2553   if (InFlag.getNode())
2554     Ops.push_back(InFlag);
2555
2556   if (isTailCall) {
2557     // We used to do:
2558     //// If this is the first return lowered for this function, add the regs
2559     //// to the liveout set for the function.
2560     // This isn't right, although it's probably harmless on x86; liveouts
2561     // should be computed from returns not tail calls.  Consider a void
2562     // function making a tail call to a function returning int.
2563     return DAG.getNode(X86ISD::TC_RETURN, dl,
2564                        NodeTys, &Ops[0], Ops.size());
2565   }
2566
2567   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2568   InFlag = Chain.getValue(1);
2569
2570   // Create the CALLSEQ_END node.
2571   unsigned NumBytesForCalleeToPush;
2572   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2573                        getTargetMachine().Options.GuaranteedTailCallOpt))
2574     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2575   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2576            IsStructRet)
2577     // If this is a call to a struct-return function, the callee
2578     // pops the hidden struct pointer, so we have to push it back.
2579     // This is common for Darwin/X86, Linux & Mingw32 targets.
2580     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2581     NumBytesForCalleeToPush = 4;
2582   else
2583     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2584
2585   // Returns a flag for retval copy to use.
2586   if (!IsSibcall) {
2587     Chain = DAG.getCALLSEQ_END(Chain,
2588                                DAG.getIntPtrConstant(NumBytes, true),
2589                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2590                                                      true),
2591                                InFlag);
2592     InFlag = Chain.getValue(1);
2593   }
2594
2595   // Handle result values, copying them out of physregs into vregs that we
2596   // return.
2597   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2598                          Ins, dl, DAG, InVals);
2599 }
2600
2601
2602 //===----------------------------------------------------------------------===//
2603 //                Fast Calling Convention (tail call) implementation
2604 //===----------------------------------------------------------------------===//
2605
2606 //  Like std call, callee cleans arguments, convention except that ECX is
2607 //  reserved for storing the tail called function address. Only 2 registers are
2608 //  free for argument passing (inreg). Tail call optimization is performed
2609 //  provided:
2610 //                * tailcallopt is enabled
2611 //                * caller/callee are fastcc
2612 //  On X86_64 architecture with GOT-style position independent code only local
2613 //  (within module) calls are supported at the moment.
2614 //  To keep the stack aligned according to platform abi the function
2615 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2616 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2617 //  If a tail called function callee has more arguments than the caller the
2618 //  caller needs to make sure that there is room to move the RETADDR to. This is
2619 //  achieved by reserving an area the size of the argument delta right after the
2620 //  original REtADDR, but before the saved framepointer or the spilled registers
2621 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2622 //  stack layout:
2623 //    arg1
2624 //    arg2
2625 //    RETADDR
2626 //    [ new RETADDR
2627 //      move area ]
2628 //    (possible EBP)
2629 //    ESI
2630 //    EDI
2631 //    local1 ..
2632
2633 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2634 /// for a 16 byte align requirement.
2635 unsigned
2636 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2637                                                SelectionDAG& DAG) const {
2638   MachineFunction &MF = DAG.getMachineFunction();
2639   const TargetMachine &TM = MF.getTarget();
2640   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2641   unsigned StackAlignment = TFI.getStackAlignment();
2642   uint64_t AlignMask = StackAlignment - 1;
2643   int64_t Offset = StackSize;
2644   uint64_t SlotSize = TD->getPointerSize();
2645   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2646     // Number smaller than 12 so just add the difference.
2647     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2648   } else {
2649     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2650     Offset = ((~AlignMask) & Offset) + StackAlignment +
2651       (StackAlignment-SlotSize);
2652   }
2653   return Offset;
2654 }
2655
2656 /// MatchingStackOffset - Return true if the given stack call argument is
2657 /// already available in the same position (relatively) of the caller's
2658 /// incoming argument stack.
2659 static
2660 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2661                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2662                          const X86InstrInfo *TII) {
2663   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2664   int FI = INT_MAX;
2665   if (Arg.getOpcode() == ISD::CopyFromReg) {
2666     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2667     if (!TargetRegisterInfo::isVirtualRegister(VR))
2668       return false;
2669     MachineInstr *Def = MRI->getVRegDef(VR);
2670     if (!Def)
2671       return false;
2672     if (!Flags.isByVal()) {
2673       if (!TII->isLoadFromStackSlot(Def, FI))
2674         return false;
2675     } else {
2676       unsigned Opcode = Def->getOpcode();
2677       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2678           Def->getOperand(1).isFI()) {
2679         FI = Def->getOperand(1).getIndex();
2680         Bytes = Flags.getByValSize();
2681       } else
2682         return false;
2683     }
2684   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2685     if (Flags.isByVal())
2686       // ByVal argument is passed in as a pointer but it's now being
2687       // dereferenced. e.g.
2688       // define @foo(%struct.X* %A) {
2689       //   tail call @bar(%struct.X* byval %A)
2690       // }
2691       return false;
2692     SDValue Ptr = Ld->getBasePtr();
2693     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2694     if (!FINode)
2695       return false;
2696     FI = FINode->getIndex();
2697   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2698     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2699     FI = FINode->getIndex();
2700     Bytes = Flags.getByValSize();
2701   } else
2702     return false;
2703
2704   assert(FI != INT_MAX);
2705   if (!MFI->isFixedObjectIndex(FI))
2706     return false;
2707   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2708 }
2709
2710 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2711 /// for tail call optimization. Targets which want to do tail call
2712 /// optimization should implement this function.
2713 bool
2714 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2715                                                      CallingConv::ID CalleeCC,
2716                                                      bool isVarArg,
2717                                                      bool isCalleeStructRet,
2718                                                      bool isCallerStructRet,
2719                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2720                                     const SmallVectorImpl<SDValue> &OutVals,
2721                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2722                                                      SelectionDAG& DAG) const {
2723   if (!IsTailCallConvention(CalleeCC) &&
2724       CalleeCC != CallingConv::C)
2725     return false;
2726
2727   // If -tailcallopt is specified, make fastcc functions tail-callable.
2728   const MachineFunction &MF = DAG.getMachineFunction();
2729   const Function *CallerF = DAG.getMachineFunction().getFunction();
2730   CallingConv::ID CallerCC = CallerF->getCallingConv();
2731   bool CCMatch = CallerCC == CalleeCC;
2732
2733   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2734     if (IsTailCallConvention(CalleeCC) && CCMatch)
2735       return true;
2736     return false;
2737   }
2738
2739   // Look for obvious safe cases to perform tail call optimization that do not
2740   // require ABI changes. This is what gcc calls sibcall.
2741
2742   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2743   // emit a special epilogue.
2744   if (RegInfo->needsStackRealignment(MF))
2745     return false;
2746
2747   // Also avoid sibcall optimization if either caller or callee uses struct
2748   // return semantics.
2749   if (isCalleeStructRet || isCallerStructRet)
2750     return false;
2751
2752   // An stdcall caller is expected to clean up its arguments; the callee
2753   // isn't going to do that.
2754   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2755     return false;
2756
2757   // Do not sibcall optimize vararg calls unless all arguments are passed via
2758   // registers.
2759   if (isVarArg && !Outs.empty()) {
2760
2761     // Optimizing for varargs on Win64 is unlikely to be safe without
2762     // additional testing.
2763     if (Subtarget->isTargetWin64())
2764       return false;
2765
2766     SmallVector<CCValAssign, 16> ArgLocs;
2767     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2768                    getTargetMachine(), ArgLocs, *DAG.getContext());
2769
2770     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2771     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2772       if (!ArgLocs[i].isRegLoc())
2773         return false;
2774   }
2775
2776   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2777   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2778   // this into a sibcall.
2779   bool Unused = false;
2780   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2781     if (!Ins[i].Used) {
2782       Unused = true;
2783       break;
2784     }
2785   }
2786   if (Unused) {
2787     SmallVector<CCValAssign, 16> RVLocs;
2788     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2789                    getTargetMachine(), RVLocs, *DAG.getContext());
2790     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2791     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2792       CCValAssign &VA = RVLocs[i];
2793       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2794         return false;
2795     }
2796   }
2797
2798   // If the calling conventions do not match, then we'd better make sure the
2799   // results are returned in the same way as what the caller expects.
2800   if (!CCMatch) {
2801     SmallVector<CCValAssign, 16> RVLocs1;
2802     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2803                     getTargetMachine(), RVLocs1, *DAG.getContext());
2804     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2805
2806     SmallVector<CCValAssign, 16> RVLocs2;
2807     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2808                     getTargetMachine(), RVLocs2, *DAG.getContext());
2809     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2810
2811     if (RVLocs1.size() != RVLocs2.size())
2812       return false;
2813     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2814       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2815         return false;
2816       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2817         return false;
2818       if (RVLocs1[i].isRegLoc()) {
2819         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2820           return false;
2821       } else {
2822         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2823           return false;
2824       }
2825     }
2826   }
2827
2828   // If the callee takes no arguments then go on to check the results of the
2829   // call.
2830   if (!Outs.empty()) {
2831     // Check if stack adjustment is needed. For now, do not do this if any
2832     // argument is passed on the stack.
2833     SmallVector<CCValAssign, 16> ArgLocs;
2834     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2835                    getTargetMachine(), ArgLocs, *DAG.getContext());
2836
2837     // Allocate shadow area for Win64
2838     if (Subtarget->isTargetWin64()) {
2839       CCInfo.AllocateStack(32, 8);
2840     }
2841
2842     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2843     if (CCInfo.getNextStackOffset()) {
2844       MachineFunction &MF = DAG.getMachineFunction();
2845       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2846         return false;
2847
2848       // Check if the arguments are already laid out in the right way as
2849       // the caller's fixed stack objects.
2850       MachineFrameInfo *MFI = MF.getFrameInfo();
2851       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2852       const X86InstrInfo *TII =
2853         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2854       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2855         CCValAssign &VA = ArgLocs[i];
2856         SDValue Arg = OutVals[i];
2857         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2858         if (VA.getLocInfo() == CCValAssign::Indirect)
2859           return false;
2860         if (!VA.isRegLoc()) {
2861           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2862                                    MFI, MRI, TII))
2863             return false;
2864         }
2865       }
2866     }
2867
2868     // If the tailcall address may be in a register, then make sure it's
2869     // possible to register allocate for it. In 32-bit, the call address can
2870     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2871     // callee-saved registers are restored. These happen to be the same
2872     // registers used to pass 'inreg' arguments so watch out for those.
2873     if (!Subtarget->is64Bit() &&
2874         !isa<GlobalAddressSDNode>(Callee) &&
2875         !isa<ExternalSymbolSDNode>(Callee)) {
2876       unsigned NumInRegs = 0;
2877       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2878         CCValAssign &VA = ArgLocs[i];
2879         if (!VA.isRegLoc())
2880           continue;
2881         unsigned Reg = VA.getLocReg();
2882         switch (Reg) {
2883         default: break;
2884         case X86::EAX: case X86::EDX: case X86::ECX:
2885           if (++NumInRegs == 3)
2886             return false;
2887           break;
2888         }
2889       }
2890     }
2891   }
2892
2893   return true;
2894 }
2895
2896 FastISel *
2897 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2898   return X86::createFastISel(funcInfo);
2899 }
2900
2901
2902 //===----------------------------------------------------------------------===//
2903 //                           Other Lowering Hooks
2904 //===----------------------------------------------------------------------===//
2905
2906 static bool MayFoldLoad(SDValue Op) {
2907   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2908 }
2909
2910 static bool MayFoldIntoStore(SDValue Op) {
2911   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2912 }
2913
2914 static bool isTargetShuffle(unsigned Opcode) {
2915   switch(Opcode) {
2916   default: return false;
2917   case X86ISD::PSHUFD:
2918   case X86ISD::PSHUFHW:
2919   case X86ISD::PSHUFLW:
2920   case X86ISD::SHUFP:
2921   case X86ISD::PALIGN:
2922   case X86ISD::MOVLHPS:
2923   case X86ISD::MOVLHPD:
2924   case X86ISD::MOVHLPS:
2925   case X86ISD::MOVLPS:
2926   case X86ISD::MOVLPD:
2927   case X86ISD::MOVSHDUP:
2928   case X86ISD::MOVSLDUP:
2929   case X86ISD::MOVDDUP:
2930   case X86ISD::MOVSS:
2931   case X86ISD::MOVSD:
2932   case X86ISD::UNPCKL:
2933   case X86ISD::UNPCKH:
2934   case X86ISD::VPERMILP:
2935   case X86ISD::VPERM2X128:
2936   case X86ISD::VPERMI:
2937     return true;
2938   }
2939 }
2940
2941 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2942                                     SDValue V1, SelectionDAG &DAG) {
2943   switch(Opc) {
2944   default: llvm_unreachable("Unknown x86 shuffle node");
2945   case X86ISD::MOVSHDUP:
2946   case X86ISD::MOVSLDUP:
2947   case X86ISD::MOVDDUP:
2948     return DAG.getNode(Opc, dl, VT, V1);
2949   }
2950 }
2951
2952 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2953                                     SDValue V1, unsigned TargetMask,
2954                                     SelectionDAG &DAG) {
2955   switch(Opc) {
2956   default: llvm_unreachable("Unknown x86 shuffle node");
2957   case X86ISD::PSHUFD:
2958   case X86ISD::PSHUFHW:
2959   case X86ISD::PSHUFLW:
2960   case X86ISD::VPERMILP:
2961   case X86ISD::VPERMI:
2962     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2963   }
2964 }
2965
2966 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2967                                     SDValue V1, SDValue V2, unsigned TargetMask,
2968                                     SelectionDAG &DAG) {
2969   switch(Opc) {
2970   default: llvm_unreachable("Unknown x86 shuffle node");
2971   case X86ISD::PALIGN:
2972   case X86ISD::SHUFP:
2973   case X86ISD::VPERM2X128:
2974     return DAG.getNode(Opc, dl, VT, V1, V2,
2975                        DAG.getConstant(TargetMask, MVT::i8));
2976   }
2977 }
2978
2979 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2980                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2981   switch(Opc) {
2982   default: llvm_unreachable("Unknown x86 shuffle node");
2983   case X86ISD::MOVLHPS:
2984   case X86ISD::MOVLHPD:
2985   case X86ISD::MOVHLPS:
2986   case X86ISD::MOVLPS:
2987   case X86ISD::MOVLPD:
2988   case X86ISD::MOVSS:
2989   case X86ISD::MOVSD:
2990   case X86ISD::UNPCKL:
2991   case X86ISD::UNPCKH:
2992     return DAG.getNode(Opc, dl, VT, V1, V2);
2993   }
2994 }
2995
2996 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2997   MachineFunction &MF = DAG.getMachineFunction();
2998   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2999   int ReturnAddrIndex = FuncInfo->getRAIndex();
3000
3001   if (ReturnAddrIndex == 0) {
3002     // Set up a frame object for the return address.
3003     uint64_t SlotSize = TD->getPointerSize();
3004     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3005                                                            false);
3006     FuncInfo->setRAIndex(ReturnAddrIndex);
3007   }
3008
3009   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3010 }
3011
3012
3013 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3014                                        bool hasSymbolicDisplacement) {
3015   // Offset should fit into 32 bit immediate field.
3016   if (!isInt<32>(Offset))
3017     return false;
3018
3019   // If we don't have a symbolic displacement - we don't have any extra
3020   // restrictions.
3021   if (!hasSymbolicDisplacement)
3022     return true;
3023
3024   // FIXME: Some tweaks might be needed for medium code model.
3025   if (M != CodeModel::Small && M != CodeModel::Kernel)
3026     return false;
3027
3028   // For small code model we assume that latest object is 16MB before end of 31
3029   // bits boundary. We may also accept pretty large negative constants knowing
3030   // that all objects are in the positive half of address space.
3031   if (M == CodeModel::Small && Offset < 16*1024*1024)
3032     return true;
3033
3034   // For kernel code model we know that all object resist in the negative half
3035   // of 32bits address space. We may not accept negative offsets, since they may
3036   // be just off and we may accept pretty large positive ones.
3037   if (M == CodeModel::Kernel && Offset > 0)
3038     return true;
3039
3040   return false;
3041 }
3042
3043 /// isCalleePop - Determines whether the callee is required to pop its
3044 /// own arguments. Callee pop is necessary to support tail calls.
3045 bool X86::isCalleePop(CallingConv::ID CallingConv,
3046                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3047   if (IsVarArg)
3048     return false;
3049
3050   switch (CallingConv) {
3051   default:
3052     return false;
3053   case CallingConv::X86_StdCall:
3054     return !is64Bit;
3055   case CallingConv::X86_FastCall:
3056     return !is64Bit;
3057   case CallingConv::X86_ThisCall:
3058     return !is64Bit;
3059   case CallingConv::Fast:
3060     return TailCallOpt;
3061   case CallingConv::GHC:
3062     return TailCallOpt;
3063   }
3064 }
3065
3066 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3067 /// specific condition code, returning the condition code and the LHS/RHS of the
3068 /// comparison to make.
3069 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3070                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3071   if (!isFP) {
3072     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3073       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3074         // X > -1   -> X == 0, jump !sign.
3075         RHS = DAG.getConstant(0, RHS.getValueType());
3076         return X86::COND_NS;
3077       }
3078       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3079         // X < 0   -> X == 0, jump on sign.
3080         return X86::COND_S;
3081       }
3082       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3083         // X < 1   -> X <= 0
3084         RHS = DAG.getConstant(0, RHS.getValueType());
3085         return X86::COND_LE;
3086       }
3087     }
3088
3089     switch (SetCCOpcode) {
3090     default: llvm_unreachable("Invalid integer condition!");
3091     case ISD::SETEQ:  return X86::COND_E;
3092     case ISD::SETGT:  return X86::COND_G;
3093     case ISD::SETGE:  return X86::COND_GE;
3094     case ISD::SETLT:  return X86::COND_L;
3095     case ISD::SETLE:  return X86::COND_LE;
3096     case ISD::SETNE:  return X86::COND_NE;
3097     case ISD::SETULT: return X86::COND_B;
3098     case ISD::SETUGT: return X86::COND_A;
3099     case ISD::SETULE: return X86::COND_BE;
3100     case ISD::SETUGE: return X86::COND_AE;
3101     }
3102   }
3103
3104   // First determine if it is required or is profitable to flip the operands.
3105
3106   // If LHS is a foldable load, but RHS is not, flip the condition.
3107   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3108       !ISD::isNON_EXTLoad(RHS.getNode())) {
3109     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3110     std::swap(LHS, RHS);
3111   }
3112
3113   switch (SetCCOpcode) {
3114   default: break;
3115   case ISD::SETOLT:
3116   case ISD::SETOLE:
3117   case ISD::SETUGT:
3118   case ISD::SETUGE:
3119     std::swap(LHS, RHS);
3120     break;
3121   }
3122
3123   // On a floating point condition, the flags are set as follows:
3124   // ZF  PF  CF   op
3125   //  0 | 0 | 0 | X > Y
3126   //  0 | 0 | 1 | X < Y
3127   //  1 | 0 | 0 | X == Y
3128   //  1 | 1 | 1 | unordered
3129   switch (SetCCOpcode) {
3130   default: llvm_unreachable("Condcode should be pre-legalized away");
3131   case ISD::SETUEQ:
3132   case ISD::SETEQ:   return X86::COND_E;
3133   case ISD::SETOLT:              // flipped
3134   case ISD::SETOGT:
3135   case ISD::SETGT:   return X86::COND_A;
3136   case ISD::SETOLE:              // flipped
3137   case ISD::SETOGE:
3138   case ISD::SETGE:   return X86::COND_AE;
3139   case ISD::SETUGT:              // flipped
3140   case ISD::SETULT:
3141   case ISD::SETLT:   return X86::COND_B;
3142   case ISD::SETUGE:              // flipped
3143   case ISD::SETULE:
3144   case ISD::SETLE:   return X86::COND_BE;
3145   case ISD::SETONE:
3146   case ISD::SETNE:   return X86::COND_NE;
3147   case ISD::SETUO:   return X86::COND_P;
3148   case ISD::SETO:    return X86::COND_NP;
3149   case ISD::SETOEQ:
3150   case ISD::SETUNE:  return X86::COND_INVALID;
3151   }
3152 }
3153
3154 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3155 /// code. Current x86 isa includes the following FP cmov instructions:
3156 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3157 static bool hasFPCMov(unsigned X86CC) {
3158   switch (X86CC) {
3159   default:
3160     return false;
3161   case X86::COND_B:
3162   case X86::COND_BE:
3163   case X86::COND_E:
3164   case X86::COND_P:
3165   case X86::COND_A:
3166   case X86::COND_AE:
3167   case X86::COND_NE:
3168   case X86::COND_NP:
3169     return true;
3170   }
3171 }
3172
3173 /// isFPImmLegal - Returns true if the target can instruction select the
3174 /// specified FP immediate natively. If false, the legalizer will
3175 /// materialize the FP immediate as a load from a constant pool.
3176 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3177   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3178     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3179       return true;
3180   }
3181   return false;
3182 }
3183
3184 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3185 /// the specified range (L, H].
3186 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3187   return (Val < 0) || (Val >= Low && Val < Hi);
3188 }
3189
3190 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3191 /// specified value.
3192 static bool isUndefOrEqual(int Val, int CmpVal) {
3193   if (Val < 0 || Val == CmpVal)
3194     return true;
3195   return false;
3196 }
3197
3198 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3199 /// from position Pos and ending in Pos+Size, falls within the specified
3200 /// sequential range (L, L+Pos]. or is undef.
3201 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3202                                        unsigned Pos, unsigned Size, int Low) {
3203   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3204     if (!isUndefOrEqual(Mask[i], Low))
3205       return false;
3206   return true;
3207 }
3208
3209 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3210 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3211 /// the second operand.
3212 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3213   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3214     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3215   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3216     return (Mask[0] < 2 && Mask[1] < 2);
3217   return false;
3218 }
3219
3220 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3221 /// is suitable for input to PSHUFHW.
3222 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3223   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3224     return false;
3225
3226   // Lower quadword copied in order or undef.
3227   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3228     return false;
3229
3230   // Upper quadword shuffled.
3231   for (unsigned i = 4; i != 8; ++i)
3232     if (!isUndefOrInRange(Mask[i], 4, 8))
3233       return false;
3234
3235   if (VT == MVT::v16i16) {
3236     // Lower quadword copied in order or undef.
3237     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3238       return false;
3239
3240     // Upper quadword shuffled.
3241     for (unsigned i = 12; i != 16; ++i)
3242       if (!isUndefOrInRange(Mask[i], 12, 16))
3243         return false;
3244   }
3245
3246   return true;
3247 }
3248
3249 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3250 /// is suitable for input to PSHUFLW.
3251 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3252   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3253     return false;
3254
3255   // Upper quadword copied in order.
3256   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3257     return false;
3258
3259   // Lower quadword shuffled.
3260   for (unsigned i = 0; i != 4; ++i)
3261     if (!isUndefOrInRange(Mask[i], 0, 4))
3262       return false;
3263
3264   if (VT == MVT::v16i16) {
3265     // Upper quadword copied in order.
3266     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3267       return false;
3268
3269     // Lower quadword shuffled.
3270     for (unsigned i = 8; i != 12; ++i)
3271       if (!isUndefOrInRange(Mask[i], 8, 12))
3272         return false;
3273   }
3274
3275   return true;
3276 }
3277
3278 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3279 /// is suitable for input to PALIGNR.
3280 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3281                           const X86Subtarget *Subtarget) {
3282   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3283       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3284     return false;
3285
3286   unsigned NumElts = VT.getVectorNumElements();
3287   unsigned NumLanes = VT.getSizeInBits()/128;
3288   unsigned NumLaneElts = NumElts/NumLanes;
3289
3290   // Do not handle 64-bit element shuffles with palignr.
3291   if (NumLaneElts == 2)
3292     return false;
3293
3294   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3295     unsigned i;
3296     for (i = 0; i != NumLaneElts; ++i) {
3297       if (Mask[i+l] >= 0)
3298         break;
3299     }
3300
3301     // Lane is all undef, go to next lane
3302     if (i == NumLaneElts)
3303       continue;
3304
3305     int Start = Mask[i+l];
3306
3307     // Make sure its in this lane in one of the sources
3308     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3309         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3310       return false;
3311
3312     // If not lane 0, then we must match lane 0
3313     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3314       return false;
3315
3316     // Correct second source to be contiguous with first source
3317     if (Start >= (int)NumElts)
3318       Start -= NumElts - NumLaneElts;
3319
3320     // Make sure we're shifting in the right direction.
3321     if (Start <= (int)(i+l))
3322       return false;
3323
3324     Start -= i;
3325
3326     // Check the rest of the elements to see if they are consecutive.
3327     for (++i; i != NumLaneElts; ++i) {
3328       int Idx = Mask[i+l];
3329
3330       // Make sure its in this lane
3331       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3332           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3333         return false;
3334
3335       // If not lane 0, then we must match lane 0
3336       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3337         return false;
3338
3339       if (Idx >= (int)NumElts)
3340         Idx -= NumElts - NumLaneElts;
3341
3342       if (!isUndefOrEqual(Idx, Start+i))
3343         return false;
3344
3345     }
3346   }
3347
3348   return true;
3349 }
3350
3351 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3352 /// the two vector operands have swapped position.
3353 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3354                                      unsigned NumElems) {
3355   for (unsigned i = 0; i != NumElems; ++i) {
3356     int idx = Mask[i];
3357     if (idx < 0)
3358       continue;
3359     else if (idx < (int)NumElems)
3360       Mask[i] = idx + NumElems;
3361     else
3362       Mask[i] = idx - NumElems;
3363   }
3364 }
3365
3366 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3367 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3368 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3369 /// reverse of what x86 shuffles want.
3370 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3371                         bool Commuted = false) {
3372   if (!HasAVX && VT.getSizeInBits() == 256)
3373     return false;
3374
3375   unsigned NumElems = VT.getVectorNumElements();
3376   unsigned NumLanes = VT.getSizeInBits()/128;
3377   unsigned NumLaneElems = NumElems/NumLanes;
3378
3379   if (NumLaneElems != 2 && NumLaneElems != 4)
3380     return false;
3381
3382   // VSHUFPSY divides the resulting vector into 4 chunks.
3383   // The sources are also splitted into 4 chunks, and each destination
3384   // chunk must come from a different source chunk.
3385   //
3386   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3387   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3388   //
3389   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3390   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3391   //
3392   // VSHUFPDY divides the resulting vector into 4 chunks.
3393   // The sources are also splitted into 4 chunks, and each destination
3394   // chunk must come from a different source chunk.
3395   //
3396   //  SRC1 =>      X3       X2       X1       X0
3397   //  SRC2 =>      Y3       Y2       Y1       Y0
3398   //
3399   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3400   //
3401   unsigned HalfLaneElems = NumLaneElems/2;
3402   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3403     for (unsigned i = 0; i != NumLaneElems; ++i) {
3404       int Idx = Mask[i+l];
3405       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3406       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3407         return false;
3408       // For VSHUFPSY, the mask of the second half must be the same as the
3409       // first but with the appropriate offsets. This works in the same way as
3410       // VPERMILPS works with masks.
3411       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3412         continue;
3413       if (!isUndefOrEqual(Idx, Mask[i]+l))
3414         return false;
3415     }
3416   }
3417
3418   return true;
3419 }
3420
3421 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3422 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3423 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3424   unsigned NumElems = VT.getVectorNumElements();
3425
3426   if (VT.getSizeInBits() != 128)
3427     return false;
3428
3429   if (NumElems != 4)
3430     return false;
3431
3432   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3433   return isUndefOrEqual(Mask[0], 6) &&
3434          isUndefOrEqual(Mask[1], 7) &&
3435          isUndefOrEqual(Mask[2], 2) &&
3436          isUndefOrEqual(Mask[3], 3);
3437 }
3438
3439 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3440 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3441 /// <2, 3, 2, 3>
3442 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3443   unsigned NumElems = VT.getVectorNumElements();
3444
3445   if (VT.getSizeInBits() != 128)
3446     return false;
3447
3448   if (NumElems != 4)
3449     return false;
3450
3451   return isUndefOrEqual(Mask[0], 2) &&
3452          isUndefOrEqual(Mask[1], 3) &&
3453          isUndefOrEqual(Mask[2], 2) &&
3454          isUndefOrEqual(Mask[3], 3);
3455 }
3456
3457 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3458 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3459 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3460   if (VT.getSizeInBits() != 128)
3461     return false;
3462
3463   unsigned NumElems = VT.getVectorNumElements();
3464
3465   if (NumElems != 2 && NumElems != 4)
3466     return false;
3467
3468   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3469     if (!isUndefOrEqual(Mask[i], i + NumElems))
3470       return false;
3471
3472   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3473     if (!isUndefOrEqual(Mask[i], i))
3474       return false;
3475
3476   return true;
3477 }
3478
3479 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3480 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3481 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3482   unsigned NumElems = VT.getVectorNumElements();
3483
3484   if ((NumElems != 2 && NumElems != 4)
3485       || VT.getSizeInBits() > 128)
3486     return false;
3487
3488   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3489     if (!isUndefOrEqual(Mask[i], i))
3490       return false;
3491
3492   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3493     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3494       return false;
3495
3496   return true;
3497 }
3498
3499 //
3500 // Some special combinations that can be optimized.
3501 //
3502 static
3503 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3504                                SelectionDAG &DAG) {
3505   EVT VT = SVOp->getValueType(0);
3506   DebugLoc dl = SVOp->getDebugLoc();
3507
3508   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3509     return SDValue();
3510
3511   ArrayRef<int> Mask = SVOp->getMask();
3512
3513   // These are the special masks that may be optimized.
3514   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3515   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3516   bool MatchEvenMask = true;
3517   bool MatchOddMask  = true;
3518   for (int i=0; i<8; ++i) {
3519     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3520       MatchEvenMask = false;
3521     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3522       MatchOddMask = false;
3523   }
3524   static const int CompactionMaskEven[] = {0, 2, -1, -1, 4, 6, -1, -1};
3525   static const int CompactionMaskOdd [] = {1, 3, -1, -1, 5, 7, -1, -1};
3526
3527   const int *CompactionMask;
3528   if (MatchEvenMask)
3529     CompactionMask = CompactionMaskEven;
3530   else if (MatchOddMask)
3531     CompactionMask = CompactionMaskOdd;
3532   else
3533     return SDValue();
3534
3535   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3536
3537   SDValue Op0 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(0),
3538                                      UndefNode, CompactionMask);
3539   SDValue Op1 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(1),
3540                                      UndefNode, CompactionMask);
3541   static const int UnpackMask[] = {0, 8, 1, 9, 4, 12, 5, 13};
3542   return DAG.getVectorShuffle(VT, dl, Op0, Op1, UnpackMask);
3543 }
3544
3545 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3546 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3547 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3548                          bool HasAVX2, bool V2IsSplat = false) {
3549   unsigned NumElts = VT.getVectorNumElements();
3550
3551   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3552          "Unsupported vector type for unpckh");
3553
3554   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3555       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3556     return false;
3557
3558   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3559   // independently on 128-bit lanes.
3560   unsigned NumLanes = VT.getSizeInBits()/128;
3561   unsigned NumLaneElts = NumElts/NumLanes;
3562
3563   for (unsigned l = 0; l != NumLanes; ++l) {
3564     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3565          i != (l+1)*NumLaneElts;
3566          i += 2, ++j) {
3567       int BitI  = Mask[i];
3568       int BitI1 = Mask[i+1];
3569       if (!isUndefOrEqual(BitI, j))
3570         return false;
3571       if (V2IsSplat) {
3572         if (!isUndefOrEqual(BitI1, NumElts))
3573           return false;
3574       } else {
3575         if (!isUndefOrEqual(BitI1, j + NumElts))
3576           return false;
3577       }
3578     }
3579   }
3580
3581   return true;
3582 }
3583
3584 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3585 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3586 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3587                          bool HasAVX2, bool V2IsSplat = false) {
3588   unsigned NumElts = VT.getVectorNumElements();
3589
3590   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3591          "Unsupported vector type for unpckh");
3592
3593   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3594       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3595     return false;
3596
3597   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3598   // independently on 128-bit lanes.
3599   unsigned NumLanes = VT.getSizeInBits()/128;
3600   unsigned NumLaneElts = NumElts/NumLanes;
3601
3602   for (unsigned l = 0; l != NumLanes; ++l) {
3603     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3604          i != (l+1)*NumLaneElts; i += 2, ++j) {
3605       int BitI  = Mask[i];
3606       int BitI1 = Mask[i+1];
3607       if (!isUndefOrEqual(BitI, j))
3608         return false;
3609       if (V2IsSplat) {
3610         if (isUndefOrEqual(BitI1, NumElts))
3611           return false;
3612       } else {
3613         if (!isUndefOrEqual(BitI1, j+NumElts))
3614           return false;
3615       }
3616     }
3617   }
3618   return true;
3619 }
3620
3621 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3622 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3623 /// <0, 0, 1, 1>
3624 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3625                                   bool HasAVX2) {
3626   unsigned NumElts = VT.getVectorNumElements();
3627
3628   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3629          "Unsupported vector type for unpckh");
3630
3631   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3632       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3633     return false;
3634
3635   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3636   // FIXME: Need a better way to get rid of this, there's no latency difference
3637   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3638   // the former later. We should also remove the "_undef" special mask.
3639   if (NumElts == 4 && VT.getSizeInBits() == 256)
3640     return false;
3641
3642   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3643   // independently on 128-bit lanes.
3644   unsigned NumLanes = VT.getSizeInBits()/128;
3645   unsigned NumLaneElts = NumElts/NumLanes;
3646
3647   for (unsigned l = 0; l != NumLanes; ++l) {
3648     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3649          i != (l+1)*NumLaneElts;
3650          i += 2, ++j) {
3651       int BitI  = Mask[i];
3652       int BitI1 = Mask[i+1];
3653
3654       if (!isUndefOrEqual(BitI, j))
3655         return false;
3656       if (!isUndefOrEqual(BitI1, j))
3657         return false;
3658     }
3659   }
3660
3661   return true;
3662 }
3663
3664 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3665 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3666 /// <2, 2, 3, 3>
3667 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3668   unsigned NumElts = VT.getVectorNumElements();
3669
3670   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3671          "Unsupported vector type for unpckh");
3672
3673   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3674       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3675     return false;
3676
3677   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3678   // independently on 128-bit lanes.
3679   unsigned NumLanes = VT.getSizeInBits()/128;
3680   unsigned NumLaneElts = NumElts/NumLanes;
3681
3682   for (unsigned l = 0; l != NumLanes; ++l) {
3683     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3684          i != (l+1)*NumLaneElts; i += 2, ++j) {
3685       int BitI  = Mask[i];
3686       int BitI1 = Mask[i+1];
3687       if (!isUndefOrEqual(BitI, j))
3688         return false;
3689       if (!isUndefOrEqual(BitI1, j))
3690         return false;
3691     }
3692   }
3693   return true;
3694 }
3695
3696 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3697 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3698 /// MOVSD, and MOVD, i.e. setting the lowest element.
3699 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3700   if (VT.getVectorElementType().getSizeInBits() < 32)
3701     return false;
3702   if (VT.getSizeInBits() == 256)
3703     return false;
3704
3705   unsigned NumElts = VT.getVectorNumElements();
3706
3707   if (!isUndefOrEqual(Mask[0], NumElts))
3708     return false;
3709
3710   for (unsigned i = 1; i != NumElts; ++i)
3711     if (!isUndefOrEqual(Mask[i], i))
3712       return false;
3713
3714   return true;
3715 }
3716
3717 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3718 /// as permutations between 128-bit chunks or halves. As an example: this
3719 /// shuffle bellow:
3720 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3721 /// The first half comes from the second half of V1 and the second half from the
3722 /// the second half of V2.
3723 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3724   if (!HasAVX || VT.getSizeInBits() != 256)
3725     return false;
3726
3727   // The shuffle result is divided into half A and half B. In total the two
3728   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3729   // B must come from C, D, E or F.
3730   unsigned HalfSize = VT.getVectorNumElements()/2;
3731   bool MatchA = false, MatchB = false;
3732
3733   // Check if A comes from one of C, D, E, F.
3734   for (unsigned Half = 0; Half != 4; ++Half) {
3735     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3736       MatchA = true;
3737       break;
3738     }
3739   }
3740
3741   // Check if B comes from one of C, D, E, F.
3742   for (unsigned Half = 0; Half != 4; ++Half) {
3743     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3744       MatchB = true;
3745       break;
3746     }
3747   }
3748
3749   return MatchA && MatchB;
3750 }
3751
3752 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3753 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3754 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3755   EVT VT = SVOp->getValueType(0);
3756
3757   unsigned HalfSize = VT.getVectorNumElements()/2;
3758
3759   unsigned FstHalf = 0, SndHalf = 0;
3760   for (unsigned i = 0; i < HalfSize; ++i) {
3761     if (SVOp->getMaskElt(i) > 0) {
3762       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3763       break;
3764     }
3765   }
3766   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3767     if (SVOp->getMaskElt(i) > 0) {
3768       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3769       break;
3770     }
3771   }
3772
3773   return (FstHalf | (SndHalf << 4));
3774 }
3775
3776 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3777 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3778 /// Note that VPERMIL mask matching is different depending whether theunderlying
3779 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3780 /// to the same elements of the low, but to the higher half of the source.
3781 /// In VPERMILPD the two lanes could be shuffled independently of each other
3782 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3783 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3784   if (!HasAVX)
3785     return false;
3786
3787   unsigned NumElts = VT.getVectorNumElements();
3788   // Only match 256-bit with 32/64-bit types
3789   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3790     return false;
3791
3792   unsigned NumLanes = VT.getSizeInBits()/128;
3793   unsigned LaneSize = NumElts/NumLanes;
3794   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3795     for (unsigned i = 0; i != LaneSize; ++i) {
3796       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3797         return false;
3798       if (NumElts != 8 || l == 0)
3799         continue;
3800       // VPERMILPS handling
3801       if (Mask[i] < 0)
3802         continue;
3803       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3804         return false;
3805     }
3806   }
3807
3808   return true;
3809 }
3810
3811 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3812 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3813 /// element of vector 2 and the other elements to come from vector 1 in order.
3814 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3815                                bool V2IsSplat = false, bool V2IsUndef = false) {
3816   unsigned NumOps = VT.getVectorNumElements();
3817   if (VT.getSizeInBits() == 256)
3818     return false;
3819   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3820     return false;
3821
3822   if (!isUndefOrEqual(Mask[0], 0))
3823     return false;
3824
3825   for (unsigned i = 1; i != NumOps; ++i)
3826     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3827           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3828           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3829       return false;
3830
3831   return true;
3832 }
3833
3834 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3835 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3836 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3837 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3838                            const X86Subtarget *Subtarget) {
3839   if (!Subtarget->hasSSE3())
3840     return false;
3841
3842   unsigned NumElems = VT.getVectorNumElements();
3843
3844   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3845       (VT.getSizeInBits() == 256 && NumElems != 8))
3846     return false;
3847
3848   // "i+1" is the value the indexed mask element must have
3849   for (unsigned i = 0; i != NumElems; i += 2)
3850     if (!isUndefOrEqual(Mask[i], i+1) ||
3851         !isUndefOrEqual(Mask[i+1], i+1))
3852       return false;
3853
3854   return true;
3855 }
3856
3857 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3858 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3859 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3860 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3861                            const X86Subtarget *Subtarget) {
3862   if (!Subtarget->hasSSE3())
3863     return false;
3864
3865   unsigned NumElems = VT.getVectorNumElements();
3866
3867   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3868       (VT.getSizeInBits() == 256 && NumElems != 8))
3869     return false;
3870
3871   // "i" is the value the indexed mask element must have
3872   for (unsigned i = 0; i != NumElems; i += 2)
3873     if (!isUndefOrEqual(Mask[i], i) ||
3874         !isUndefOrEqual(Mask[i+1], i))
3875       return false;
3876
3877   return true;
3878 }
3879
3880 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3881 /// specifies a shuffle of elements that is suitable for input to 256-bit
3882 /// version of MOVDDUP.
3883 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3884   unsigned NumElts = VT.getVectorNumElements();
3885
3886   if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3887     return false;
3888
3889   for (unsigned i = 0; i != NumElts/2; ++i)
3890     if (!isUndefOrEqual(Mask[i], 0))
3891       return false;
3892   for (unsigned i = NumElts/2; i != NumElts; ++i)
3893     if (!isUndefOrEqual(Mask[i], NumElts/2))
3894       return false;
3895   return true;
3896 }
3897
3898 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3899 /// specifies a shuffle of elements that is suitable for input to 128-bit
3900 /// version of MOVDDUP.
3901 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3902   if (VT.getSizeInBits() != 128)
3903     return false;
3904
3905   unsigned e = VT.getVectorNumElements() / 2;
3906   for (unsigned i = 0; i != e; ++i)
3907     if (!isUndefOrEqual(Mask[i], i))
3908       return false;
3909   for (unsigned i = 0; i != e; ++i)
3910     if (!isUndefOrEqual(Mask[e+i], i))
3911       return false;
3912   return true;
3913 }
3914
3915 /// isVEXTRACTF128Index - Return true if the specified
3916 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3917 /// suitable for input to VEXTRACTF128.
3918 bool X86::isVEXTRACTF128Index(SDNode *N) {
3919   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3920     return false;
3921
3922   // The index should be aligned on a 128-bit boundary.
3923   uint64_t Index =
3924     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3925
3926   unsigned VL = N->getValueType(0).getVectorNumElements();
3927   unsigned VBits = N->getValueType(0).getSizeInBits();
3928   unsigned ElSize = VBits / VL;
3929   bool Result = (Index * ElSize) % 128 == 0;
3930
3931   return Result;
3932 }
3933
3934 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3935 /// operand specifies a subvector insert that is suitable for input to
3936 /// VINSERTF128.
3937 bool X86::isVINSERTF128Index(SDNode *N) {
3938   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3939     return false;
3940
3941   // The index should be aligned on a 128-bit boundary.
3942   uint64_t Index =
3943     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3944
3945   unsigned VL = N->getValueType(0).getVectorNumElements();
3946   unsigned VBits = N->getValueType(0).getSizeInBits();
3947   unsigned ElSize = VBits / VL;
3948   bool Result = (Index * ElSize) % 128 == 0;
3949
3950   return Result;
3951 }
3952
3953 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3954 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3955 /// Handles 128-bit and 256-bit.
3956 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3957   EVT VT = N->getValueType(0);
3958
3959   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3960          "Unsupported vector type for PSHUF/SHUFP");
3961
3962   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3963   // independently on 128-bit lanes.
3964   unsigned NumElts = VT.getVectorNumElements();
3965   unsigned NumLanes = VT.getSizeInBits()/128;
3966   unsigned NumLaneElts = NumElts/NumLanes;
3967
3968   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3969          "Only supports 2 or 4 elements per lane");
3970
3971   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3972   unsigned Mask = 0;
3973   for (unsigned i = 0; i != NumElts; ++i) {
3974     int Elt = N->getMaskElt(i);
3975     if (Elt < 0) continue;
3976     Elt &= NumLaneElts - 1;
3977     unsigned ShAmt = (i << Shift) % 8;
3978     Mask |= Elt << ShAmt;
3979   }
3980
3981   return Mask;
3982 }
3983
3984 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3985 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3986 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3987   EVT VT = N->getValueType(0);
3988
3989   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3990          "Unsupported vector type for PSHUFHW");
3991
3992   unsigned NumElts = VT.getVectorNumElements();
3993
3994   unsigned Mask = 0;
3995   for (unsigned l = 0; l != NumElts; l += 8) {
3996     // 8 nodes per lane, but we only care about the last 4.
3997     for (unsigned i = 0; i < 4; ++i) {
3998       int Elt = N->getMaskElt(l+i+4);
3999       if (Elt < 0) continue;
4000       Elt &= 0x3; // only 2-bits.
4001       Mask |= Elt << (i * 2);
4002     }
4003   }
4004
4005   return Mask;
4006 }
4007
4008 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4009 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4010 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4011   EVT VT = N->getValueType(0);
4012
4013   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4014          "Unsupported vector type for PSHUFHW");
4015
4016   unsigned NumElts = VT.getVectorNumElements();
4017
4018   unsigned Mask = 0;
4019   for (unsigned l = 0; l != NumElts; l += 8) {
4020     // 8 nodes per lane, but we only care about the first 4.
4021     for (unsigned i = 0; i < 4; ++i) {
4022       int Elt = N->getMaskElt(l+i);
4023       if (Elt < 0) continue;
4024       Elt &= 0x3; // only 2-bits
4025       Mask |= Elt << (i * 2);
4026     }
4027   }
4028
4029   return Mask;
4030 }
4031
4032 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4033 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4034 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4035   EVT VT = SVOp->getValueType(0);
4036   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4037
4038   unsigned NumElts = VT.getVectorNumElements();
4039   unsigned NumLanes = VT.getSizeInBits()/128;
4040   unsigned NumLaneElts = NumElts/NumLanes;
4041
4042   int Val = 0;
4043   unsigned i;
4044   for (i = 0; i != NumElts; ++i) {
4045     Val = SVOp->getMaskElt(i);
4046     if (Val >= 0)
4047       break;
4048   }
4049   if (Val >= (int)NumElts)
4050     Val -= NumElts - NumLaneElts;
4051
4052   assert(Val - i > 0 && "PALIGNR imm should be positive");
4053   return (Val - i) * EltSize;
4054 }
4055
4056 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4057 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4058 /// instructions.
4059 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4060   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4061     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4062
4063   uint64_t Index =
4064     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4065
4066   EVT VecVT = N->getOperand(0).getValueType();
4067   EVT ElVT = VecVT.getVectorElementType();
4068
4069   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4070   return Index / NumElemsPerChunk;
4071 }
4072
4073 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4074 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4075 /// instructions.
4076 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4077   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4078     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4079
4080   uint64_t Index =
4081     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4082
4083   EVT VecVT = N->getValueType(0);
4084   EVT ElVT = VecVT.getVectorElementType();
4085
4086   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4087   return Index / NumElemsPerChunk;
4088 }
4089
4090 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4091 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4092 /// Handles 256-bit.
4093 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4094   EVT VT = N->getValueType(0);
4095
4096   unsigned NumElts = VT.getVectorNumElements();
4097
4098   assert((VT.is256BitVector() && NumElts == 4) &&
4099          "Unsupported vector type for VPERMQ/VPERMPD");
4100
4101   unsigned Mask = 0;
4102   for (unsigned i = 0; i != NumElts; ++i) {
4103     int Elt = N->getMaskElt(i);
4104     if (Elt < 0)
4105       continue;
4106     Mask |= Elt << (i*2);
4107   }
4108
4109   return Mask;
4110 }
4111 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4112 /// constant +0.0.
4113 bool X86::isZeroNode(SDValue Elt) {
4114   return ((isa<ConstantSDNode>(Elt) &&
4115            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4116           (isa<ConstantFPSDNode>(Elt) &&
4117            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4118 }
4119
4120 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4121 /// their permute mask.
4122 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4123                                     SelectionDAG &DAG) {
4124   EVT VT = SVOp->getValueType(0);
4125   unsigned NumElems = VT.getVectorNumElements();
4126   SmallVector<int, 8> MaskVec;
4127
4128   for (unsigned i = 0; i != NumElems; ++i) {
4129     int Idx = SVOp->getMaskElt(i);
4130     if (Idx >= 0) {
4131       if (Idx < (int)NumElems)
4132         Idx += NumElems;
4133       else
4134         Idx -= NumElems;
4135     }
4136     MaskVec.push_back(Idx);
4137   }
4138   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4139                               SVOp->getOperand(0), &MaskVec[0]);
4140 }
4141
4142 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4143 /// match movhlps. The lower half elements should come from upper half of
4144 /// V1 (and in order), and the upper half elements should come from the upper
4145 /// half of V2 (and in order).
4146 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4147   if (VT.getSizeInBits() != 128)
4148     return false;
4149   if (VT.getVectorNumElements() != 4)
4150     return false;
4151   for (unsigned i = 0, e = 2; i != e; ++i)
4152     if (!isUndefOrEqual(Mask[i], i+2))
4153       return false;
4154   for (unsigned i = 2; i != 4; ++i)
4155     if (!isUndefOrEqual(Mask[i], i+4))
4156       return false;
4157   return true;
4158 }
4159
4160 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4161 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4162 /// required.
4163 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4164   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4165     return false;
4166   N = N->getOperand(0).getNode();
4167   if (!ISD::isNON_EXTLoad(N))
4168     return false;
4169   if (LD)
4170     *LD = cast<LoadSDNode>(N);
4171   return true;
4172 }
4173
4174 // Test whether the given value is a vector value which will be legalized
4175 // into a load.
4176 static bool WillBeConstantPoolLoad(SDNode *N) {
4177   if (N->getOpcode() != ISD::BUILD_VECTOR)
4178     return false;
4179
4180   // Check for any non-constant elements.
4181   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4182     switch (N->getOperand(i).getNode()->getOpcode()) {
4183     case ISD::UNDEF:
4184     case ISD::ConstantFP:
4185     case ISD::Constant:
4186       break;
4187     default:
4188       return false;
4189     }
4190
4191   // Vectors of all-zeros and all-ones are materialized with special
4192   // instructions rather than being loaded.
4193   return !ISD::isBuildVectorAllZeros(N) &&
4194          !ISD::isBuildVectorAllOnes(N);
4195 }
4196
4197 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4198 /// match movlp{s|d}. The lower half elements should come from lower half of
4199 /// V1 (and in order), and the upper half elements should come from the upper
4200 /// half of V2 (and in order). And since V1 will become the source of the
4201 /// MOVLP, it must be either a vector load or a scalar load to vector.
4202 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4203                                ArrayRef<int> Mask, EVT VT) {
4204   if (VT.getSizeInBits() != 128)
4205     return false;
4206
4207   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4208     return false;
4209   // Is V2 is a vector load, don't do this transformation. We will try to use
4210   // load folding shufps op.
4211   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4212     return false;
4213
4214   unsigned NumElems = VT.getVectorNumElements();
4215
4216   if (NumElems != 2 && NumElems != 4)
4217     return false;
4218   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4219     if (!isUndefOrEqual(Mask[i], i))
4220       return false;
4221   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4222     if (!isUndefOrEqual(Mask[i], i+NumElems))
4223       return false;
4224   return true;
4225 }
4226
4227 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4228 /// all the same.
4229 static bool isSplatVector(SDNode *N) {
4230   if (N->getOpcode() != ISD::BUILD_VECTOR)
4231     return false;
4232
4233   SDValue SplatValue = N->getOperand(0);
4234   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4235     if (N->getOperand(i) != SplatValue)
4236       return false;
4237   return true;
4238 }
4239
4240 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4241 /// to an zero vector.
4242 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4243 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4244   SDValue V1 = N->getOperand(0);
4245   SDValue V2 = N->getOperand(1);
4246   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4247   for (unsigned i = 0; i != NumElems; ++i) {
4248     int Idx = N->getMaskElt(i);
4249     if (Idx >= (int)NumElems) {
4250       unsigned Opc = V2.getOpcode();
4251       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4252         continue;
4253       if (Opc != ISD::BUILD_VECTOR ||
4254           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4255         return false;
4256     } else if (Idx >= 0) {
4257       unsigned Opc = V1.getOpcode();
4258       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4259         continue;
4260       if (Opc != ISD::BUILD_VECTOR ||
4261           !X86::isZeroNode(V1.getOperand(Idx)))
4262         return false;
4263     }
4264   }
4265   return true;
4266 }
4267
4268 /// getZeroVector - Returns a vector of specified type with all zero elements.
4269 ///
4270 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4271                              SelectionDAG &DAG, DebugLoc dl) {
4272   assert(VT.isVector() && "Expected a vector type");
4273   unsigned Size = VT.getSizeInBits();
4274
4275   // Always build SSE zero vectors as <4 x i32> bitcasted
4276   // to their dest type. This ensures they get CSE'd.
4277   SDValue Vec;
4278   if (Size == 128) {  // SSE
4279     if (Subtarget->hasSSE2()) {  // SSE2
4280       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4281       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4282     } else { // SSE1
4283       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4284       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4285     }
4286   } else if (Size == 256) { // AVX
4287     if (Subtarget->hasAVX2()) { // AVX2
4288       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4289       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4290       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4291     } else {
4292       // 256-bit logic and arithmetic instructions in AVX are all
4293       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4294       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4295       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4296       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4297     }
4298   } else
4299     llvm_unreachable("Unexpected vector type");
4300
4301   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4302 }
4303
4304 /// getOnesVector - Returns a vector of specified type with all bits set.
4305 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4306 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4307 /// Then bitcast to their original type, ensuring they get CSE'd.
4308 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4309                              DebugLoc dl) {
4310   assert(VT.isVector() && "Expected a vector type");
4311   unsigned Size = VT.getSizeInBits();
4312
4313   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4314   SDValue Vec;
4315   if (Size == 256) {
4316     if (HasAVX2) { // AVX2
4317       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4318       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4319     } else { // AVX
4320       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4321       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4322     }
4323   } else if (Size == 128) {
4324     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4325   } else
4326     llvm_unreachable("Unexpected vector type");
4327
4328   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4329 }
4330
4331 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4332 /// that point to V2 points to its first element.
4333 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4334   for (unsigned i = 0; i != NumElems; ++i) {
4335     if (Mask[i] > (int)NumElems) {
4336       Mask[i] = NumElems;
4337     }
4338   }
4339 }
4340
4341 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4342 /// operation of specified width.
4343 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4344                        SDValue V2) {
4345   unsigned NumElems = VT.getVectorNumElements();
4346   SmallVector<int, 8> Mask;
4347   Mask.push_back(NumElems);
4348   for (unsigned i = 1; i != NumElems; ++i)
4349     Mask.push_back(i);
4350   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4351 }
4352
4353 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4354 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4355                           SDValue V2) {
4356   unsigned NumElems = VT.getVectorNumElements();
4357   SmallVector<int, 8> Mask;
4358   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4359     Mask.push_back(i);
4360     Mask.push_back(i + NumElems);
4361   }
4362   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4363 }
4364
4365 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4366 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4367                           SDValue V2) {
4368   unsigned NumElems = VT.getVectorNumElements();
4369   SmallVector<int, 8> Mask;
4370   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4371     Mask.push_back(i + Half);
4372     Mask.push_back(i + NumElems + Half);
4373   }
4374   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4375 }
4376
4377 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4378 // a generic shuffle instruction because the target has no such instructions.
4379 // Generate shuffles which repeat i16 and i8 several times until they can be
4380 // represented by v4f32 and then be manipulated by target suported shuffles.
4381 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4382   EVT VT = V.getValueType();
4383   int NumElems = VT.getVectorNumElements();
4384   DebugLoc dl = V.getDebugLoc();
4385
4386   while (NumElems > 4) {
4387     if (EltNo < NumElems/2) {
4388       V = getUnpackl(DAG, dl, VT, V, V);
4389     } else {
4390       V = getUnpackh(DAG, dl, VT, V, V);
4391       EltNo -= NumElems/2;
4392     }
4393     NumElems >>= 1;
4394   }
4395   return V;
4396 }
4397
4398 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4399 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4400   EVT VT = V.getValueType();
4401   DebugLoc dl = V.getDebugLoc();
4402   unsigned Size = VT.getSizeInBits();
4403
4404   if (Size == 128) {
4405     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4406     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4407     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4408                              &SplatMask[0]);
4409   } else if (Size == 256) {
4410     // To use VPERMILPS to splat scalars, the second half of indicies must
4411     // refer to the higher part, which is a duplication of the lower one,
4412     // because VPERMILPS can only handle in-lane permutations.
4413     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4414                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4415
4416     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4417     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4418                              &SplatMask[0]);
4419   } else
4420     llvm_unreachable("Vector size not supported");
4421
4422   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4423 }
4424
4425 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4426 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4427   EVT SrcVT = SV->getValueType(0);
4428   SDValue V1 = SV->getOperand(0);
4429   DebugLoc dl = SV->getDebugLoc();
4430
4431   int EltNo = SV->getSplatIndex();
4432   int NumElems = SrcVT.getVectorNumElements();
4433   unsigned Size = SrcVT.getSizeInBits();
4434
4435   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4436           "Unknown how to promote splat for type");
4437
4438   // Extract the 128-bit part containing the splat element and update
4439   // the splat element index when it refers to the higher register.
4440   if (Size == 256) {
4441     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4442     if (EltNo >= NumElems/2)
4443       EltNo -= NumElems/2;
4444   }
4445
4446   // All i16 and i8 vector types can't be used directly by a generic shuffle
4447   // instruction because the target has no such instruction. Generate shuffles
4448   // which repeat i16 and i8 several times until they fit in i32, and then can
4449   // be manipulated by target suported shuffles.
4450   EVT EltVT = SrcVT.getVectorElementType();
4451   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4452     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4453
4454   // Recreate the 256-bit vector and place the same 128-bit vector
4455   // into the low and high part. This is necessary because we want
4456   // to use VPERM* to shuffle the vectors
4457   if (Size == 256) {
4458     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4459   }
4460
4461   return getLegalSplat(DAG, V1, EltNo);
4462 }
4463
4464 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4465 /// vector of zero or undef vector.  This produces a shuffle where the low
4466 /// element of V2 is swizzled into the zero/undef vector, landing at element
4467 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4468 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4469                                            bool IsZero,
4470                                            const X86Subtarget *Subtarget,
4471                                            SelectionDAG &DAG) {
4472   EVT VT = V2.getValueType();
4473   SDValue V1 = IsZero
4474     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4475   unsigned NumElems = VT.getVectorNumElements();
4476   SmallVector<int, 16> MaskVec;
4477   for (unsigned i = 0; i != NumElems; ++i)
4478     // If this is the insertion idx, put the low elt of V2 here.
4479     MaskVec.push_back(i == Idx ? NumElems : i);
4480   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4481 }
4482
4483 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4484 /// target specific opcode. Returns true if the Mask could be calculated.
4485 /// Sets IsUnary to true if only uses one source.
4486 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4487                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4488   unsigned NumElems = VT.getVectorNumElements();
4489   SDValue ImmN;
4490
4491   IsUnary = false;
4492   switch(N->getOpcode()) {
4493   case X86ISD::SHUFP:
4494     ImmN = N->getOperand(N->getNumOperands()-1);
4495     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4496     break;
4497   case X86ISD::UNPCKH:
4498     DecodeUNPCKHMask(VT, Mask);
4499     break;
4500   case X86ISD::UNPCKL:
4501     DecodeUNPCKLMask(VT, Mask);
4502     break;
4503   case X86ISD::MOVHLPS:
4504     DecodeMOVHLPSMask(NumElems, Mask);
4505     break;
4506   case X86ISD::MOVLHPS:
4507     DecodeMOVLHPSMask(NumElems, Mask);
4508     break;
4509   case X86ISD::PSHUFD:
4510   case X86ISD::VPERMILP:
4511     ImmN = N->getOperand(N->getNumOperands()-1);
4512     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4513     IsUnary = true;
4514     break;
4515   case X86ISD::PSHUFHW:
4516     ImmN = N->getOperand(N->getNumOperands()-1);
4517     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4518     IsUnary = true;
4519     break;
4520   case X86ISD::PSHUFLW:
4521     ImmN = N->getOperand(N->getNumOperands()-1);
4522     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4523     IsUnary = true;
4524     break;
4525   case X86ISD::VPERMI:
4526     ImmN = N->getOperand(N->getNumOperands()-1);
4527     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4528     IsUnary = true;
4529     break;
4530   case X86ISD::MOVSS:
4531   case X86ISD::MOVSD: {
4532     // The index 0 always comes from the first element of the second source,
4533     // this is why MOVSS and MOVSD are used in the first place. The other
4534     // elements come from the other positions of the first source vector
4535     Mask.push_back(NumElems);
4536     for (unsigned i = 1; i != NumElems; ++i) {
4537       Mask.push_back(i);
4538     }
4539     break;
4540   }
4541   case X86ISD::VPERM2X128:
4542     ImmN = N->getOperand(N->getNumOperands()-1);
4543     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4544     if (Mask.empty()) return false;
4545     break;
4546   case X86ISD::MOVDDUP:
4547   case X86ISD::MOVLHPD:
4548   case X86ISD::MOVLPD:
4549   case X86ISD::MOVLPS:
4550   case X86ISD::MOVSHDUP:
4551   case X86ISD::MOVSLDUP:
4552   case X86ISD::PALIGN:
4553     // Not yet implemented
4554     return false;
4555   default: llvm_unreachable("unknown target shuffle node");
4556   }
4557
4558   return true;
4559 }
4560
4561 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4562 /// element of the result of the vector shuffle.
4563 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4564                                    unsigned Depth) {
4565   if (Depth == 6)
4566     return SDValue();  // Limit search depth.
4567
4568   SDValue V = SDValue(N, 0);
4569   EVT VT = V.getValueType();
4570   unsigned Opcode = V.getOpcode();
4571
4572   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4573   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4574     int Elt = SV->getMaskElt(Index);
4575
4576     if (Elt < 0)
4577       return DAG.getUNDEF(VT.getVectorElementType());
4578
4579     unsigned NumElems = VT.getVectorNumElements();
4580     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4581                                          : SV->getOperand(1);
4582     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4583   }
4584
4585   // Recurse into target specific vector shuffles to find scalars.
4586   if (isTargetShuffle(Opcode)) {
4587     MVT ShufVT = V.getValueType().getSimpleVT();
4588     unsigned NumElems = ShufVT.getVectorNumElements();
4589     SmallVector<int, 16> ShuffleMask;
4590     SDValue ImmN;
4591     bool IsUnary;
4592
4593     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4594       return SDValue();
4595
4596     int Elt = ShuffleMask[Index];
4597     if (Elt < 0)
4598       return DAG.getUNDEF(ShufVT.getVectorElementType());
4599
4600     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4601                                          : N->getOperand(1);
4602     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4603                                Depth+1);
4604   }
4605
4606   // Actual nodes that may contain scalar elements
4607   if (Opcode == ISD::BITCAST) {
4608     V = V.getOperand(0);
4609     EVT SrcVT = V.getValueType();
4610     unsigned NumElems = VT.getVectorNumElements();
4611
4612     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4613       return SDValue();
4614   }
4615
4616   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4617     return (Index == 0) ? V.getOperand(0)
4618                         : DAG.getUNDEF(VT.getVectorElementType());
4619
4620   if (V.getOpcode() == ISD::BUILD_VECTOR)
4621     return V.getOperand(Index);
4622
4623   return SDValue();
4624 }
4625
4626 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4627 /// shuffle operation which come from a consecutively from a zero. The
4628 /// search can start in two different directions, from left or right.
4629 static
4630 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4631                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4632   unsigned i;
4633   for (i = 0; i != NumElems; ++i) {
4634     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4635     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4636     if (!(Elt.getNode() &&
4637          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4638       break;
4639   }
4640
4641   return i;
4642 }
4643
4644 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4645 /// correspond consecutively to elements from one of the vector operands,
4646 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4647 static
4648 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4649                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4650                               unsigned NumElems, unsigned &OpNum) {
4651   bool SeenV1 = false;
4652   bool SeenV2 = false;
4653
4654   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4655     int Idx = SVOp->getMaskElt(i);
4656     // Ignore undef indicies
4657     if (Idx < 0)
4658       continue;
4659
4660     if (Idx < (int)NumElems)
4661       SeenV1 = true;
4662     else
4663       SeenV2 = true;
4664
4665     // Only accept consecutive elements from the same vector
4666     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4667       return false;
4668   }
4669
4670   OpNum = SeenV1 ? 0 : 1;
4671   return true;
4672 }
4673
4674 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4675 /// logical left shift of a vector.
4676 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4677                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4678   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4679   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4680               false /* check zeros from right */, DAG);
4681   unsigned OpSrc;
4682
4683   if (!NumZeros)
4684     return false;
4685
4686   // Considering the elements in the mask that are not consecutive zeros,
4687   // check if they consecutively come from only one of the source vectors.
4688   //
4689   //               V1 = {X, A, B, C}     0
4690   //                         \  \  \    /
4691   //   vector_shuffle V1, V2 <1, 2, 3, X>
4692   //
4693   if (!isShuffleMaskConsecutive(SVOp,
4694             0,                   // Mask Start Index
4695             NumElems-NumZeros,   // Mask End Index(exclusive)
4696             NumZeros,            // Where to start looking in the src vector
4697             NumElems,            // Number of elements in vector
4698             OpSrc))              // Which source operand ?
4699     return false;
4700
4701   isLeft = false;
4702   ShAmt = NumZeros;
4703   ShVal = SVOp->getOperand(OpSrc);
4704   return true;
4705 }
4706
4707 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4708 /// logical left shift of a vector.
4709 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4710                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4711   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4712   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4713               true /* check zeros from left */, DAG);
4714   unsigned OpSrc;
4715
4716   if (!NumZeros)
4717     return false;
4718
4719   // Considering the elements in the mask that are not consecutive zeros,
4720   // check if they consecutively come from only one of the source vectors.
4721   //
4722   //                           0    { A, B, X, X } = V2
4723   //                          / \    /  /
4724   //   vector_shuffle V1, V2 <X, X, 4, 5>
4725   //
4726   if (!isShuffleMaskConsecutive(SVOp,
4727             NumZeros,     // Mask Start Index
4728             NumElems,     // Mask End Index(exclusive)
4729             0,            // Where to start looking in the src vector
4730             NumElems,     // Number of elements in vector
4731             OpSrc))       // Which source operand ?
4732     return false;
4733
4734   isLeft = true;
4735   ShAmt = NumZeros;
4736   ShVal = SVOp->getOperand(OpSrc);
4737   return true;
4738 }
4739
4740 /// isVectorShift - Returns true if the shuffle can be implemented as a
4741 /// logical left or right shift of a vector.
4742 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4743                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4744   // Although the logic below support any bitwidth size, there are no
4745   // shift instructions which handle more than 128-bit vectors.
4746   if (SVOp->getValueType(0).getSizeInBits() > 128)
4747     return false;
4748
4749   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4750       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4751     return true;
4752
4753   return false;
4754 }
4755
4756 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4757 ///
4758 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4759                                        unsigned NumNonZero, unsigned NumZero,
4760                                        SelectionDAG &DAG,
4761                                        const X86Subtarget* Subtarget,
4762                                        const TargetLowering &TLI) {
4763   if (NumNonZero > 8)
4764     return SDValue();
4765
4766   DebugLoc dl = Op.getDebugLoc();
4767   SDValue V(0, 0);
4768   bool First = true;
4769   for (unsigned i = 0; i < 16; ++i) {
4770     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4771     if (ThisIsNonZero && First) {
4772       if (NumZero)
4773         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4774       else
4775         V = DAG.getUNDEF(MVT::v8i16);
4776       First = false;
4777     }
4778
4779     if ((i & 1) != 0) {
4780       SDValue ThisElt(0, 0), LastElt(0, 0);
4781       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4782       if (LastIsNonZero) {
4783         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4784                               MVT::i16, Op.getOperand(i-1));
4785       }
4786       if (ThisIsNonZero) {
4787         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4788         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4789                               ThisElt, DAG.getConstant(8, MVT::i8));
4790         if (LastIsNonZero)
4791           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4792       } else
4793         ThisElt = LastElt;
4794
4795       if (ThisElt.getNode())
4796         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4797                         DAG.getIntPtrConstant(i/2));
4798     }
4799   }
4800
4801   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4802 }
4803
4804 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4805 ///
4806 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4807                                      unsigned NumNonZero, unsigned NumZero,
4808                                      SelectionDAG &DAG,
4809                                      const X86Subtarget* Subtarget,
4810                                      const TargetLowering &TLI) {
4811   if (NumNonZero > 4)
4812     return SDValue();
4813
4814   DebugLoc dl = Op.getDebugLoc();
4815   SDValue V(0, 0);
4816   bool First = true;
4817   for (unsigned i = 0; i < 8; ++i) {
4818     bool isNonZero = (NonZeros & (1 << i)) != 0;
4819     if (isNonZero) {
4820       if (First) {
4821         if (NumZero)
4822           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4823         else
4824           V = DAG.getUNDEF(MVT::v8i16);
4825         First = false;
4826       }
4827       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4828                       MVT::v8i16, V, Op.getOperand(i),
4829                       DAG.getIntPtrConstant(i));
4830     }
4831   }
4832
4833   return V;
4834 }
4835
4836 /// getVShift - Return a vector logical shift node.
4837 ///
4838 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4839                          unsigned NumBits, SelectionDAG &DAG,
4840                          const TargetLowering &TLI, DebugLoc dl) {
4841   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4842   EVT ShVT = MVT::v2i64;
4843   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4844   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4845   return DAG.getNode(ISD::BITCAST, dl, VT,
4846                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4847                              DAG.getConstant(NumBits,
4848                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4849 }
4850
4851 SDValue
4852 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4853                                           SelectionDAG &DAG) const {
4854
4855   // Check if the scalar load can be widened into a vector load. And if
4856   // the address is "base + cst" see if the cst can be "absorbed" into
4857   // the shuffle mask.
4858   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4859     SDValue Ptr = LD->getBasePtr();
4860     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4861       return SDValue();
4862     EVT PVT = LD->getValueType(0);
4863     if (PVT != MVT::i32 && PVT != MVT::f32)
4864       return SDValue();
4865
4866     int FI = -1;
4867     int64_t Offset = 0;
4868     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4869       FI = FINode->getIndex();
4870       Offset = 0;
4871     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4872                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4873       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4874       Offset = Ptr.getConstantOperandVal(1);
4875       Ptr = Ptr.getOperand(0);
4876     } else {
4877       return SDValue();
4878     }
4879
4880     // FIXME: 256-bit vector instructions don't require a strict alignment,
4881     // improve this code to support it better.
4882     unsigned RequiredAlign = VT.getSizeInBits()/8;
4883     SDValue Chain = LD->getChain();
4884     // Make sure the stack object alignment is at least 16 or 32.
4885     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4886     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4887       if (MFI->isFixedObjectIndex(FI)) {
4888         // Can't change the alignment. FIXME: It's possible to compute
4889         // the exact stack offset and reference FI + adjust offset instead.
4890         // If someone *really* cares about this. That's the way to implement it.
4891         return SDValue();
4892       } else {
4893         MFI->setObjectAlignment(FI, RequiredAlign);
4894       }
4895     }
4896
4897     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4898     // Ptr + (Offset & ~15).
4899     if (Offset < 0)
4900       return SDValue();
4901     if ((Offset % RequiredAlign) & 3)
4902       return SDValue();
4903     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4904     if (StartOffset)
4905       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4906                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4907
4908     int EltNo = (Offset - StartOffset) >> 2;
4909     unsigned NumElems = VT.getVectorNumElements();
4910
4911     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4912     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4913                              LD->getPointerInfo().getWithOffset(StartOffset),
4914                              false, false, false, 0);
4915
4916     SmallVector<int, 8> Mask;
4917     for (unsigned i = 0; i != NumElems; ++i)
4918       Mask.push_back(EltNo);
4919
4920     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4921   }
4922
4923   return SDValue();
4924 }
4925
4926 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4927 /// vector of type 'VT', see if the elements can be replaced by a single large
4928 /// load which has the same value as a build_vector whose operands are 'elts'.
4929 ///
4930 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4931 ///
4932 /// FIXME: we'd also like to handle the case where the last elements are zero
4933 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4934 /// There's even a handy isZeroNode for that purpose.
4935 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4936                                         DebugLoc &DL, SelectionDAG &DAG) {
4937   EVT EltVT = VT.getVectorElementType();
4938   unsigned NumElems = Elts.size();
4939
4940   LoadSDNode *LDBase = NULL;
4941   unsigned LastLoadedElt = -1U;
4942
4943   // For each element in the initializer, see if we've found a load or an undef.
4944   // If we don't find an initial load element, or later load elements are
4945   // non-consecutive, bail out.
4946   for (unsigned i = 0; i < NumElems; ++i) {
4947     SDValue Elt = Elts[i];
4948
4949     if (!Elt.getNode() ||
4950         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4951       return SDValue();
4952     if (!LDBase) {
4953       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4954         return SDValue();
4955       LDBase = cast<LoadSDNode>(Elt.getNode());
4956       LastLoadedElt = i;
4957       continue;
4958     }
4959     if (Elt.getOpcode() == ISD::UNDEF)
4960       continue;
4961
4962     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4963     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4964       return SDValue();
4965     LastLoadedElt = i;
4966   }
4967
4968   // If we have found an entire vector of loads and undefs, then return a large
4969   // load of the entire vector width starting at the base pointer.  If we found
4970   // consecutive loads for the low half, generate a vzext_load node.
4971   if (LastLoadedElt == NumElems - 1) {
4972     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4973       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4974                          LDBase->getPointerInfo(),
4975                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4976                          LDBase->isInvariant(), 0);
4977     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4978                        LDBase->getPointerInfo(),
4979                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4980                        LDBase->isInvariant(), LDBase->getAlignment());
4981   }
4982   if (NumElems == 4 && LastLoadedElt == 1 &&
4983       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4984     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4985     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4986     SDValue ResNode =
4987         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4988                                 LDBase->getPointerInfo(),
4989                                 LDBase->getAlignment(),
4990                                 false/*isVolatile*/, true/*ReadMem*/,
4991                                 false/*WriteMem*/);
4992     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4993   }
4994   return SDValue();
4995 }
4996
4997 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4998 /// to generate a splat value for the following cases:
4999 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5000 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5001 /// a scalar load, or a constant.
5002 /// The VBROADCAST node is returned when a pattern is found,
5003 /// or SDValue() otherwise.
5004 SDValue
5005 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
5006   if (!Subtarget->hasAVX())
5007     return SDValue();
5008
5009   EVT VT = Op.getValueType();
5010   DebugLoc dl = Op.getDebugLoc();
5011
5012   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5013          "Unsupported vector type for broadcast.");
5014
5015   SDValue Ld;
5016   bool ConstSplatVal;
5017
5018   switch (Op.getOpcode()) {
5019     default:
5020       // Unknown pattern found.
5021       return SDValue();
5022
5023     case ISD::BUILD_VECTOR: {
5024       // The BUILD_VECTOR node must be a splat.
5025       if (!isSplatVector(Op.getNode()))
5026         return SDValue();
5027
5028       Ld = Op.getOperand(0);
5029       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5030                      Ld.getOpcode() == ISD::ConstantFP);
5031
5032       // The suspected load node has several users. Make sure that all
5033       // of its users are from the BUILD_VECTOR node.
5034       // Constants may have multiple users.
5035       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5036         return SDValue();
5037       break;
5038     }
5039
5040     case ISD::VECTOR_SHUFFLE: {
5041       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5042
5043       // Shuffles must have a splat mask where the first element is
5044       // broadcasted.
5045       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5046         return SDValue();
5047
5048       SDValue Sc = Op.getOperand(0);
5049       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5050           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5051
5052         if (!Subtarget->hasAVX2())
5053           return SDValue();
5054
5055         // Use the register form of the broadcast instruction available on AVX2.
5056         if (VT.is256BitVector())
5057           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5058         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5059       }
5060
5061       Ld = Sc.getOperand(0);
5062       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5063                        Ld.getOpcode() == ISD::ConstantFP);
5064
5065       // The scalar_to_vector node and the suspected
5066       // load node must have exactly one user.
5067       // Constants may have multiple users.
5068       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5069         return SDValue();
5070       break;
5071     }
5072   }
5073
5074   bool Is256 = VT.getSizeInBits() == 256;
5075
5076   // Handle the broadcasting a single constant scalar from the constant pool
5077   // into a vector. On Sandybridge it is still better to load a constant vector
5078   // from the constant pool and not to broadcast it from a scalar.
5079   if (ConstSplatVal && Subtarget->hasAVX2()) {
5080     EVT CVT = Ld.getValueType();
5081     assert(!CVT.isVector() && "Must not broadcast a vector type");
5082     unsigned ScalarSize = CVT.getSizeInBits();
5083
5084     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5085       const Constant *C = 0;
5086       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5087         C = CI->getConstantIntValue();
5088       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5089         C = CF->getConstantFPValue();
5090
5091       assert(C && "Invalid constant type");
5092
5093       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5094       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5095       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5096                        MachinePointerInfo::getConstantPool(),
5097                        false, false, false, Alignment);
5098
5099       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5100     }
5101   }
5102
5103   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5104   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5105
5106   // Handle AVX2 in-register broadcasts.
5107   if (!IsLoad && Subtarget->hasAVX2() &&
5108       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5109     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5110
5111   // The scalar source must be a normal load.
5112   if (!IsLoad)
5113     return SDValue();
5114
5115   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5116     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5117
5118   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5119   // double since there is no vbroadcastsd xmm
5120   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5121     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5122       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5123   }
5124
5125   // Unsupported broadcast.
5126   return SDValue();
5127 }
5128
5129 SDValue
5130 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5131   DebugLoc dl = Op.getDebugLoc();
5132
5133   EVT VT = Op.getValueType();
5134   EVT ExtVT = VT.getVectorElementType();
5135   unsigned NumElems = Op.getNumOperands();
5136
5137   // Vectors containing all zeros can be matched by pxor and xorps later
5138   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5139     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5140     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5141     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5142       return Op;
5143
5144     return getZeroVector(VT, Subtarget, DAG, dl);
5145   }
5146
5147   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5148   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5149   // vpcmpeqd on 256-bit vectors.
5150   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5151     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5152       return Op;
5153
5154     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5155   }
5156
5157   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5158   if (Broadcast.getNode())
5159     return Broadcast;
5160
5161   unsigned EVTBits = ExtVT.getSizeInBits();
5162
5163   unsigned NumZero  = 0;
5164   unsigned NumNonZero = 0;
5165   unsigned NonZeros = 0;
5166   bool IsAllConstants = true;
5167   SmallSet<SDValue, 8> Values;
5168   for (unsigned i = 0; i < NumElems; ++i) {
5169     SDValue Elt = Op.getOperand(i);
5170     if (Elt.getOpcode() == ISD::UNDEF)
5171       continue;
5172     Values.insert(Elt);
5173     if (Elt.getOpcode() != ISD::Constant &&
5174         Elt.getOpcode() != ISD::ConstantFP)
5175       IsAllConstants = false;
5176     if (X86::isZeroNode(Elt))
5177       NumZero++;
5178     else {
5179       NonZeros |= (1 << i);
5180       NumNonZero++;
5181     }
5182   }
5183
5184   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5185   if (NumNonZero == 0)
5186     return DAG.getUNDEF(VT);
5187
5188   // Special case for single non-zero, non-undef, element.
5189   if (NumNonZero == 1) {
5190     unsigned Idx = CountTrailingZeros_32(NonZeros);
5191     SDValue Item = Op.getOperand(Idx);
5192
5193     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5194     // the value are obviously zero, truncate the value to i32 and do the
5195     // insertion that way.  Only do this if the value is non-constant or if the
5196     // value is a constant being inserted into element 0.  It is cheaper to do
5197     // a constant pool load than it is to do a movd + shuffle.
5198     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5199         (!IsAllConstants || Idx == 0)) {
5200       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5201         // Handle SSE only.
5202         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5203         EVT VecVT = MVT::v4i32;
5204         unsigned VecElts = 4;
5205
5206         // Truncate the value (which may itself be a constant) to i32, and
5207         // convert it to a vector with movd (S2V+shuffle to zero extend).
5208         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5209         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5210         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5211
5212         // Now we have our 32-bit value zero extended in the low element of
5213         // a vector.  If Idx != 0, swizzle it into place.
5214         if (Idx != 0) {
5215           SmallVector<int, 4> Mask;
5216           Mask.push_back(Idx);
5217           for (unsigned i = 1; i != VecElts; ++i)
5218             Mask.push_back(i);
5219           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5220                                       &Mask[0]);
5221         }
5222         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5223       }
5224     }
5225
5226     // If we have a constant or non-constant insertion into the low element of
5227     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5228     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5229     // depending on what the source datatype is.
5230     if (Idx == 0) {
5231       if (NumZero == 0)
5232         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5233
5234       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5235           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5236         if (VT.getSizeInBits() == 256) {
5237           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5238           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5239                              Item, DAG.getIntPtrConstant(0));
5240         }
5241         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5242         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5243         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5244         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5245       }
5246
5247       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5248         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5249         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5250         if (VT.getSizeInBits() == 256) {
5251           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5252           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5253         } else {
5254           assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5255           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5256         }
5257         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5258       }
5259     }
5260
5261     // Is it a vector logical left shift?
5262     if (NumElems == 2 && Idx == 1 &&
5263         X86::isZeroNode(Op.getOperand(0)) &&
5264         !X86::isZeroNode(Op.getOperand(1))) {
5265       unsigned NumBits = VT.getSizeInBits();
5266       return getVShift(true, VT,
5267                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5268                                    VT, Op.getOperand(1)),
5269                        NumBits/2, DAG, *this, dl);
5270     }
5271
5272     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5273       return SDValue();
5274
5275     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5276     // is a non-constant being inserted into an element other than the low one,
5277     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5278     // movd/movss) to move this into the low element, then shuffle it into
5279     // place.
5280     if (EVTBits == 32) {
5281       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5282
5283       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5284       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5285       SmallVector<int, 8> MaskVec;
5286       for (unsigned i = 0; i != NumElems; ++i)
5287         MaskVec.push_back(i == Idx ? 0 : 1);
5288       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5289     }
5290   }
5291
5292   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5293   if (Values.size() == 1) {
5294     if (EVTBits == 32) {
5295       // Instead of a shuffle like this:
5296       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5297       // Check if it's possible to issue this instead.
5298       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5299       unsigned Idx = CountTrailingZeros_32(NonZeros);
5300       SDValue Item = Op.getOperand(Idx);
5301       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5302         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5303     }
5304     return SDValue();
5305   }
5306
5307   // A vector full of immediates; various special cases are already
5308   // handled, so this is best done with a single constant-pool load.
5309   if (IsAllConstants)
5310     return SDValue();
5311
5312   // For AVX-length vectors, build the individual 128-bit pieces and use
5313   // shuffles to put them in place.
5314   if (VT.getSizeInBits() == 256) {
5315     SmallVector<SDValue, 32> V;
5316     for (unsigned i = 0; i != NumElems; ++i)
5317       V.push_back(Op.getOperand(i));
5318
5319     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5320
5321     // Build both the lower and upper subvector.
5322     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5323     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5324                                 NumElems/2);
5325
5326     // Recreate the wider vector with the lower and upper part.
5327     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5328   }
5329
5330   // Let legalizer expand 2-wide build_vectors.
5331   if (EVTBits == 64) {
5332     if (NumNonZero == 1) {
5333       // One half is zero or undef.
5334       unsigned Idx = CountTrailingZeros_32(NonZeros);
5335       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5336                                  Op.getOperand(Idx));
5337       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5338     }
5339     return SDValue();
5340   }
5341
5342   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5343   if (EVTBits == 8 && NumElems == 16) {
5344     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5345                                         Subtarget, *this);
5346     if (V.getNode()) return V;
5347   }
5348
5349   if (EVTBits == 16 && NumElems == 8) {
5350     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5351                                       Subtarget, *this);
5352     if (V.getNode()) return V;
5353   }
5354
5355   // If element VT is == 32 bits, turn it into a number of shuffles.
5356   SmallVector<SDValue, 8> V(NumElems);
5357   if (NumElems == 4 && NumZero > 0) {
5358     for (unsigned i = 0; i < 4; ++i) {
5359       bool isZero = !(NonZeros & (1 << i));
5360       if (isZero)
5361         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5362       else
5363         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5364     }
5365
5366     for (unsigned i = 0; i < 2; ++i) {
5367       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5368         default: break;
5369         case 0:
5370           V[i] = V[i*2];  // Must be a zero vector.
5371           break;
5372         case 1:
5373           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5374           break;
5375         case 2:
5376           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5377           break;
5378         case 3:
5379           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5380           break;
5381       }
5382     }
5383
5384     bool Reverse1 = (NonZeros & 0x3) == 2;
5385     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5386     int MaskVec[] = {
5387       Reverse1 ? 1 : 0,
5388       Reverse1 ? 0 : 1,
5389       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5390       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5391     };
5392     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5393   }
5394
5395   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5396     // Check for a build vector of consecutive loads.
5397     for (unsigned i = 0; i < NumElems; ++i)
5398       V[i] = Op.getOperand(i);
5399
5400     // Check for elements which are consecutive loads.
5401     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5402     if (LD.getNode())
5403       return LD;
5404
5405     // For SSE 4.1, use insertps to put the high elements into the low element.
5406     if (getSubtarget()->hasSSE41()) {
5407       SDValue Result;
5408       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5409         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5410       else
5411         Result = DAG.getUNDEF(VT);
5412
5413       for (unsigned i = 1; i < NumElems; ++i) {
5414         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5415         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5416                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5417       }
5418       return Result;
5419     }
5420
5421     // Otherwise, expand into a number of unpckl*, start by extending each of
5422     // our (non-undef) elements to the full vector width with the element in the
5423     // bottom slot of the vector (which generates no code for SSE).
5424     for (unsigned i = 0; i < NumElems; ++i) {
5425       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5426         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5427       else
5428         V[i] = DAG.getUNDEF(VT);
5429     }
5430
5431     // Next, we iteratively mix elements, e.g. for v4f32:
5432     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5433     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5434     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5435     unsigned EltStride = NumElems >> 1;
5436     while (EltStride != 0) {
5437       for (unsigned i = 0; i < EltStride; ++i) {
5438         // If V[i+EltStride] is undef and this is the first round of mixing,
5439         // then it is safe to just drop this shuffle: V[i] is already in the
5440         // right place, the one element (since it's the first round) being
5441         // inserted as undef can be dropped.  This isn't safe for successive
5442         // rounds because they will permute elements within both vectors.
5443         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5444             EltStride == NumElems/2)
5445           continue;
5446
5447         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5448       }
5449       EltStride >>= 1;
5450     }
5451     return V[0];
5452   }
5453   return SDValue();
5454 }
5455
5456 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5457 // them in a MMX register.  This is better than doing a stack convert.
5458 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5459   DebugLoc dl = Op.getDebugLoc();
5460   EVT ResVT = Op.getValueType();
5461
5462   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5463          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5464   int Mask[2];
5465   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5466   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5467   InVec = Op.getOperand(1);
5468   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5469     unsigned NumElts = ResVT.getVectorNumElements();
5470     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5471     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5472                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5473   } else {
5474     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5475     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5476     Mask[0] = 0; Mask[1] = 2;
5477     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5478   }
5479   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5480 }
5481
5482 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5483 // to create 256-bit vectors from two other 128-bit ones.
5484 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5485   DebugLoc dl = Op.getDebugLoc();
5486   EVT ResVT = Op.getValueType();
5487
5488   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5489
5490   SDValue V1 = Op.getOperand(0);
5491   SDValue V2 = Op.getOperand(1);
5492   unsigned NumElems = ResVT.getVectorNumElements();
5493
5494   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5495 }
5496
5497 SDValue
5498 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5499   EVT ResVT = Op.getValueType();
5500
5501   assert(Op.getNumOperands() == 2);
5502   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5503          "Unsupported CONCAT_VECTORS for value type");
5504
5505   // We support concatenate two MMX registers and place them in a MMX register.
5506   // This is better than doing a stack convert.
5507   if (ResVT.is128BitVector())
5508     return LowerMMXCONCAT_VECTORS(Op, DAG);
5509
5510   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5511   // from two other 128-bit ones.
5512   return LowerAVXCONCAT_VECTORS(Op, DAG);
5513 }
5514
5515 // Try to lower a shuffle node into a simple blend instruction.
5516 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5517                                           const X86Subtarget *Subtarget,
5518                                           SelectionDAG &DAG) {
5519   SDValue V1 = SVOp->getOperand(0);
5520   SDValue V2 = SVOp->getOperand(1);
5521   DebugLoc dl = SVOp->getDebugLoc();
5522   MVT VT = SVOp->getValueType(0).getSimpleVT();
5523   unsigned NumElems = VT.getVectorNumElements();
5524
5525   if (!Subtarget->hasSSE41())
5526     return SDValue();
5527
5528   unsigned ISDNo = 0;
5529   MVT OpTy;
5530
5531   switch (VT.SimpleTy) {
5532   default: return SDValue();
5533   case MVT::v8i16:
5534     ISDNo = X86ISD::BLENDPW;
5535     OpTy = MVT::v8i16;
5536     break;
5537   case MVT::v4i32:
5538   case MVT::v4f32:
5539     ISDNo = X86ISD::BLENDPS;
5540     OpTy = MVT::v4f32;
5541     break;
5542   case MVT::v2i64:
5543   case MVT::v2f64:
5544     ISDNo = X86ISD::BLENDPD;
5545     OpTy = MVT::v2f64;
5546     break;
5547   case MVT::v8i32:
5548   case MVT::v8f32:
5549     if (!Subtarget->hasAVX())
5550       return SDValue();
5551     ISDNo = X86ISD::BLENDPS;
5552     OpTy = MVT::v8f32;
5553     break;
5554   case MVT::v4i64:
5555   case MVT::v4f64:
5556     if (!Subtarget->hasAVX())
5557       return SDValue();
5558     ISDNo = X86ISD::BLENDPD;
5559     OpTy = MVT::v4f64;
5560     break;
5561   }
5562   assert(ISDNo && "Invalid Op Number");
5563
5564   unsigned MaskVals = 0;
5565
5566   for (unsigned i = 0; i != NumElems; ++i) {
5567     int EltIdx = SVOp->getMaskElt(i);
5568     if (EltIdx == (int)i || EltIdx < 0)
5569       MaskVals |= (1<<i);
5570     else if (EltIdx == (int)(i + NumElems))
5571       continue; // Bit is set to zero;
5572     else
5573       return SDValue();
5574   }
5575
5576   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5577   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5578   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5579                              DAG.getConstant(MaskVals, MVT::i32));
5580   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5581 }
5582
5583 // v8i16 shuffles - Prefer shuffles in the following order:
5584 // 1. [all]   pshuflw, pshufhw, optional move
5585 // 2. [ssse3] 1 x pshufb
5586 // 3. [ssse3] 2 x pshufb + 1 x por
5587 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5588 SDValue
5589 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5590                                             SelectionDAG &DAG) const {
5591   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5592   SDValue V1 = SVOp->getOperand(0);
5593   SDValue V2 = SVOp->getOperand(1);
5594   DebugLoc dl = SVOp->getDebugLoc();
5595   SmallVector<int, 8> MaskVals;
5596
5597   // Determine if more than 1 of the words in each of the low and high quadwords
5598   // of the result come from the same quadword of one of the two inputs.  Undef
5599   // mask values count as coming from any quadword, for better codegen.
5600   unsigned LoQuad[] = { 0, 0, 0, 0 };
5601   unsigned HiQuad[] = { 0, 0, 0, 0 };
5602   std::bitset<4> InputQuads;
5603   for (unsigned i = 0; i < 8; ++i) {
5604     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5605     int EltIdx = SVOp->getMaskElt(i);
5606     MaskVals.push_back(EltIdx);
5607     if (EltIdx < 0) {
5608       ++Quad[0];
5609       ++Quad[1];
5610       ++Quad[2];
5611       ++Quad[3];
5612       continue;
5613     }
5614     ++Quad[EltIdx / 4];
5615     InputQuads.set(EltIdx / 4);
5616   }
5617
5618   int BestLoQuad = -1;
5619   unsigned MaxQuad = 1;
5620   for (unsigned i = 0; i < 4; ++i) {
5621     if (LoQuad[i] > MaxQuad) {
5622       BestLoQuad = i;
5623       MaxQuad = LoQuad[i];
5624     }
5625   }
5626
5627   int BestHiQuad = -1;
5628   MaxQuad = 1;
5629   for (unsigned i = 0; i < 4; ++i) {
5630     if (HiQuad[i] > MaxQuad) {
5631       BestHiQuad = i;
5632       MaxQuad = HiQuad[i];
5633     }
5634   }
5635
5636   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5637   // of the two input vectors, shuffle them into one input vector so only a
5638   // single pshufb instruction is necessary. If There are more than 2 input
5639   // quads, disable the next transformation since it does not help SSSE3.
5640   bool V1Used = InputQuads[0] || InputQuads[1];
5641   bool V2Used = InputQuads[2] || InputQuads[3];
5642   if (Subtarget->hasSSSE3()) {
5643     if (InputQuads.count() == 2 && V1Used && V2Used) {
5644       BestLoQuad = InputQuads[0] ? 0 : 1;
5645       BestHiQuad = InputQuads[2] ? 2 : 3;
5646     }
5647     if (InputQuads.count() > 2) {
5648       BestLoQuad = -1;
5649       BestHiQuad = -1;
5650     }
5651   }
5652
5653   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5654   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5655   // words from all 4 input quadwords.
5656   SDValue NewV;
5657   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5658     int MaskV[] = {
5659       BestLoQuad < 0 ? 0 : BestLoQuad,
5660       BestHiQuad < 0 ? 1 : BestHiQuad
5661     };
5662     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5663                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5664                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5665     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5666
5667     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5668     // source words for the shuffle, to aid later transformations.
5669     bool AllWordsInNewV = true;
5670     bool InOrder[2] = { true, true };
5671     for (unsigned i = 0; i != 8; ++i) {
5672       int idx = MaskVals[i];
5673       if (idx != (int)i)
5674         InOrder[i/4] = false;
5675       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5676         continue;
5677       AllWordsInNewV = false;
5678       break;
5679     }
5680
5681     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5682     if (AllWordsInNewV) {
5683       for (int i = 0; i != 8; ++i) {
5684         int idx = MaskVals[i];
5685         if (idx < 0)
5686           continue;
5687         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5688         if ((idx != i) && idx < 4)
5689           pshufhw = false;
5690         if ((idx != i) && idx > 3)
5691           pshuflw = false;
5692       }
5693       V1 = NewV;
5694       V2Used = false;
5695       BestLoQuad = 0;
5696       BestHiQuad = 1;
5697     }
5698
5699     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5700     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5701     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5702       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5703       unsigned TargetMask = 0;
5704       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5705                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5706       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5707       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5708                              getShufflePSHUFLWImmediate(SVOp);
5709       V1 = NewV.getOperand(0);
5710       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5711     }
5712   }
5713
5714   // If we have SSSE3, and all words of the result are from 1 input vector,
5715   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5716   // is present, fall back to case 4.
5717   if (Subtarget->hasSSSE3()) {
5718     SmallVector<SDValue,16> pshufbMask;
5719
5720     // If we have elements from both input vectors, set the high bit of the
5721     // shuffle mask element to zero out elements that come from V2 in the V1
5722     // mask, and elements that come from V1 in the V2 mask, so that the two
5723     // results can be OR'd together.
5724     bool TwoInputs = V1Used && V2Used;
5725     for (unsigned i = 0; i != 8; ++i) {
5726       int EltIdx = MaskVals[i] * 2;
5727       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5728       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5729       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5730       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5731     }
5732     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5733     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5734                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5735                                  MVT::v16i8, &pshufbMask[0], 16));
5736     if (!TwoInputs)
5737       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5738
5739     // Calculate the shuffle mask for the second input, shuffle it, and
5740     // OR it with the first shuffled input.
5741     pshufbMask.clear();
5742     for (unsigned i = 0; i != 8; ++i) {
5743       int EltIdx = MaskVals[i] * 2;
5744       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5745       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5746       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5747       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5748     }
5749     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5750     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5751                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5752                                  MVT::v16i8, &pshufbMask[0], 16));
5753     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5754     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5755   }
5756
5757   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5758   // and update MaskVals with new element order.
5759   std::bitset<8> InOrder;
5760   if (BestLoQuad >= 0) {
5761     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5762     for (int i = 0; i != 4; ++i) {
5763       int idx = MaskVals[i];
5764       if (idx < 0) {
5765         InOrder.set(i);
5766       } else if ((idx / 4) == BestLoQuad) {
5767         MaskV[i] = idx & 3;
5768         InOrder.set(i);
5769       }
5770     }
5771     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5772                                 &MaskV[0]);
5773
5774     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5775       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5776       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5777                                   NewV.getOperand(0),
5778                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5779     }
5780   }
5781
5782   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5783   // and update MaskVals with the new element order.
5784   if (BestHiQuad >= 0) {
5785     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5786     for (unsigned i = 4; i != 8; ++i) {
5787       int idx = MaskVals[i];
5788       if (idx < 0) {
5789         InOrder.set(i);
5790       } else if ((idx / 4) == BestHiQuad) {
5791         MaskV[i] = (idx & 3) + 4;
5792         InOrder.set(i);
5793       }
5794     }
5795     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5796                                 &MaskV[0]);
5797
5798     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5799       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5800       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5801                                   NewV.getOperand(0),
5802                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5803     }
5804   }
5805
5806   // In case BestHi & BestLo were both -1, which means each quadword has a word
5807   // from each of the four input quadwords, calculate the InOrder bitvector now
5808   // before falling through to the insert/extract cleanup.
5809   if (BestLoQuad == -1 && BestHiQuad == -1) {
5810     NewV = V1;
5811     for (int i = 0; i != 8; ++i)
5812       if (MaskVals[i] < 0 || MaskVals[i] == i)
5813         InOrder.set(i);
5814   }
5815
5816   // The other elements are put in the right place using pextrw and pinsrw.
5817   for (unsigned i = 0; i != 8; ++i) {
5818     if (InOrder[i])
5819       continue;
5820     int EltIdx = MaskVals[i];
5821     if (EltIdx < 0)
5822       continue;
5823     SDValue ExtOp = (EltIdx < 8) ?
5824       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5825                   DAG.getIntPtrConstant(EltIdx)) :
5826       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5827                   DAG.getIntPtrConstant(EltIdx - 8));
5828     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5829                        DAG.getIntPtrConstant(i));
5830   }
5831   return NewV;
5832 }
5833
5834 // v16i8 shuffles - Prefer shuffles in the following order:
5835 // 1. [ssse3] 1 x pshufb
5836 // 2. [ssse3] 2 x pshufb + 1 x por
5837 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5838 static
5839 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5840                                  SelectionDAG &DAG,
5841                                  const X86TargetLowering &TLI) {
5842   SDValue V1 = SVOp->getOperand(0);
5843   SDValue V2 = SVOp->getOperand(1);
5844   DebugLoc dl = SVOp->getDebugLoc();
5845   ArrayRef<int> MaskVals = SVOp->getMask();
5846
5847   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5848
5849   // If we have SSSE3, case 1 is generated when all result bytes come from
5850   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5851   // present, fall back to case 3.
5852
5853   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5854   if (TLI.getSubtarget()->hasSSSE3()) {
5855     SmallVector<SDValue,16> pshufbMask;
5856
5857     // If all result elements are from one input vector, then only translate
5858     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5859     //
5860     // Otherwise, we have elements from both input vectors, and must zero out
5861     // elements that come from V2 in the first mask, and V1 in the second mask
5862     // so that we can OR them together.
5863     for (unsigned i = 0; i != 16; ++i) {
5864       int EltIdx = MaskVals[i];
5865       if (EltIdx < 0 || EltIdx >= 16)
5866         EltIdx = 0x80;
5867       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5868     }
5869     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5870                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5871                                  MVT::v16i8, &pshufbMask[0], 16));
5872     if (V2IsUndef)
5873       return V1;
5874
5875     // Calculate the shuffle mask for the second input, shuffle it, and
5876     // OR it with the first shuffled input.
5877     pshufbMask.clear();
5878     for (unsigned i = 0; i != 16; ++i) {
5879       int EltIdx = MaskVals[i];
5880       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5881       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5882     }
5883     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5884                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5885                                  MVT::v16i8, &pshufbMask[0], 16));
5886     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5887   }
5888
5889   // No SSSE3 - Calculate in place words and then fix all out of place words
5890   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5891   // the 16 different words that comprise the two doublequadword input vectors.
5892   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5893   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5894   SDValue NewV = V1;
5895   for (int i = 0; i != 8; ++i) {
5896     int Elt0 = MaskVals[i*2];
5897     int Elt1 = MaskVals[i*2+1];
5898
5899     // This word of the result is all undef, skip it.
5900     if (Elt0 < 0 && Elt1 < 0)
5901       continue;
5902
5903     // This word of the result is already in the correct place, skip it.
5904     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5905       continue;
5906
5907     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5908     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5909     SDValue InsElt;
5910
5911     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5912     // using a single extract together, load it and store it.
5913     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5914       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5915                            DAG.getIntPtrConstant(Elt1 / 2));
5916       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5917                         DAG.getIntPtrConstant(i));
5918       continue;
5919     }
5920
5921     // If Elt1 is defined, extract it from the appropriate source.  If the
5922     // source byte is not also odd, shift the extracted word left 8 bits
5923     // otherwise clear the bottom 8 bits if we need to do an or.
5924     if (Elt1 >= 0) {
5925       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5926                            DAG.getIntPtrConstant(Elt1 / 2));
5927       if ((Elt1 & 1) == 0)
5928         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5929                              DAG.getConstant(8,
5930                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5931       else if (Elt0 >= 0)
5932         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5933                              DAG.getConstant(0xFF00, MVT::i16));
5934     }
5935     // If Elt0 is defined, extract it from the appropriate source.  If the
5936     // source byte is not also even, shift the extracted word right 8 bits. If
5937     // Elt1 was also defined, OR the extracted values together before
5938     // inserting them in the result.
5939     if (Elt0 >= 0) {
5940       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5941                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5942       if ((Elt0 & 1) != 0)
5943         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5944                               DAG.getConstant(8,
5945                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5946       else if (Elt1 >= 0)
5947         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5948                              DAG.getConstant(0x00FF, MVT::i16));
5949       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5950                          : InsElt0;
5951     }
5952     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5953                        DAG.getIntPtrConstant(i));
5954   }
5955   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5956 }
5957
5958 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5959 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5960 /// done when every pair / quad of shuffle mask elements point to elements in
5961 /// the right sequence. e.g.
5962 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5963 static
5964 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5965                                  SelectionDAG &DAG, DebugLoc dl) {
5966   MVT VT = SVOp->getValueType(0).getSimpleVT();
5967   unsigned NumElems = VT.getVectorNumElements();
5968   MVT NewVT;
5969   unsigned Scale;
5970   switch (VT.SimpleTy) {
5971   default: llvm_unreachable("Unexpected!");
5972   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
5973   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
5974   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
5975   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
5976   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
5977   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
5978   }
5979
5980   SmallVector<int, 8> MaskVec;
5981   for (unsigned i = 0; i != NumElems; i += Scale) {
5982     int StartIdx = -1;
5983     for (unsigned j = 0; j != Scale; ++j) {
5984       int EltIdx = SVOp->getMaskElt(i+j);
5985       if (EltIdx < 0)
5986         continue;
5987       if (StartIdx < 0)
5988         StartIdx = (EltIdx / Scale);
5989       if (EltIdx != (int)(StartIdx*Scale + j))
5990         return SDValue();
5991     }
5992     MaskVec.push_back(StartIdx);
5993   }
5994
5995   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
5996   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
5997   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5998 }
5999
6000 /// getVZextMovL - Return a zero-extending vector move low node.
6001 ///
6002 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6003                             SDValue SrcOp, SelectionDAG &DAG,
6004                             const X86Subtarget *Subtarget, DebugLoc dl) {
6005   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6006     LoadSDNode *LD = NULL;
6007     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6008       LD = dyn_cast<LoadSDNode>(SrcOp);
6009     if (!LD) {
6010       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6011       // instead.
6012       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6013       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6014           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6015           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6016           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6017         // PR2108
6018         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6019         return DAG.getNode(ISD::BITCAST, dl, VT,
6020                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6021                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6022                                                    OpVT,
6023                                                    SrcOp.getOperand(0)
6024                                                           .getOperand(0))));
6025       }
6026     }
6027   }
6028
6029   return DAG.getNode(ISD::BITCAST, dl, VT,
6030                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6031                                  DAG.getNode(ISD::BITCAST, dl,
6032                                              OpVT, SrcOp)));
6033 }
6034
6035 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6036 /// which could not be matched by any known target speficic shuffle
6037 static SDValue
6038 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6039
6040   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6041   if (NewOp.getNode())
6042     return NewOp;
6043
6044   EVT VT = SVOp->getValueType(0);
6045
6046   unsigned NumElems = VT.getVectorNumElements();
6047   unsigned NumLaneElems = NumElems / 2;
6048
6049   DebugLoc dl = SVOp->getDebugLoc();
6050   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6051   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6052   SDValue Output[2];
6053
6054   SmallVector<int, 16> Mask;
6055   for (unsigned l = 0; l < 2; ++l) {
6056     // Build a shuffle mask for the output, discovering on the fly which
6057     // input vectors to use as shuffle operands (recorded in InputUsed).
6058     // If building a suitable shuffle vector proves too hard, then bail
6059     // out with UseBuildVector set.
6060     bool UseBuildVector = false;
6061     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6062     unsigned LaneStart = l * NumLaneElems;
6063     for (unsigned i = 0; i != NumLaneElems; ++i) {
6064       // The mask element.  This indexes into the input.
6065       int Idx = SVOp->getMaskElt(i+LaneStart);
6066       if (Idx < 0) {
6067         // the mask element does not index into any input vector.
6068         Mask.push_back(-1);
6069         continue;
6070       }
6071
6072       // The input vector this mask element indexes into.
6073       int Input = Idx / NumLaneElems;
6074
6075       // Turn the index into an offset from the start of the input vector.
6076       Idx -= Input * NumLaneElems;
6077
6078       // Find or create a shuffle vector operand to hold this input.
6079       unsigned OpNo;
6080       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6081         if (InputUsed[OpNo] == Input)
6082           // This input vector is already an operand.
6083           break;
6084         if (InputUsed[OpNo] < 0) {
6085           // Create a new operand for this input vector.
6086           InputUsed[OpNo] = Input;
6087           break;
6088         }
6089       }
6090
6091       if (OpNo >= array_lengthof(InputUsed)) {
6092         // More than two input vectors used!  Give up on trying to create a
6093         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6094         UseBuildVector = true;
6095         break;
6096       }
6097
6098       // Add the mask index for the new shuffle vector.
6099       Mask.push_back(Idx + OpNo * NumLaneElems);
6100     }
6101
6102     if (UseBuildVector) {
6103       SmallVector<SDValue, 16> SVOps;
6104       for (unsigned i = 0; i != NumLaneElems; ++i) {
6105         // The mask element.  This indexes into the input.
6106         int Idx = SVOp->getMaskElt(i+LaneStart);
6107         if (Idx < 0) {
6108           SVOps.push_back(DAG.getUNDEF(EltVT));
6109           continue;
6110         }
6111
6112         // The input vector this mask element indexes into.
6113         int Input = Idx / NumElems;
6114
6115         // Turn the index into an offset from the start of the input vector.
6116         Idx -= Input * NumElems;
6117
6118         // Extract the vector element by hand.
6119         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6120                                     SVOp->getOperand(Input),
6121                                     DAG.getIntPtrConstant(Idx)));
6122       }
6123
6124       // Construct the output using a BUILD_VECTOR.
6125       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6126                               SVOps.size());
6127     } else if (InputUsed[0] < 0) {
6128       // No input vectors were used! The result is undefined.
6129       Output[l] = DAG.getUNDEF(NVT);
6130     } else {
6131       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6132                                         (InputUsed[0] % 2) * NumLaneElems,
6133                                         DAG, dl);
6134       // If only one input was used, use an undefined vector for the other.
6135       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6136         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6137                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6138       // At least one input vector was used. Create a new shuffle vector.
6139       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6140     }
6141
6142     Mask.clear();
6143   }
6144
6145   // Concatenate the result back
6146   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6147 }
6148
6149 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6150 /// 4 elements, and match them with several different shuffle types.
6151 static SDValue
6152 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6153   SDValue V1 = SVOp->getOperand(0);
6154   SDValue V2 = SVOp->getOperand(1);
6155   DebugLoc dl = SVOp->getDebugLoc();
6156   EVT VT = SVOp->getValueType(0);
6157
6158   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6159
6160   std::pair<int, int> Locs[4];
6161   int Mask1[] = { -1, -1, -1, -1 };
6162   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6163
6164   unsigned NumHi = 0;
6165   unsigned NumLo = 0;
6166   for (unsigned i = 0; i != 4; ++i) {
6167     int Idx = PermMask[i];
6168     if (Idx < 0) {
6169       Locs[i] = std::make_pair(-1, -1);
6170     } else {
6171       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6172       if (Idx < 4) {
6173         Locs[i] = std::make_pair(0, NumLo);
6174         Mask1[NumLo] = Idx;
6175         NumLo++;
6176       } else {
6177         Locs[i] = std::make_pair(1, NumHi);
6178         if (2+NumHi < 4)
6179           Mask1[2+NumHi] = Idx;
6180         NumHi++;
6181       }
6182     }
6183   }
6184
6185   if (NumLo <= 2 && NumHi <= 2) {
6186     // If no more than two elements come from either vector. This can be
6187     // implemented with two shuffles. First shuffle gather the elements.
6188     // The second shuffle, which takes the first shuffle as both of its
6189     // vector operands, put the elements into the right order.
6190     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6191
6192     int Mask2[] = { -1, -1, -1, -1 };
6193
6194     for (unsigned i = 0; i != 4; ++i)
6195       if (Locs[i].first != -1) {
6196         unsigned Idx = (i < 2) ? 0 : 4;
6197         Idx += Locs[i].first * 2 + Locs[i].second;
6198         Mask2[i] = Idx;
6199       }
6200
6201     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6202   }
6203
6204   if (NumLo == 3 || NumHi == 3) {
6205     // Otherwise, we must have three elements from one vector, call it X, and
6206     // one element from the other, call it Y.  First, use a shufps to build an
6207     // intermediate vector with the one element from Y and the element from X
6208     // that will be in the same half in the final destination (the indexes don't
6209     // matter). Then, use a shufps to build the final vector, taking the half
6210     // containing the element from Y from the intermediate, and the other half
6211     // from X.
6212     if (NumHi == 3) {
6213       // Normalize it so the 3 elements come from V1.
6214       CommuteVectorShuffleMask(PermMask, 4);
6215       std::swap(V1, V2);
6216     }
6217
6218     // Find the element from V2.
6219     unsigned HiIndex;
6220     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6221       int Val = PermMask[HiIndex];
6222       if (Val < 0)
6223         continue;
6224       if (Val >= 4)
6225         break;
6226     }
6227
6228     Mask1[0] = PermMask[HiIndex];
6229     Mask1[1] = -1;
6230     Mask1[2] = PermMask[HiIndex^1];
6231     Mask1[3] = -1;
6232     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6233
6234     if (HiIndex >= 2) {
6235       Mask1[0] = PermMask[0];
6236       Mask1[1] = PermMask[1];
6237       Mask1[2] = HiIndex & 1 ? 6 : 4;
6238       Mask1[3] = HiIndex & 1 ? 4 : 6;
6239       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6240     }
6241
6242     Mask1[0] = HiIndex & 1 ? 2 : 0;
6243     Mask1[1] = HiIndex & 1 ? 0 : 2;
6244     Mask1[2] = PermMask[2];
6245     Mask1[3] = PermMask[3];
6246     if (Mask1[2] >= 0)
6247       Mask1[2] += 4;
6248     if (Mask1[3] >= 0)
6249       Mask1[3] += 4;
6250     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6251   }
6252
6253   // Break it into (shuffle shuffle_hi, shuffle_lo).
6254   int LoMask[] = { -1, -1, -1, -1 };
6255   int HiMask[] = { -1, -1, -1, -1 };
6256
6257   int *MaskPtr = LoMask;
6258   unsigned MaskIdx = 0;
6259   unsigned LoIdx = 0;
6260   unsigned HiIdx = 2;
6261   for (unsigned i = 0; i != 4; ++i) {
6262     if (i == 2) {
6263       MaskPtr = HiMask;
6264       MaskIdx = 1;
6265       LoIdx = 0;
6266       HiIdx = 2;
6267     }
6268     int Idx = PermMask[i];
6269     if (Idx < 0) {
6270       Locs[i] = std::make_pair(-1, -1);
6271     } else if (Idx < 4) {
6272       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6273       MaskPtr[LoIdx] = Idx;
6274       LoIdx++;
6275     } else {
6276       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6277       MaskPtr[HiIdx] = Idx;
6278       HiIdx++;
6279     }
6280   }
6281
6282   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6283   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6284   int MaskOps[] = { -1, -1, -1, -1 };
6285   for (unsigned i = 0; i != 4; ++i)
6286     if (Locs[i].first != -1)
6287       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6288   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6289 }
6290
6291 static bool MayFoldVectorLoad(SDValue V) {
6292   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6293     V = V.getOperand(0);
6294   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6295     V = V.getOperand(0);
6296   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6297       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6298     // BUILD_VECTOR (load), undef
6299     V = V.getOperand(0);
6300   if (MayFoldLoad(V))
6301     return true;
6302   return false;
6303 }
6304
6305 // FIXME: the version above should always be used. Since there's
6306 // a bug where several vector shuffles can't be folded because the
6307 // DAG is not updated during lowering and a node claims to have two
6308 // uses while it only has one, use this version, and let isel match
6309 // another instruction if the load really happens to have more than
6310 // one use. Remove this version after this bug get fixed.
6311 // rdar://8434668, PR8156
6312 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6313   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6314     V = V.getOperand(0);
6315   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6316     V = V.getOperand(0);
6317   if (ISD::isNormalLoad(V.getNode()))
6318     return true;
6319   return false;
6320 }
6321
6322 static
6323 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6324   EVT VT = Op.getValueType();
6325
6326   // Canonizalize to v2f64.
6327   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6328   return DAG.getNode(ISD::BITCAST, dl, VT,
6329                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6330                                           V1, DAG));
6331 }
6332
6333 static
6334 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6335                         bool HasSSE2) {
6336   SDValue V1 = Op.getOperand(0);
6337   SDValue V2 = Op.getOperand(1);
6338   EVT VT = Op.getValueType();
6339
6340   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6341
6342   if (HasSSE2 && VT == MVT::v2f64)
6343     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6344
6345   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6346   return DAG.getNode(ISD::BITCAST, dl, VT,
6347                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6348                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6349                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6350 }
6351
6352 static
6353 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6354   SDValue V1 = Op.getOperand(0);
6355   SDValue V2 = Op.getOperand(1);
6356   EVT VT = Op.getValueType();
6357
6358   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6359          "unsupported shuffle type");
6360
6361   if (V2.getOpcode() == ISD::UNDEF)
6362     V2 = V1;
6363
6364   // v4i32 or v4f32
6365   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6366 }
6367
6368 static
6369 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6370   SDValue V1 = Op.getOperand(0);
6371   SDValue V2 = Op.getOperand(1);
6372   EVT VT = Op.getValueType();
6373   unsigned NumElems = VT.getVectorNumElements();
6374
6375   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6376   // operand of these instructions is only memory, so check if there's a
6377   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6378   // same masks.
6379   bool CanFoldLoad = false;
6380
6381   // Trivial case, when V2 comes from a load.
6382   if (MayFoldVectorLoad(V2))
6383     CanFoldLoad = true;
6384
6385   // When V1 is a load, it can be folded later into a store in isel, example:
6386   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6387   //    turns into:
6388   //  (MOVLPSmr addr:$src1, VR128:$src2)
6389   // So, recognize this potential and also use MOVLPS or MOVLPD
6390   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6391     CanFoldLoad = true;
6392
6393   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6394   if (CanFoldLoad) {
6395     if (HasSSE2 && NumElems == 2)
6396       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6397
6398     if (NumElems == 4)
6399       // If we don't care about the second element, proceed to use movss.
6400       if (SVOp->getMaskElt(1) != -1)
6401         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6402   }
6403
6404   // movl and movlp will both match v2i64, but v2i64 is never matched by
6405   // movl earlier because we make it strict to avoid messing with the movlp load
6406   // folding logic (see the code above getMOVLP call). Match it here then,
6407   // this is horrible, but will stay like this until we move all shuffle
6408   // matching to x86 specific nodes. Note that for the 1st condition all
6409   // types are matched with movsd.
6410   if (HasSSE2) {
6411     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6412     // as to remove this logic from here, as much as possible
6413     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6414       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6415     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6416   }
6417
6418   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6419
6420   // Invert the operand order and use SHUFPS to match it.
6421   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6422                               getShuffleSHUFImmediate(SVOp), DAG);
6423 }
6424
6425 SDValue
6426 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6427   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6428   EVT VT = Op.getValueType();
6429   DebugLoc dl = Op.getDebugLoc();
6430   SDValue V1 = Op.getOperand(0);
6431   SDValue V2 = Op.getOperand(1);
6432
6433   if (isZeroShuffle(SVOp))
6434     return getZeroVector(VT, Subtarget, DAG, dl);
6435
6436   // Handle splat operations
6437   if (SVOp->isSplat()) {
6438     unsigned NumElem = VT.getVectorNumElements();
6439     int Size = VT.getSizeInBits();
6440
6441     // Use vbroadcast whenever the splat comes from a foldable load
6442     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6443     if (Broadcast.getNode())
6444       return Broadcast;
6445
6446     // Handle splats by matching through known shuffle masks
6447     if ((Size == 128 && NumElem <= 4) ||
6448         (Size == 256 && NumElem < 8))
6449       return SDValue();
6450
6451     // All remaning splats are promoted to target supported vector shuffles.
6452     return PromoteSplat(SVOp, DAG);
6453   }
6454
6455   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6456   // do it!
6457   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6458       VT == MVT::v16i16 || VT == MVT::v32i8) {
6459     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6460     if (NewOp.getNode())
6461       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6462   } else if ((VT == MVT::v4i32 ||
6463              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6464     // FIXME: Figure out a cleaner way to do this.
6465     // Try to make use of movq to zero out the top part.
6466     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6467       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6468       if (NewOp.getNode()) {
6469         EVT NewVT = NewOp.getValueType();
6470         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6471                                NewVT, true, false))
6472           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6473                               DAG, Subtarget, dl);
6474       }
6475     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6476       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6477       if (NewOp.getNode()) {
6478         EVT NewVT = NewOp.getValueType();
6479         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6480           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6481                               DAG, Subtarget, dl);
6482       }
6483     }
6484   }
6485   return SDValue();
6486 }
6487
6488 SDValue
6489 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6490   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6491   SDValue V1 = Op.getOperand(0);
6492   SDValue V2 = Op.getOperand(1);
6493   EVT VT = Op.getValueType();
6494   DebugLoc dl = Op.getDebugLoc();
6495   unsigned NumElems = VT.getVectorNumElements();
6496   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6497   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6498   bool V1IsSplat = false;
6499   bool V2IsSplat = false;
6500   bool HasSSE2 = Subtarget->hasSSE2();
6501   bool HasAVX    = Subtarget->hasAVX();
6502   bool HasAVX2   = Subtarget->hasAVX2();
6503   MachineFunction &MF = DAG.getMachineFunction();
6504   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6505
6506   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6507
6508   if (V1IsUndef && V2IsUndef)
6509     return DAG.getUNDEF(VT);
6510
6511   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6512
6513   // Vector shuffle lowering takes 3 steps:
6514   //
6515   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6516   //    narrowing and commutation of operands should be handled.
6517   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6518   //    shuffle nodes.
6519   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6520   //    so the shuffle can be broken into other shuffles and the legalizer can
6521   //    try the lowering again.
6522   //
6523   // The general idea is that no vector_shuffle operation should be left to
6524   // be matched during isel, all of them must be converted to a target specific
6525   // node here.
6526
6527   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6528   // narrowing and commutation of operands should be handled. The actual code
6529   // doesn't include all of those, work in progress...
6530   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6531   if (NewOp.getNode())
6532     return NewOp;
6533
6534   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6535
6536   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6537   // unpckh_undef). Only use pshufd if speed is more important than size.
6538   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6539     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6540   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6541     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6542
6543   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6544       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6545     return getMOVDDup(Op, dl, V1, DAG);
6546
6547   if (isMOVHLPS_v_undef_Mask(M, VT))
6548     return getMOVHighToLow(Op, dl, DAG);
6549
6550   // Use to match splats
6551   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6552       (VT == MVT::v2f64 || VT == MVT::v2i64))
6553     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6554
6555   if (isPSHUFDMask(M, VT)) {
6556     // The actual implementation will match the mask in the if above and then
6557     // during isel it can match several different instructions, not only pshufd
6558     // as its name says, sad but true, emulate the behavior for now...
6559     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6560       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6561
6562     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6563
6564     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6565       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6566
6567     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6568       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6569
6570     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6571                                 TargetMask, DAG);
6572   }
6573
6574   // Check if this can be converted into a logical shift.
6575   bool isLeft = false;
6576   unsigned ShAmt = 0;
6577   SDValue ShVal;
6578   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6579   if (isShift && ShVal.hasOneUse()) {
6580     // If the shifted value has multiple uses, it may be cheaper to use
6581     // v_set0 + movlhps or movhlps, etc.
6582     EVT EltVT = VT.getVectorElementType();
6583     ShAmt *= EltVT.getSizeInBits();
6584     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6585   }
6586
6587   if (isMOVLMask(M, VT)) {
6588     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6589       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6590     if (!isMOVLPMask(M, VT)) {
6591       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6592         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6593
6594       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6595         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6596     }
6597   }
6598
6599   // FIXME: fold these into legal mask.
6600   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6601     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6602
6603   if (isMOVHLPSMask(M, VT))
6604     return getMOVHighToLow(Op, dl, DAG);
6605
6606   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6607     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6608
6609   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6610     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6611
6612   if (isMOVLPMask(M, VT))
6613     return getMOVLP(Op, dl, DAG, HasSSE2);
6614
6615   if (ShouldXformToMOVHLPS(M, VT) ||
6616       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6617     return CommuteVectorShuffle(SVOp, DAG);
6618
6619   if (isShift) {
6620     // No better options. Use a vshldq / vsrldq.
6621     EVT EltVT = VT.getVectorElementType();
6622     ShAmt *= EltVT.getSizeInBits();
6623     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6624   }
6625
6626   bool Commuted = false;
6627   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6628   // 1,1,1,1 -> v8i16 though.
6629   V1IsSplat = isSplatVector(V1.getNode());
6630   V2IsSplat = isSplatVector(V2.getNode());
6631
6632   // Canonicalize the splat or undef, if present, to be on the RHS.
6633   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6634     CommuteVectorShuffleMask(M, NumElems);
6635     std::swap(V1, V2);
6636     std::swap(V1IsSplat, V2IsSplat);
6637     Commuted = true;
6638   }
6639
6640   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6641     // Shuffling low element of v1 into undef, just return v1.
6642     if (V2IsUndef)
6643       return V1;
6644     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6645     // the instruction selector will not match, so get a canonical MOVL with
6646     // swapped operands to undo the commute.
6647     return getMOVL(DAG, dl, VT, V2, V1);
6648   }
6649
6650   if (isUNPCKLMask(M, VT, HasAVX2))
6651     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6652
6653   if (isUNPCKHMask(M, VT, HasAVX2))
6654     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6655
6656   if (V2IsSplat) {
6657     // Normalize mask so all entries that point to V2 points to its first
6658     // element then try to match unpck{h|l} again. If match, return a
6659     // new vector_shuffle with the corrected mask.p
6660     SmallVector<int, 8> NewMask(M.begin(), M.end());
6661     NormalizeMask(NewMask, NumElems);
6662     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6663       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6664     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6665       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6666   }
6667
6668   if (Commuted) {
6669     // Commute is back and try unpck* again.
6670     // FIXME: this seems wrong.
6671     CommuteVectorShuffleMask(M, NumElems);
6672     std::swap(V1, V2);
6673     std::swap(V1IsSplat, V2IsSplat);
6674     Commuted = false;
6675
6676     if (isUNPCKLMask(M, VT, HasAVX2))
6677       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6678
6679     if (isUNPCKHMask(M, VT, HasAVX2))
6680       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6681   }
6682
6683   // Normalize the node to match x86 shuffle ops if needed
6684   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6685     return CommuteVectorShuffle(SVOp, DAG);
6686
6687   // The checks below are all present in isShuffleMaskLegal, but they are
6688   // inlined here right now to enable us to directly emit target specific
6689   // nodes, and remove one by one until they don't return Op anymore.
6690
6691   if (isPALIGNRMask(M, VT, Subtarget))
6692     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6693                                 getShufflePALIGNRImmediate(SVOp),
6694                                 DAG);
6695
6696   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6697       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6698     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6699       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6700   }
6701
6702   if (isPSHUFHWMask(M, VT, HasAVX2))
6703     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6704                                 getShufflePSHUFHWImmediate(SVOp),
6705                                 DAG);
6706
6707   if (isPSHUFLWMask(M, VT, HasAVX2))
6708     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6709                                 getShufflePSHUFLWImmediate(SVOp),
6710                                 DAG);
6711
6712   if (isSHUFPMask(M, VT, HasAVX))
6713     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6714                                 getShuffleSHUFImmediate(SVOp), DAG);
6715
6716   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6717     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6718   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6719     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6720
6721   //===--------------------------------------------------------------------===//
6722   // Generate target specific nodes for 128 or 256-bit shuffles only
6723   // supported in the AVX instruction set.
6724   //
6725
6726   // Handle VMOVDDUPY permutations
6727   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6728     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6729
6730   // Handle VPERMILPS/D* permutations
6731   if (isVPERMILPMask(M, VT, HasAVX)) {
6732     if (HasAVX2 && VT == MVT::v8i32)
6733       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6734                                   getShuffleSHUFImmediate(SVOp), DAG);
6735     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6736                                 getShuffleSHUFImmediate(SVOp), DAG);
6737   }
6738
6739   // Handle VPERM2F128/VPERM2I128 permutations
6740   if (isVPERM2X128Mask(M, VT, HasAVX))
6741     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6742                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6743
6744   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6745   if (BlendOp.getNode())
6746     return BlendOp;
6747
6748   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6749     SmallVector<SDValue, 8> permclMask;
6750     for (unsigned i = 0; i != 8; ++i) {
6751       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6752     }
6753     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6754                                &permclMask[0], 8);
6755     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6756     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6757                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6758   }
6759
6760   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6761     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6762                                 getShuffleCLImmediate(SVOp), DAG);
6763
6764
6765   //===--------------------------------------------------------------------===//
6766   // Since no target specific shuffle was selected for this generic one,
6767   // lower it into other known shuffles. FIXME: this isn't true yet, but
6768   // this is the plan.
6769   //
6770
6771   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6772   if (VT == MVT::v8i16) {
6773     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6774     if (NewOp.getNode())
6775       return NewOp;
6776   }
6777
6778   if (VT == MVT::v16i8) {
6779     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6780     if (NewOp.getNode())
6781       return NewOp;
6782   }
6783
6784   // Handle all 128-bit wide vectors with 4 elements, and match them with
6785   // several different shuffle types.
6786   if (NumElems == 4 && VT.getSizeInBits() == 128)
6787     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6788
6789   // Handle general 256-bit shuffles
6790   if (VT.is256BitVector())
6791     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6792
6793   return SDValue();
6794 }
6795
6796 SDValue
6797 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6798                                                 SelectionDAG &DAG) const {
6799   EVT VT = Op.getValueType();
6800   DebugLoc dl = Op.getDebugLoc();
6801
6802   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6803     return SDValue();
6804
6805   if (VT.getSizeInBits() == 8) {
6806     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6807                                     Op.getOperand(0), Op.getOperand(1));
6808     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6809                                     DAG.getValueType(VT));
6810     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6811   }
6812
6813   if (VT.getSizeInBits() == 16) {
6814     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6815     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6816     if (Idx == 0)
6817       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6818                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6819                                      DAG.getNode(ISD::BITCAST, dl,
6820                                                  MVT::v4i32,
6821                                                  Op.getOperand(0)),
6822                                      Op.getOperand(1)));
6823     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6824                                     Op.getOperand(0), Op.getOperand(1));
6825     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6826                                     DAG.getValueType(VT));
6827     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6828   }
6829
6830   if (VT == MVT::f32) {
6831     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6832     // the result back to FR32 register. It's only worth matching if the
6833     // result has a single use which is a store or a bitcast to i32.  And in
6834     // the case of a store, it's not worth it if the index is a constant 0,
6835     // because a MOVSSmr can be used instead, which is smaller and faster.
6836     if (!Op.hasOneUse())
6837       return SDValue();
6838     SDNode *User = *Op.getNode()->use_begin();
6839     if ((User->getOpcode() != ISD::STORE ||
6840          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6841           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6842         (User->getOpcode() != ISD::BITCAST ||
6843          User->getValueType(0) != MVT::i32))
6844       return SDValue();
6845     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6846                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6847                                               Op.getOperand(0)),
6848                                               Op.getOperand(1));
6849     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6850   }
6851
6852   if (VT == MVT::i32 || VT == MVT::i64) {
6853     // ExtractPS/pextrq works with constant index.
6854     if (isa<ConstantSDNode>(Op.getOperand(1)))
6855       return Op;
6856   }
6857   return SDValue();
6858 }
6859
6860
6861 SDValue
6862 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6863                                            SelectionDAG &DAG) const {
6864   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6865     return SDValue();
6866
6867   SDValue Vec = Op.getOperand(0);
6868   EVT VecVT = Vec.getValueType();
6869
6870   // If this is a 256-bit vector result, first extract the 128-bit vector and
6871   // then extract the element from the 128-bit vector.
6872   if (VecVT.getSizeInBits() == 256) {
6873     DebugLoc dl = Op.getNode()->getDebugLoc();
6874     unsigned NumElems = VecVT.getVectorNumElements();
6875     SDValue Idx = Op.getOperand(1);
6876     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6877
6878     // Get the 128-bit vector.
6879     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6880
6881     if (IdxVal >= NumElems/2)
6882       IdxVal -= NumElems/2;
6883     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6884                        DAG.getConstant(IdxVal, MVT::i32));
6885   }
6886
6887   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6888
6889   if (Subtarget->hasSSE41()) {
6890     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6891     if (Res.getNode())
6892       return Res;
6893   }
6894
6895   EVT VT = Op.getValueType();
6896   DebugLoc dl = Op.getDebugLoc();
6897   // TODO: handle v16i8.
6898   if (VT.getSizeInBits() == 16) {
6899     SDValue Vec = Op.getOperand(0);
6900     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6901     if (Idx == 0)
6902       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6903                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6904                                      DAG.getNode(ISD::BITCAST, dl,
6905                                                  MVT::v4i32, Vec),
6906                                      Op.getOperand(1)));
6907     // Transform it so it match pextrw which produces a 32-bit result.
6908     EVT EltVT = MVT::i32;
6909     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6910                                     Op.getOperand(0), Op.getOperand(1));
6911     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6912                                     DAG.getValueType(VT));
6913     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6914   }
6915
6916   if (VT.getSizeInBits() == 32) {
6917     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6918     if (Idx == 0)
6919       return Op;
6920
6921     // SHUFPS the element to the lowest double word, then movss.
6922     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6923     EVT VVT = Op.getOperand(0).getValueType();
6924     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6925                                        DAG.getUNDEF(VVT), Mask);
6926     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6927                        DAG.getIntPtrConstant(0));
6928   }
6929
6930   if (VT.getSizeInBits() == 64) {
6931     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6932     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6933     //        to match extract_elt for f64.
6934     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6935     if (Idx == 0)
6936       return Op;
6937
6938     // UNPCKHPD the element to the lowest double word, then movsd.
6939     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6940     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6941     int Mask[2] = { 1, -1 };
6942     EVT VVT = Op.getOperand(0).getValueType();
6943     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6944                                        DAG.getUNDEF(VVT), Mask);
6945     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6946                        DAG.getIntPtrConstant(0));
6947   }
6948
6949   return SDValue();
6950 }
6951
6952 SDValue
6953 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6954                                                SelectionDAG &DAG) const {
6955   EVT VT = Op.getValueType();
6956   EVT EltVT = VT.getVectorElementType();
6957   DebugLoc dl = Op.getDebugLoc();
6958
6959   SDValue N0 = Op.getOperand(0);
6960   SDValue N1 = Op.getOperand(1);
6961   SDValue N2 = Op.getOperand(2);
6962
6963   if (VT.getSizeInBits() == 256)
6964     return SDValue();
6965
6966   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6967       isa<ConstantSDNode>(N2)) {
6968     unsigned Opc;
6969     if (VT == MVT::v8i16)
6970       Opc = X86ISD::PINSRW;
6971     else if (VT == MVT::v16i8)
6972       Opc = X86ISD::PINSRB;
6973     else
6974       Opc = X86ISD::PINSRB;
6975
6976     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6977     // argument.
6978     if (N1.getValueType() != MVT::i32)
6979       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6980     if (N2.getValueType() != MVT::i32)
6981       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6982     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6983   }
6984
6985   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6986     // Bits [7:6] of the constant are the source select.  This will always be
6987     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6988     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6989     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6990     // Bits [5:4] of the constant are the destination select.  This is the
6991     //  value of the incoming immediate.
6992     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6993     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6994     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6995     // Create this as a scalar to vector..
6996     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6997     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6998   }
6999
7000   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7001     // PINSR* works with constant index.
7002     return Op;
7003   }
7004   return SDValue();
7005 }
7006
7007 SDValue
7008 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7009   EVT VT = Op.getValueType();
7010   EVT EltVT = VT.getVectorElementType();
7011
7012   DebugLoc dl = Op.getDebugLoc();
7013   SDValue N0 = Op.getOperand(0);
7014   SDValue N1 = Op.getOperand(1);
7015   SDValue N2 = Op.getOperand(2);
7016
7017   // If this is a 256-bit vector result, first extract the 128-bit vector,
7018   // insert the element into the extracted half and then place it back.
7019   if (VT.getSizeInBits() == 256) {
7020     if (!isa<ConstantSDNode>(N2))
7021       return SDValue();
7022
7023     // Get the desired 128-bit vector half.
7024     unsigned NumElems = VT.getVectorNumElements();
7025     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7026     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7027
7028     // Insert the element into the desired half.
7029     bool Upper = IdxVal >= NumElems/2;
7030     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7031                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7032
7033     // Insert the changed part back to the 256-bit vector
7034     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7035   }
7036
7037   if (Subtarget->hasSSE41())
7038     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7039
7040   if (EltVT == MVT::i8)
7041     return SDValue();
7042
7043   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7044     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7045     // as its second argument.
7046     if (N1.getValueType() != MVT::i32)
7047       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7048     if (N2.getValueType() != MVT::i32)
7049       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7050     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7051   }
7052   return SDValue();
7053 }
7054
7055 SDValue
7056 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7057   LLVMContext *Context = DAG.getContext();
7058   DebugLoc dl = Op.getDebugLoc();
7059   EVT OpVT = Op.getValueType();
7060
7061   // If this is a 256-bit vector result, first insert into a 128-bit
7062   // vector and then insert into the 256-bit vector.
7063   if (OpVT.getSizeInBits() > 128) {
7064     // Insert into a 128-bit vector.
7065     EVT VT128 = EVT::getVectorVT(*Context,
7066                                  OpVT.getVectorElementType(),
7067                                  OpVT.getVectorNumElements() / 2);
7068
7069     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7070
7071     // Insert the 128-bit vector.
7072     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7073   }
7074
7075   if (OpVT == MVT::v1i64 &&
7076       Op.getOperand(0).getValueType() == MVT::i64)
7077     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7078
7079   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7080   assert(OpVT.getSizeInBits() == 128 && "Expected an SSE type!");
7081   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7082                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7083 }
7084
7085 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7086 // a simple subregister reference or explicit instructions to grab
7087 // upper bits of a vector.
7088 SDValue
7089 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7090   if (Subtarget->hasAVX()) {
7091     DebugLoc dl = Op.getNode()->getDebugLoc();
7092     SDValue Vec = Op.getNode()->getOperand(0);
7093     SDValue Idx = Op.getNode()->getOperand(1);
7094
7095     if (Op.getNode()->getValueType(0).getSizeInBits() == 128 &&
7096         Vec.getNode()->getValueType(0).getSizeInBits() == 256 &&
7097         isa<ConstantSDNode>(Idx)) {
7098       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7099       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7100     }
7101   }
7102   return SDValue();
7103 }
7104
7105 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7106 // simple superregister reference or explicit instructions to insert
7107 // the upper bits of a vector.
7108 SDValue
7109 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7110   if (Subtarget->hasAVX()) {
7111     DebugLoc dl = Op.getNode()->getDebugLoc();
7112     SDValue Vec = Op.getNode()->getOperand(0);
7113     SDValue SubVec = Op.getNode()->getOperand(1);
7114     SDValue Idx = Op.getNode()->getOperand(2);
7115
7116     if (Op.getNode()->getValueType(0).getSizeInBits() == 256 &&
7117         SubVec.getNode()->getValueType(0).getSizeInBits() == 128 &&
7118         isa<ConstantSDNode>(Idx)) {
7119       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7120       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7121     }
7122   }
7123   return SDValue();
7124 }
7125
7126 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7127 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7128 // one of the above mentioned nodes. It has to be wrapped because otherwise
7129 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7130 // be used to form addressing mode. These wrapped nodes will be selected
7131 // into MOV32ri.
7132 SDValue
7133 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7134   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7135
7136   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7137   // global base reg.
7138   unsigned char OpFlag = 0;
7139   unsigned WrapperKind = X86ISD::Wrapper;
7140   CodeModel::Model M = getTargetMachine().getCodeModel();
7141
7142   if (Subtarget->isPICStyleRIPRel() &&
7143       (M == CodeModel::Small || M == CodeModel::Kernel))
7144     WrapperKind = X86ISD::WrapperRIP;
7145   else if (Subtarget->isPICStyleGOT())
7146     OpFlag = X86II::MO_GOTOFF;
7147   else if (Subtarget->isPICStyleStubPIC())
7148     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7149
7150   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7151                                              CP->getAlignment(),
7152                                              CP->getOffset(), OpFlag);
7153   DebugLoc DL = CP->getDebugLoc();
7154   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7155   // With PIC, the address is actually $g + Offset.
7156   if (OpFlag) {
7157     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7158                          DAG.getNode(X86ISD::GlobalBaseReg,
7159                                      DebugLoc(), getPointerTy()),
7160                          Result);
7161   }
7162
7163   return Result;
7164 }
7165
7166 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7167   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7168
7169   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7170   // global base reg.
7171   unsigned char OpFlag = 0;
7172   unsigned WrapperKind = X86ISD::Wrapper;
7173   CodeModel::Model M = getTargetMachine().getCodeModel();
7174
7175   if (Subtarget->isPICStyleRIPRel() &&
7176       (M == CodeModel::Small || M == CodeModel::Kernel))
7177     WrapperKind = X86ISD::WrapperRIP;
7178   else if (Subtarget->isPICStyleGOT())
7179     OpFlag = X86II::MO_GOTOFF;
7180   else if (Subtarget->isPICStyleStubPIC())
7181     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7182
7183   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7184                                           OpFlag);
7185   DebugLoc DL = JT->getDebugLoc();
7186   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7187
7188   // With PIC, the address is actually $g + Offset.
7189   if (OpFlag)
7190     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7191                          DAG.getNode(X86ISD::GlobalBaseReg,
7192                                      DebugLoc(), getPointerTy()),
7193                          Result);
7194
7195   return Result;
7196 }
7197
7198 SDValue
7199 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7200   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7201
7202   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7203   // global base reg.
7204   unsigned char OpFlag = 0;
7205   unsigned WrapperKind = X86ISD::Wrapper;
7206   CodeModel::Model M = getTargetMachine().getCodeModel();
7207
7208   if (Subtarget->isPICStyleRIPRel() &&
7209       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7210     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7211       OpFlag = X86II::MO_GOTPCREL;
7212     WrapperKind = X86ISD::WrapperRIP;
7213   } else if (Subtarget->isPICStyleGOT()) {
7214     OpFlag = X86II::MO_GOT;
7215   } else if (Subtarget->isPICStyleStubPIC()) {
7216     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7217   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7218     OpFlag = X86II::MO_DARWIN_NONLAZY;
7219   }
7220
7221   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7222
7223   DebugLoc DL = Op.getDebugLoc();
7224   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7225
7226
7227   // With PIC, the address is actually $g + Offset.
7228   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7229       !Subtarget->is64Bit()) {
7230     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7231                          DAG.getNode(X86ISD::GlobalBaseReg,
7232                                      DebugLoc(), getPointerTy()),
7233                          Result);
7234   }
7235
7236   // For symbols that require a load from a stub to get the address, emit the
7237   // load.
7238   if (isGlobalStubReference(OpFlag))
7239     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7240                          MachinePointerInfo::getGOT(), false, false, false, 0);
7241
7242   return Result;
7243 }
7244
7245 SDValue
7246 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7247   // Create the TargetBlockAddressAddress node.
7248   unsigned char OpFlags =
7249     Subtarget->ClassifyBlockAddressReference();
7250   CodeModel::Model M = getTargetMachine().getCodeModel();
7251   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7252   DebugLoc dl = Op.getDebugLoc();
7253   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7254                                        /*isTarget=*/true, OpFlags);
7255
7256   if (Subtarget->isPICStyleRIPRel() &&
7257       (M == CodeModel::Small || M == CodeModel::Kernel))
7258     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7259   else
7260     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7261
7262   // With PIC, the address is actually $g + Offset.
7263   if (isGlobalRelativeToPICBase(OpFlags)) {
7264     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7265                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7266                          Result);
7267   }
7268
7269   return Result;
7270 }
7271
7272 SDValue
7273 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7274                                       int64_t Offset,
7275                                       SelectionDAG &DAG) const {
7276   // Create the TargetGlobalAddress node, folding in the constant
7277   // offset if it is legal.
7278   unsigned char OpFlags =
7279     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7280   CodeModel::Model M = getTargetMachine().getCodeModel();
7281   SDValue Result;
7282   if (OpFlags == X86II::MO_NO_FLAG &&
7283       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7284     // A direct static reference to a global.
7285     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7286     Offset = 0;
7287   } else {
7288     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7289   }
7290
7291   if (Subtarget->isPICStyleRIPRel() &&
7292       (M == CodeModel::Small || M == CodeModel::Kernel))
7293     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7294   else
7295     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7296
7297   // With PIC, the address is actually $g + Offset.
7298   if (isGlobalRelativeToPICBase(OpFlags)) {
7299     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7300                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7301                          Result);
7302   }
7303
7304   // For globals that require a load from a stub to get the address, emit the
7305   // load.
7306   if (isGlobalStubReference(OpFlags))
7307     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7308                          MachinePointerInfo::getGOT(), false, false, false, 0);
7309
7310   // If there was a non-zero offset that we didn't fold, create an explicit
7311   // addition for it.
7312   if (Offset != 0)
7313     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7314                          DAG.getConstant(Offset, getPointerTy()));
7315
7316   return Result;
7317 }
7318
7319 SDValue
7320 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7321   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7322   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7323   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7324 }
7325
7326 static SDValue
7327 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7328            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7329            unsigned char OperandFlags, bool LocalDynamic = false) {
7330   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7331   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7332   DebugLoc dl = GA->getDebugLoc();
7333   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7334                                            GA->getValueType(0),
7335                                            GA->getOffset(),
7336                                            OperandFlags);
7337
7338   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7339                                            : X86ISD::TLSADDR;
7340
7341   if (InFlag) {
7342     SDValue Ops[] = { Chain,  TGA, *InFlag };
7343     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7344   } else {
7345     SDValue Ops[]  = { Chain, TGA };
7346     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7347   }
7348
7349   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7350   MFI->setAdjustsStack(true);
7351
7352   SDValue Flag = Chain.getValue(1);
7353   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7354 }
7355
7356 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7357 static SDValue
7358 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7359                                 const EVT PtrVT) {
7360   SDValue InFlag;
7361   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7362   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7363                                      DAG.getNode(X86ISD::GlobalBaseReg,
7364                                                  DebugLoc(), PtrVT), InFlag);
7365   InFlag = Chain.getValue(1);
7366
7367   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7368 }
7369
7370 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7371 static SDValue
7372 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7373                                 const EVT PtrVT) {
7374   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7375                     X86::RAX, X86II::MO_TLSGD);
7376 }
7377
7378 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7379                                            SelectionDAG &DAG,
7380                                            const EVT PtrVT,
7381                                            bool is64Bit) {
7382   DebugLoc dl = GA->getDebugLoc();
7383
7384   // Get the start address of the TLS block for this module.
7385   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7386       .getInfo<X86MachineFunctionInfo>();
7387   MFI->incNumLocalDynamicTLSAccesses();
7388
7389   SDValue Base;
7390   if (is64Bit) {
7391     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7392                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7393   } else {
7394     SDValue InFlag;
7395     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7396         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7397     InFlag = Chain.getValue(1);
7398     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7399                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7400   }
7401
7402   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7403   // of Base.
7404
7405   // Build x@dtpoff.
7406   unsigned char OperandFlags = X86II::MO_DTPOFF;
7407   unsigned WrapperKind = X86ISD::Wrapper;
7408   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7409                                            GA->getValueType(0),
7410                                            GA->getOffset(), OperandFlags);
7411   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7412
7413   // Add x@dtpoff with the base.
7414   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7415 }
7416
7417 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7418 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7419                                    const EVT PtrVT, TLSModel::Model model,
7420                                    bool is64Bit, bool isPIC) {
7421   DebugLoc dl = GA->getDebugLoc();
7422
7423   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7424   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7425                                                          is64Bit ? 257 : 256));
7426
7427   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7428                                       DAG.getIntPtrConstant(0),
7429                                       MachinePointerInfo(Ptr),
7430                                       false, false, false, 0);
7431
7432   unsigned char OperandFlags = 0;
7433   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7434   // initialexec.
7435   unsigned WrapperKind = X86ISD::Wrapper;
7436   if (model == TLSModel::LocalExec) {
7437     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7438   } else if (model == TLSModel::InitialExec) {
7439     if (is64Bit) {
7440       OperandFlags = X86II::MO_GOTTPOFF;
7441       WrapperKind = X86ISD::WrapperRIP;
7442     } else {
7443       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7444     }
7445   } else {
7446     llvm_unreachable("Unexpected model");
7447   }
7448
7449   // emit "addl x@ntpoff,%eax" (local exec)
7450   // or "addl x@indntpoff,%eax" (initial exec)
7451   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7452   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7453                                            GA->getValueType(0),
7454                                            GA->getOffset(), OperandFlags);
7455   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7456
7457   if (model == TLSModel::InitialExec) {
7458     if (isPIC && !is64Bit) {
7459       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7460                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7461                            Offset);
7462     }
7463
7464     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7465                          MachinePointerInfo::getGOT(), false, false, false,
7466                          0);
7467   }
7468
7469   // The address of the thread local variable is the add of the thread
7470   // pointer with the offset of the variable.
7471   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7472 }
7473
7474 SDValue
7475 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7476
7477   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7478   const GlobalValue *GV = GA->getGlobal();
7479
7480   if (Subtarget->isTargetELF()) {
7481     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7482
7483     switch (model) {
7484       case TLSModel::GeneralDynamic:
7485         if (Subtarget->is64Bit())
7486           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7487         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7488       case TLSModel::LocalDynamic:
7489         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7490                                            Subtarget->is64Bit());
7491       case TLSModel::InitialExec:
7492       case TLSModel::LocalExec:
7493         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7494                                    Subtarget->is64Bit(),
7495                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7496     }
7497     llvm_unreachable("Unknown TLS model.");
7498   }
7499
7500   if (Subtarget->isTargetDarwin()) {
7501     // Darwin only has one model of TLS.  Lower to that.
7502     unsigned char OpFlag = 0;
7503     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7504                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7505
7506     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7507     // global base reg.
7508     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7509                   !Subtarget->is64Bit();
7510     if (PIC32)
7511       OpFlag = X86II::MO_TLVP_PIC_BASE;
7512     else
7513       OpFlag = X86II::MO_TLVP;
7514     DebugLoc DL = Op.getDebugLoc();
7515     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7516                                                 GA->getValueType(0),
7517                                                 GA->getOffset(), OpFlag);
7518     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7519
7520     // With PIC32, the address is actually $g + Offset.
7521     if (PIC32)
7522       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7523                            DAG.getNode(X86ISD::GlobalBaseReg,
7524                                        DebugLoc(), getPointerTy()),
7525                            Offset);
7526
7527     // Lowering the machine isd will make sure everything is in the right
7528     // location.
7529     SDValue Chain = DAG.getEntryNode();
7530     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7531     SDValue Args[] = { Chain, Offset };
7532     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7533
7534     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7535     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7536     MFI->setAdjustsStack(true);
7537
7538     // And our return value (tls address) is in the standard call return value
7539     // location.
7540     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7541     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7542                               Chain.getValue(1));
7543   }
7544
7545   if (Subtarget->isTargetWindows()) {
7546     // Just use the implicit TLS architecture
7547     // Need to generate someting similar to:
7548     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7549     //                                  ; from TEB
7550     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7551     //   mov     rcx, qword [rdx+rcx*8]
7552     //   mov     eax, .tls$:tlsvar
7553     //   [rax+rcx] contains the address
7554     // Windows 64bit: gs:0x58
7555     // Windows 32bit: fs:__tls_array
7556
7557     // If GV is an alias then use the aliasee for determining
7558     // thread-localness.
7559     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7560       GV = GA->resolveAliasedGlobal(false);
7561     DebugLoc dl = GA->getDebugLoc();
7562     SDValue Chain = DAG.getEntryNode();
7563
7564     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7565     // %gs:0x58 (64-bit).
7566     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7567                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7568                                                              256)
7569                                         : Type::getInt32PtrTy(*DAG.getContext(),
7570                                                               257));
7571
7572     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7573                                         Subtarget->is64Bit()
7574                                         ? DAG.getIntPtrConstant(0x58)
7575                                         : DAG.getExternalSymbol("_tls_array",
7576                                                                 getPointerTy()),
7577                                         MachinePointerInfo(Ptr),
7578                                         false, false, false, 0);
7579
7580     // Load the _tls_index variable
7581     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7582     if (Subtarget->is64Bit())
7583       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7584                            IDX, MachinePointerInfo(), MVT::i32,
7585                            false, false, 0);
7586     else
7587       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7588                         false, false, false, 0);
7589
7590     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7591                                     getPointerTy());
7592     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7593
7594     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7595     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7596                       false, false, false, 0);
7597
7598     // Get the offset of start of .tls section
7599     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7600                                              GA->getValueType(0),
7601                                              GA->getOffset(), X86II::MO_SECREL);
7602     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7603
7604     // The address of the thread local variable is the add of the thread
7605     // pointer with the offset of the variable.
7606     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7607   }
7608
7609   llvm_unreachable("TLS not implemented for this target.");
7610 }
7611
7612
7613 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7614 /// and take a 2 x i32 value to shift plus a shift amount.
7615 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7616   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7617   EVT VT = Op.getValueType();
7618   unsigned VTBits = VT.getSizeInBits();
7619   DebugLoc dl = Op.getDebugLoc();
7620   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7621   SDValue ShOpLo = Op.getOperand(0);
7622   SDValue ShOpHi = Op.getOperand(1);
7623   SDValue ShAmt  = Op.getOperand(2);
7624   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7625                                      DAG.getConstant(VTBits - 1, MVT::i8))
7626                        : DAG.getConstant(0, VT);
7627
7628   SDValue Tmp2, Tmp3;
7629   if (Op.getOpcode() == ISD::SHL_PARTS) {
7630     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7631     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7632   } else {
7633     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7634     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7635   }
7636
7637   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7638                                 DAG.getConstant(VTBits, MVT::i8));
7639   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7640                              AndNode, DAG.getConstant(0, MVT::i8));
7641
7642   SDValue Hi, Lo;
7643   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7644   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7645   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7646
7647   if (Op.getOpcode() == ISD::SHL_PARTS) {
7648     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7649     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7650   } else {
7651     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7652     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7653   }
7654
7655   SDValue Ops[2] = { Lo, Hi };
7656   return DAG.getMergeValues(Ops, 2, dl);
7657 }
7658
7659 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7660                                            SelectionDAG &DAG) const {
7661   EVT SrcVT = Op.getOperand(0).getValueType();
7662
7663   if (SrcVT.isVector())
7664     return SDValue();
7665
7666   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7667          "Unknown SINT_TO_FP to lower!");
7668
7669   // These are really Legal; return the operand so the caller accepts it as
7670   // Legal.
7671   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7672     return Op;
7673   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7674       Subtarget->is64Bit()) {
7675     return Op;
7676   }
7677
7678   DebugLoc dl = Op.getDebugLoc();
7679   unsigned Size = SrcVT.getSizeInBits()/8;
7680   MachineFunction &MF = DAG.getMachineFunction();
7681   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7682   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7683   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7684                                StackSlot,
7685                                MachinePointerInfo::getFixedStack(SSFI),
7686                                false, false, 0);
7687   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7688 }
7689
7690 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7691                                      SDValue StackSlot,
7692                                      SelectionDAG &DAG) const {
7693   // Build the FILD
7694   DebugLoc DL = Op.getDebugLoc();
7695   SDVTList Tys;
7696   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7697   if (useSSE)
7698     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7699   else
7700     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7701
7702   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7703
7704   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7705   MachineMemOperand *MMO;
7706   if (FI) {
7707     int SSFI = FI->getIndex();
7708     MMO =
7709       DAG.getMachineFunction()
7710       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7711                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7712   } else {
7713     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7714     StackSlot = StackSlot.getOperand(1);
7715   }
7716   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7717   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7718                                            X86ISD::FILD, DL,
7719                                            Tys, Ops, array_lengthof(Ops),
7720                                            SrcVT, MMO);
7721
7722   if (useSSE) {
7723     Chain = Result.getValue(1);
7724     SDValue InFlag = Result.getValue(2);
7725
7726     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7727     // shouldn't be necessary except that RFP cannot be live across
7728     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7729     MachineFunction &MF = DAG.getMachineFunction();
7730     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7731     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7732     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7733     Tys = DAG.getVTList(MVT::Other);
7734     SDValue Ops[] = {
7735       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7736     };
7737     MachineMemOperand *MMO =
7738       DAG.getMachineFunction()
7739       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7740                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7741
7742     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7743                                     Ops, array_lengthof(Ops),
7744                                     Op.getValueType(), MMO);
7745     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7746                          MachinePointerInfo::getFixedStack(SSFI),
7747                          false, false, false, 0);
7748   }
7749
7750   return Result;
7751 }
7752
7753 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7754 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7755                                                SelectionDAG &DAG) const {
7756   // This algorithm is not obvious. Here it is what we're trying to output:
7757   /*
7758      movq       %rax,  %xmm0
7759      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7760      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7761      #ifdef __SSE3__
7762        haddpd   %xmm0, %xmm0          
7763      #else
7764        pshufd   $0x4e, %xmm0, %xmm1 
7765        addpd    %xmm1, %xmm0
7766      #endif
7767   */
7768
7769   DebugLoc dl = Op.getDebugLoc();
7770   LLVMContext *Context = DAG.getContext();
7771
7772   // Build some magic constants.
7773   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7774   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7775   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7776
7777   SmallVector<Constant*,2> CV1;
7778   CV1.push_back(
7779         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7780   CV1.push_back(
7781         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7782   Constant *C1 = ConstantVector::get(CV1);
7783   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7784
7785   // Load the 64-bit value into an XMM register.
7786   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7787                             Op.getOperand(0));
7788   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7789                               MachinePointerInfo::getConstantPool(),
7790                               false, false, false, 16);
7791   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7792                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7793                               CLod0);
7794
7795   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7796                               MachinePointerInfo::getConstantPool(),
7797                               false, false, false, 16);
7798   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7799   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7800   SDValue Result;
7801
7802   if (Subtarget->hasSSE3()) {
7803     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7804     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7805   } else {
7806     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7807     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7808                                            S2F, 0x4E, DAG);
7809     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7810                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7811                          Sub);
7812   }
7813
7814   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7815                      DAG.getIntPtrConstant(0));
7816 }
7817
7818 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7819 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7820                                                SelectionDAG &DAG) const {
7821   DebugLoc dl = Op.getDebugLoc();
7822   // FP constant to bias correct the final result.
7823   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7824                                    MVT::f64);
7825
7826   // Load the 32-bit value into an XMM register.
7827   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7828                              Op.getOperand(0));
7829
7830   // Zero out the upper parts of the register.
7831   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7832
7833   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7834                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7835                      DAG.getIntPtrConstant(0));
7836
7837   // Or the load with the bias.
7838   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7839                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7840                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7841                                                    MVT::v2f64, Load)),
7842                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7843                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7844                                                    MVT::v2f64, Bias)));
7845   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7846                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7847                    DAG.getIntPtrConstant(0));
7848
7849   // Subtract the bias.
7850   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7851
7852   // Handle final rounding.
7853   EVT DestVT = Op.getValueType();
7854
7855   if (DestVT.bitsLT(MVT::f64))
7856     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7857                        DAG.getIntPtrConstant(0));
7858   if (DestVT.bitsGT(MVT::f64))
7859     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7860
7861   // Handle final rounding.
7862   return Sub;
7863 }
7864
7865 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7866                                            SelectionDAG &DAG) const {
7867   SDValue N0 = Op.getOperand(0);
7868   DebugLoc dl = Op.getDebugLoc();
7869
7870   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7871   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7872   // the optimization here.
7873   if (DAG.SignBitIsZero(N0))
7874     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7875
7876   EVT SrcVT = N0.getValueType();
7877   EVT DstVT = Op.getValueType();
7878   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7879     return LowerUINT_TO_FP_i64(Op, DAG);
7880   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7881     return LowerUINT_TO_FP_i32(Op, DAG);
7882   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7883     return SDValue();
7884
7885   // Make a 64-bit buffer, and use it to build an FILD.
7886   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7887   if (SrcVT == MVT::i32) {
7888     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7889     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7890                                      getPointerTy(), StackSlot, WordOff);
7891     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7892                                   StackSlot, MachinePointerInfo(),
7893                                   false, false, 0);
7894     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7895                                   OffsetSlot, MachinePointerInfo(),
7896                                   false, false, 0);
7897     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7898     return Fild;
7899   }
7900
7901   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7902   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7903                                StackSlot, MachinePointerInfo(),
7904                                false, false, 0);
7905   // For i64 source, we need to add the appropriate power of 2 if the input
7906   // was negative.  This is the same as the optimization in
7907   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7908   // we must be careful to do the computation in x87 extended precision, not
7909   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7910   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7911   MachineMemOperand *MMO =
7912     DAG.getMachineFunction()
7913     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7914                           MachineMemOperand::MOLoad, 8, 8);
7915
7916   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7917   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7918   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7919                                          MVT::i64, MMO);
7920
7921   APInt FF(32, 0x5F800000ULL);
7922
7923   // Check whether the sign bit is set.
7924   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7925                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7926                                  ISD::SETLT);
7927
7928   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7929   SDValue FudgePtr = DAG.getConstantPool(
7930                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7931                                          getPointerTy());
7932
7933   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7934   SDValue Zero = DAG.getIntPtrConstant(0);
7935   SDValue Four = DAG.getIntPtrConstant(4);
7936   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7937                                Zero, Four);
7938   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7939
7940   // Load the value out, extending it from f32 to f80.
7941   // FIXME: Avoid the extend by constructing the right constant pool?
7942   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7943                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7944                                  MVT::f32, false, false, 4);
7945   // Extend everything to 80 bits to force it to be done on x87.
7946   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7947   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7948 }
7949
7950 std::pair<SDValue,SDValue> X86TargetLowering::
7951 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7952   DebugLoc DL = Op.getDebugLoc();
7953
7954   EVT DstTy = Op.getValueType();
7955
7956   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7957     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7958     DstTy = MVT::i64;
7959   }
7960
7961   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7962          DstTy.getSimpleVT() >= MVT::i16 &&
7963          "Unknown FP_TO_INT to lower!");
7964
7965   // These are really Legal.
7966   if (DstTy == MVT::i32 &&
7967       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7968     return std::make_pair(SDValue(), SDValue());
7969   if (Subtarget->is64Bit() &&
7970       DstTy == MVT::i64 &&
7971       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7972     return std::make_pair(SDValue(), SDValue());
7973
7974   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
7975   // stack slot, or into the FTOL runtime function.
7976   MachineFunction &MF = DAG.getMachineFunction();
7977   unsigned MemSize = DstTy.getSizeInBits()/8;
7978   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7979   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7980
7981   unsigned Opc;
7982   if (!IsSigned && isIntegerTypeFTOL(DstTy))
7983     Opc = X86ISD::WIN_FTOL;
7984   else
7985     switch (DstTy.getSimpleVT().SimpleTy) {
7986     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7987     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7988     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7989     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7990     }
7991
7992   SDValue Chain = DAG.getEntryNode();
7993   SDValue Value = Op.getOperand(0);
7994   EVT TheVT = Op.getOperand(0).getValueType();
7995   // FIXME This causes a redundant load/store if the SSE-class value is already
7996   // in memory, such as if it is on the callstack.
7997   if (isScalarFPTypeInSSEReg(TheVT)) {
7998     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7999     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8000                          MachinePointerInfo::getFixedStack(SSFI),
8001                          false, false, 0);
8002     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8003     SDValue Ops[] = {
8004       Chain, StackSlot, DAG.getValueType(TheVT)
8005     };
8006
8007     MachineMemOperand *MMO =
8008       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8009                               MachineMemOperand::MOLoad, MemSize, MemSize);
8010     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8011                                     DstTy, MMO);
8012     Chain = Value.getValue(1);
8013     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8014     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8015   }
8016
8017   MachineMemOperand *MMO =
8018     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8019                             MachineMemOperand::MOStore, MemSize, MemSize);
8020
8021   if (Opc != X86ISD::WIN_FTOL) {
8022     // Build the FP_TO_INT*_IN_MEM
8023     SDValue Ops[] = { Chain, Value, StackSlot };
8024     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8025                                            Ops, 3, DstTy, MMO);
8026     return std::make_pair(FIST, StackSlot);
8027   } else {
8028     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8029       DAG.getVTList(MVT::Other, MVT::Glue),
8030       Chain, Value);
8031     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8032       MVT::i32, ftol.getValue(1));
8033     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8034       MVT::i32, eax.getValue(2));
8035     SDValue Ops[] = { eax, edx };
8036     SDValue pair = IsReplace
8037       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8038       : DAG.getMergeValues(Ops, 2, DL);
8039     return std::make_pair(pair, SDValue());
8040   }
8041 }
8042
8043 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8044                                            SelectionDAG &DAG) const {
8045   if (Op.getValueType().isVector())
8046     return SDValue();
8047
8048   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8049     /*IsSigned=*/ true, /*IsReplace=*/ false);
8050   SDValue FIST = Vals.first, StackSlot = Vals.second;
8051   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8052   if (FIST.getNode() == 0) return Op;
8053
8054   if (StackSlot.getNode())
8055     // Load the result.
8056     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8057                        FIST, StackSlot, MachinePointerInfo(),
8058                        false, false, false, 0);
8059
8060   // The node is the result.
8061   return FIST;
8062 }
8063
8064 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8065                                            SelectionDAG &DAG) const {
8066   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8067     /*IsSigned=*/ false, /*IsReplace=*/ false);
8068   SDValue FIST = Vals.first, StackSlot = Vals.second;
8069   assert(FIST.getNode() && "Unexpected failure");
8070
8071   if (StackSlot.getNode())
8072     // Load the result.
8073     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8074                        FIST, StackSlot, MachinePointerInfo(),
8075                        false, false, false, 0);
8076
8077   // The node is the result.
8078   return FIST;
8079 }
8080
8081 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8082                                      SelectionDAG &DAG) const {
8083   LLVMContext *Context = DAG.getContext();
8084   DebugLoc dl = Op.getDebugLoc();
8085   EVT VT = Op.getValueType();
8086   EVT EltVT = VT;
8087   if (VT.isVector())
8088     EltVT = VT.getVectorElementType();
8089   Constant *C;
8090   if (EltVT == MVT::f64) {
8091     C = ConstantVector::getSplat(2, 
8092                 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8093   } else {
8094     C = ConstantVector::getSplat(4,
8095                ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8096   }
8097   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8098   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8099                              MachinePointerInfo::getConstantPool(),
8100                              false, false, false, 16);
8101   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8102 }
8103
8104 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8105   LLVMContext *Context = DAG.getContext();
8106   DebugLoc dl = Op.getDebugLoc();
8107   EVT VT = Op.getValueType();
8108   EVT EltVT = VT;
8109   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8110   if (VT.isVector()) {
8111     EltVT = VT.getVectorElementType();
8112     NumElts = VT.getVectorNumElements();
8113   }
8114   Constant *C;
8115   if (EltVT == MVT::f64)
8116     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8117   else
8118     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8119   C = ConstantVector::getSplat(NumElts, C);
8120   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8121   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8122                              MachinePointerInfo::getConstantPool(),
8123                              false, false, false, 16);
8124   if (VT.isVector()) {
8125     MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
8126     return DAG.getNode(ISD::BITCAST, dl, VT,
8127                        DAG.getNode(ISD::XOR, dl, XORVT,
8128                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8129                                                Op.getOperand(0)),
8130                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8131   }
8132
8133   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8134 }
8135
8136 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8137   LLVMContext *Context = DAG.getContext();
8138   SDValue Op0 = Op.getOperand(0);
8139   SDValue Op1 = Op.getOperand(1);
8140   DebugLoc dl = Op.getDebugLoc();
8141   EVT VT = Op.getValueType();
8142   EVT SrcVT = Op1.getValueType();
8143
8144   // If second operand is smaller, extend it first.
8145   if (SrcVT.bitsLT(VT)) {
8146     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8147     SrcVT = VT;
8148   }
8149   // And if it is bigger, shrink it first.
8150   if (SrcVT.bitsGT(VT)) {
8151     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8152     SrcVT = VT;
8153   }
8154
8155   // At this point the operands and the result should have the same
8156   // type, and that won't be f80 since that is not custom lowered.
8157
8158   // First get the sign bit of second operand.
8159   SmallVector<Constant*,4> CV;
8160   if (SrcVT == MVT::f64) {
8161     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8162     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8163   } else {
8164     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8165     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8166     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8167     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8168   }
8169   Constant *C = ConstantVector::get(CV);
8170   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8171   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8172                               MachinePointerInfo::getConstantPool(),
8173                               false, false, false, 16);
8174   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8175
8176   // Shift sign bit right or left if the two operands have different types.
8177   if (SrcVT.bitsGT(VT)) {
8178     // Op0 is MVT::f32, Op1 is MVT::f64.
8179     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8180     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8181                           DAG.getConstant(32, MVT::i32));
8182     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8183     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8184                           DAG.getIntPtrConstant(0));
8185   }
8186
8187   // Clear first operand sign bit.
8188   CV.clear();
8189   if (VT == MVT::f64) {
8190     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8191     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8192   } else {
8193     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8194     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8195     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8196     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8197   }
8198   C = ConstantVector::get(CV);
8199   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8200   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8201                               MachinePointerInfo::getConstantPool(),
8202                               false, false, false, 16);
8203   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8204
8205   // Or the value with the sign bit.
8206   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8207 }
8208
8209 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8210   SDValue N0 = Op.getOperand(0);
8211   DebugLoc dl = Op.getDebugLoc();
8212   EVT VT = Op.getValueType();
8213
8214   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8215   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8216                                   DAG.getConstant(1, VT));
8217   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8218 }
8219
8220 /// Emit nodes that will be selected as "test Op0,Op0", or something
8221 /// equivalent.
8222 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8223                                     SelectionDAG &DAG) const {
8224   DebugLoc dl = Op.getDebugLoc();
8225
8226   // CF and OF aren't always set the way we want. Determine which
8227   // of these we need.
8228   bool NeedCF = false;
8229   bool NeedOF = false;
8230   switch (X86CC) {
8231   default: break;
8232   case X86::COND_A: case X86::COND_AE:
8233   case X86::COND_B: case X86::COND_BE:
8234     NeedCF = true;
8235     break;
8236   case X86::COND_G: case X86::COND_GE:
8237   case X86::COND_L: case X86::COND_LE:
8238   case X86::COND_O: case X86::COND_NO:
8239     NeedOF = true;
8240     break;
8241   }
8242
8243   // See if we can use the EFLAGS value from the operand instead of
8244   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8245   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8246   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8247     // Emit a CMP with 0, which is the TEST pattern.
8248     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8249                        DAG.getConstant(0, Op.getValueType()));
8250
8251   unsigned Opcode = 0;
8252   unsigned NumOperands = 0;
8253   switch (Op.getNode()->getOpcode()) {
8254   case ISD::ADD:
8255     // Due to an isel shortcoming, be conservative if this add is likely to be
8256     // selected as part of a load-modify-store instruction. When the root node
8257     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8258     // uses of other nodes in the match, such as the ADD in this case. This
8259     // leads to the ADD being left around and reselected, with the result being
8260     // two adds in the output.  Alas, even if none our users are stores, that
8261     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8262     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8263     // climbing the DAG back to the root, and it doesn't seem to be worth the
8264     // effort.
8265     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8266          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8267       if (UI->getOpcode() != ISD::CopyToReg &&
8268           UI->getOpcode() != ISD::SETCC &&
8269           UI->getOpcode() != ISD::STORE)
8270         goto default_case;
8271
8272     if (ConstantSDNode *C =
8273         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8274       // An add of one will be selected as an INC.
8275       if (C->getAPIntValue() == 1) {
8276         Opcode = X86ISD::INC;
8277         NumOperands = 1;
8278         break;
8279       }
8280
8281       // An add of negative one (subtract of one) will be selected as a DEC.
8282       if (C->getAPIntValue().isAllOnesValue()) {
8283         Opcode = X86ISD::DEC;
8284         NumOperands = 1;
8285         break;
8286       }
8287     }
8288
8289     // Otherwise use a regular EFLAGS-setting add.
8290     Opcode = X86ISD::ADD;
8291     NumOperands = 2;
8292     break;
8293   case ISD::AND: {
8294     // If the primary and result isn't used, don't bother using X86ISD::AND,
8295     // because a TEST instruction will be better.
8296     bool NonFlagUse = false;
8297     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8298            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8299       SDNode *User = *UI;
8300       unsigned UOpNo = UI.getOperandNo();
8301       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8302         // Look pass truncate.
8303         UOpNo = User->use_begin().getOperandNo();
8304         User = *User->use_begin();
8305       }
8306
8307       if (User->getOpcode() != ISD::BRCOND &&
8308           User->getOpcode() != ISD::SETCC &&
8309           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8310         NonFlagUse = true;
8311         break;
8312       }
8313     }
8314
8315     if (!NonFlagUse)
8316       break;
8317   }
8318     // FALL THROUGH
8319   case ISD::SUB:
8320   case ISD::OR:
8321   case ISD::XOR:
8322     // Due to the ISEL shortcoming noted above, be conservative if this op is
8323     // likely to be selected as part of a load-modify-store instruction.
8324     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8325            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8326       if (UI->getOpcode() == ISD::STORE)
8327         goto default_case;
8328
8329     // Otherwise use a regular EFLAGS-setting instruction.
8330     switch (Op.getNode()->getOpcode()) {
8331     default: llvm_unreachable("unexpected operator!");
8332     case ISD::SUB:
8333       // If the only use of SUB is EFLAGS, use CMP instead.
8334       if (Op.hasOneUse())
8335         Opcode = X86ISD::CMP;
8336       else
8337         Opcode = X86ISD::SUB;
8338       break;
8339     case ISD::OR:  Opcode = X86ISD::OR;  break;
8340     case ISD::XOR: Opcode = X86ISD::XOR; break;
8341     case ISD::AND: Opcode = X86ISD::AND; break;
8342     }
8343
8344     NumOperands = 2;
8345     break;
8346   case X86ISD::ADD:
8347   case X86ISD::SUB:
8348   case X86ISD::INC:
8349   case X86ISD::DEC:
8350   case X86ISD::OR:
8351   case X86ISD::XOR:
8352   case X86ISD::AND:
8353     return SDValue(Op.getNode(), 1);
8354   default:
8355   default_case:
8356     break;
8357   }
8358
8359   if (Opcode == 0)
8360     // Emit a CMP with 0, which is the TEST pattern.
8361     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8362                        DAG.getConstant(0, Op.getValueType()));
8363
8364   if (Opcode == X86ISD::CMP) {
8365     SDValue New = DAG.getNode(Opcode, dl, MVT::i32, Op.getOperand(0),
8366                               Op.getOperand(1));
8367     // We can't replace usage of SUB with CMP.
8368     // The SUB node will be removed later because there is no use of it.
8369     return SDValue(New.getNode(), 0);
8370   }
8371
8372   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8373   SmallVector<SDValue, 4> Ops;
8374   for (unsigned i = 0; i != NumOperands; ++i)
8375     Ops.push_back(Op.getOperand(i));
8376
8377   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8378   DAG.ReplaceAllUsesWith(Op, New);
8379   return SDValue(New.getNode(), 1);
8380 }
8381
8382 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8383 /// equivalent.
8384 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8385                                    SelectionDAG &DAG) const {
8386   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8387     if (C->getAPIntValue() == 0)
8388       return EmitTest(Op0, X86CC, DAG);
8389
8390   DebugLoc dl = Op0.getDebugLoc();
8391   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8392 }
8393
8394 /// Convert a comparison if required by the subtarget.
8395 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8396                                                  SelectionDAG &DAG) const {
8397   // If the subtarget does not support the FUCOMI instruction, floating-point
8398   // comparisons have to be converted.
8399   if (Subtarget->hasCMov() ||
8400       Cmp.getOpcode() != X86ISD::CMP ||
8401       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8402       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8403     return Cmp;
8404
8405   // The instruction selector will select an FUCOM instruction instead of
8406   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8407   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8408   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8409   DebugLoc dl = Cmp.getDebugLoc();
8410   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8411   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8412   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8413                             DAG.getConstant(8, MVT::i8));
8414   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8415   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8416 }
8417
8418 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8419 /// if it's possible.
8420 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8421                                      DebugLoc dl, SelectionDAG &DAG) const {
8422   SDValue Op0 = And.getOperand(0);
8423   SDValue Op1 = And.getOperand(1);
8424   if (Op0.getOpcode() == ISD::TRUNCATE)
8425     Op0 = Op0.getOperand(0);
8426   if (Op1.getOpcode() == ISD::TRUNCATE)
8427     Op1 = Op1.getOperand(0);
8428
8429   SDValue LHS, RHS;
8430   if (Op1.getOpcode() == ISD::SHL)
8431     std::swap(Op0, Op1);
8432   if (Op0.getOpcode() == ISD::SHL) {
8433     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8434       if (And00C->getZExtValue() == 1) {
8435         // If we looked past a truncate, check that it's only truncating away
8436         // known zeros.
8437         unsigned BitWidth = Op0.getValueSizeInBits();
8438         unsigned AndBitWidth = And.getValueSizeInBits();
8439         if (BitWidth > AndBitWidth) {
8440           APInt Zeros, Ones;
8441           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8442           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8443             return SDValue();
8444         }
8445         LHS = Op1;
8446         RHS = Op0.getOperand(1);
8447       }
8448   } else if (Op1.getOpcode() == ISD::Constant) {
8449     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8450     uint64_t AndRHSVal = AndRHS->getZExtValue();
8451     SDValue AndLHS = Op0;
8452
8453     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8454       LHS = AndLHS.getOperand(0);
8455       RHS = AndLHS.getOperand(1);
8456     }
8457
8458     // Use BT if the immediate can't be encoded in a TEST instruction.
8459     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8460       LHS = AndLHS;
8461       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8462     }
8463   }
8464
8465   if (LHS.getNode()) {
8466     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8467     // instruction.  Since the shift amount is in-range-or-undefined, we know
8468     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8469     // the encoding for the i16 version is larger than the i32 version.
8470     // Also promote i16 to i32 for performance / code size reason.
8471     if (LHS.getValueType() == MVT::i8 ||
8472         LHS.getValueType() == MVT::i16)
8473       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8474
8475     // If the operand types disagree, extend the shift amount to match.  Since
8476     // BT ignores high bits (like shifts) we can use anyextend.
8477     if (LHS.getValueType() != RHS.getValueType())
8478       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8479
8480     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8481     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8482     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8483                        DAG.getConstant(Cond, MVT::i8), BT);
8484   }
8485
8486   return SDValue();
8487 }
8488
8489 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8490
8491   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8492
8493   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8494   SDValue Op0 = Op.getOperand(0);
8495   SDValue Op1 = Op.getOperand(1);
8496   DebugLoc dl = Op.getDebugLoc();
8497   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8498
8499   // Optimize to BT if possible.
8500   // Lower (X & (1 << N)) == 0 to BT(X, N).
8501   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8502   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8503   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8504       Op1.getOpcode() == ISD::Constant &&
8505       cast<ConstantSDNode>(Op1)->isNullValue() &&
8506       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8507     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8508     if (NewSetCC.getNode())
8509       return NewSetCC;
8510   }
8511
8512   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8513   // these.
8514   if (Op1.getOpcode() == ISD::Constant &&
8515       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8516        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8517       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8518
8519     // If the input is a setcc, then reuse the input setcc or use a new one with
8520     // the inverted condition.
8521     if (Op0.getOpcode() == X86ISD::SETCC) {
8522       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8523       bool Invert = (CC == ISD::SETNE) ^
8524         cast<ConstantSDNode>(Op1)->isNullValue();
8525       if (!Invert) return Op0;
8526
8527       CCode = X86::GetOppositeBranchCondition(CCode);
8528       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8529                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8530     }
8531   }
8532
8533   bool isFP = Op1.getValueType().isFloatingPoint();
8534   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8535   if (X86CC == X86::COND_INVALID)
8536     return SDValue();
8537
8538   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8539   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8540   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8541                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8542 }
8543
8544 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8545 // ones, and then concatenate the result back.
8546 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8547   EVT VT = Op.getValueType();
8548
8549   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8550          "Unsupported value type for operation");
8551
8552   unsigned NumElems = VT.getVectorNumElements();
8553   DebugLoc dl = Op.getDebugLoc();
8554   SDValue CC = Op.getOperand(2);
8555
8556   // Extract the LHS vectors
8557   SDValue LHS = Op.getOperand(0);
8558   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8559   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8560
8561   // Extract the RHS vectors
8562   SDValue RHS = Op.getOperand(1);
8563   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8564   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8565
8566   // Issue the operation on the smaller types and concatenate the result back
8567   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8568   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8569   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8570                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8571                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8572 }
8573
8574
8575 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8576   SDValue Cond;
8577   SDValue Op0 = Op.getOperand(0);
8578   SDValue Op1 = Op.getOperand(1);
8579   SDValue CC = Op.getOperand(2);
8580   EVT VT = Op.getValueType();
8581   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8582   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8583   DebugLoc dl = Op.getDebugLoc();
8584
8585   if (isFP) {
8586     unsigned SSECC = 8;
8587     EVT EltVT = Op0.getValueType().getVectorElementType();
8588     assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8589
8590     bool Swap = false;
8591
8592     // SSE Condition code mapping:
8593     //  0 - EQ
8594     //  1 - LT
8595     //  2 - LE
8596     //  3 - UNORD
8597     //  4 - NEQ
8598     //  5 - NLT
8599     //  6 - NLE
8600     //  7 - ORD
8601     switch (SetCCOpcode) {
8602     default: break;
8603     case ISD::SETOEQ:
8604     case ISD::SETEQ:  SSECC = 0; break;
8605     case ISD::SETOGT:
8606     case ISD::SETGT: Swap = true; // Fallthrough
8607     case ISD::SETLT:
8608     case ISD::SETOLT: SSECC = 1; break;
8609     case ISD::SETOGE:
8610     case ISD::SETGE: Swap = true; // Fallthrough
8611     case ISD::SETLE:
8612     case ISD::SETOLE: SSECC = 2; break;
8613     case ISD::SETUO:  SSECC = 3; break;
8614     case ISD::SETUNE:
8615     case ISD::SETNE:  SSECC = 4; break;
8616     case ISD::SETULE: Swap = true;
8617     case ISD::SETUGE: SSECC = 5; break;
8618     case ISD::SETULT: Swap = true;
8619     case ISD::SETUGT: SSECC = 6; break;
8620     case ISD::SETO:   SSECC = 7; break;
8621     }
8622     if (Swap)
8623       std::swap(Op0, Op1);
8624
8625     // In the two special cases we can't handle, emit two comparisons.
8626     if (SSECC == 8) {
8627       if (SetCCOpcode == ISD::SETUEQ) {
8628         SDValue UNORD, EQ;
8629         UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8630                             DAG.getConstant(3, MVT::i8));
8631         EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8632                          DAG.getConstant(0, MVT::i8));
8633         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8634       }
8635       if (SetCCOpcode == ISD::SETONE) {
8636         SDValue ORD, NEQ;
8637         ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8638                           DAG.getConstant(7, MVT::i8));
8639         NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8640                           DAG.getConstant(4, MVT::i8));
8641         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8642       }
8643       llvm_unreachable("Illegal FP comparison");
8644     }
8645     // Handle all other FP comparisons here.
8646     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8647                        DAG.getConstant(SSECC, MVT::i8));
8648   }
8649
8650   // Break 256-bit integer vector compare into smaller ones.
8651   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8652     return Lower256IntVSETCC(Op, DAG);
8653
8654   // We are handling one of the integer comparisons here.  Since SSE only has
8655   // GT and EQ comparisons for integer, swapping operands and multiple
8656   // operations may be required for some comparisons.
8657   unsigned Opc = 0;
8658   bool Swap = false, Invert = false, FlipSigns = false;
8659
8660   switch (SetCCOpcode) {
8661   default: break;
8662   case ISD::SETNE:  Invert = true;
8663   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8664   case ISD::SETLT:  Swap = true;
8665   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8666   case ISD::SETGE:  Swap = true;
8667   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8668   case ISD::SETULT: Swap = true;
8669   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8670   case ISD::SETUGE: Swap = true;
8671   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8672   }
8673   if (Swap)
8674     std::swap(Op0, Op1);
8675
8676   // Check that the operation in question is available (most are plain SSE2,
8677   // but PCMPGTQ and PCMPEQQ have different requirements).
8678   if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8679     return SDValue();
8680   if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8681     return SDValue();
8682
8683   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8684   // bits of the inputs before performing those operations.
8685   if (FlipSigns) {
8686     EVT EltVT = VT.getVectorElementType();
8687     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8688                                       EltVT);
8689     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8690     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8691                                     SignBits.size());
8692     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8693     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8694   }
8695
8696   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8697
8698   // If the logical-not of the result is required, perform that now.
8699   if (Invert)
8700     Result = DAG.getNOT(dl, Result, VT);
8701
8702   return Result;
8703 }
8704
8705 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8706 static bool isX86LogicalCmp(SDValue Op) {
8707   unsigned Opc = Op.getNode()->getOpcode();
8708   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8709       Opc == X86ISD::SAHF)
8710     return true;
8711   if (Op.getResNo() == 1 &&
8712       (Opc == X86ISD::ADD ||
8713        Opc == X86ISD::SUB ||
8714        Opc == X86ISD::ADC ||
8715        Opc == X86ISD::SBB ||
8716        Opc == X86ISD::SMUL ||
8717        Opc == X86ISD::UMUL ||
8718        Opc == X86ISD::INC ||
8719        Opc == X86ISD::DEC ||
8720        Opc == X86ISD::OR ||
8721        Opc == X86ISD::XOR ||
8722        Opc == X86ISD::AND))
8723     return true;
8724
8725   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8726     return true;
8727
8728   return false;
8729 }
8730
8731 static bool isZero(SDValue V) {
8732   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8733   return C && C->isNullValue();
8734 }
8735
8736 static bool isAllOnes(SDValue V) {
8737   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8738   return C && C->isAllOnesValue();
8739 }
8740
8741 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8742   bool addTest = true;
8743   SDValue Cond  = Op.getOperand(0);
8744   SDValue Op1 = Op.getOperand(1);
8745   SDValue Op2 = Op.getOperand(2);
8746   DebugLoc DL = Op.getDebugLoc();
8747   SDValue CC;
8748
8749   if (Cond.getOpcode() == ISD::SETCC) {
8750     SDValue NewCond = LowerSETCC(Cond, DAG);
8751     if (NewCond.getNode())
8752       Cond = NewCond;
8753   }
8754
8755   // Handle the following cases related to max and min:
8756   // (a > b) ? (a-b) : 0
8757   // (a >= b) ? (a-b) : 0
8758   // (b < a) ? (a-b) : 0
8759   // (b <= a) ? (a-b) : 0
8760   // Comparison is removed to use EFLAGS from SUB.
8761   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2))
8762     if (Cond.getOpcode() == X86ISD::SETCC &&
8763         Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8764         (Op1.getOpcode() == ISD::SUB || Op1.getOpcode() == X86ISD::SUB) &&
8765         C->getAPIntValue() == 0) {
8766       SDValue Cmp = Cond.getOperand(1);
8767       unsigned CC = cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8768       if ((DAG.isEqualTo(Op1.getOperand(0), Cmp.getOperand(0)) &&
8769            DAG.isEqualTo(Op1.getOperand(1), Cmp.getOperand(1)) &&
8770            (CC == X86::COND_G || CC == X86::COND_GE ||
8771             CC == X86::COND_A || CC == X86::COND_AE)) ||
8772           (DAG.isEqualTo(Op1.getOperand(0), Cmp.getOperand(1)) &&
8773            DAG.isEqualTo(Op1.getOperand(1), Cmp.getOperand(0)) &&
8774            (CC == X86::COND_L || CC == X86::COND_LE ||
8775             CC == X86::COND_B || CC == X86::COND_BE))) {
8776
8777         if (Op1.getOpcode() == ISD::SUB) {
8778           SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i32);
8779           SDValue New = DAG.getNode(X86ISD::SUB, DL, VTs,
8780                                     Op1.getOperand(0), Op1.getOperand(1));
8781           DAG.ReplaceAllUsesWith(Op1, New);
8782           Op1 = New;
8783         }
8784
8785         SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8786         unsigned NewCC = (CC == X86::COND_G || CC == X86::COND_GE ||
8787                           CC == X86::COND_L ||
8788                           CC == X86::COND_LE) ? X86::COND_GE : X86::COND_AE;
8789         SDValue Ops[] = { Op2, Op1, DAG.getConstant(NewCC, MVT::i8),
8790                           SDValue(Op1.getNode(), 1) };
8791         return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8792       }
8793     }
8794
8795   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8796   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8797   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8798   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8799   if (Cond.getOpcode() == X86ISD::SETCC &&
8800       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8801       isZero(Cond.getOperand(1).getOperand(1))) {
8802     SDValue Cmp = Cond.getOperand(1);
8803
8804     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8805
8806     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8807         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8808       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8809
8810       SDValue CmpOp0 = Cmp.getOperand(0);
8811       // Apply further optimizations for special cases
8812       // (select (x != 0), -1, 0) -> neg & sbb
8813       // (select (x == 0), 0, -1) -> neg & sbb
8814       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8815         if (YC->isNullValue() && 
8816             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8817           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8818           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs, 
8819                                     DAG.getConstant(0, CmpOp0.getValueType()), 
8820                                     CmpOp0);
8821           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8822                                     DAG.getConstant(X86::COND_B, MVT::i8),
8823                                     SDValue(Neg.getNode(), 1));
8824           return Res;
8825         }
8826
8827       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8828                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8829       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8830
8831       SDValue Res =   // Res = 0 or -1.
8832         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8833                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8834
8835       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8836         Res = DAG.getNOT(DL, Res, Res.getValueType());
8837
8838       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8839       if (N2C == 0 || !N2C->isNullValue())
8840         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8841       return Res;
8842     }
8843   }
8844
8845   // Look past (and (setcc_carry (cmp ...)), 1).
8846   if (Cond.getOpcode() == ISD::AND &&
8847       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8848     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8849     if (C && C->getAPIntValue() == 1)
8850       Cond = Cond.getOperand(0);
8851   }
8852
8853   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8854   // setting operand in place of the X86ISD::SETCC.
8855   unsigned CondOpcode = Cond.getOpcode();
8856   if (CondOpcode == X86ISD::SETCC ||
8857       CondOpcode == X86ISD::SETCC_CARRY) {
8858     CC = Cond.getOperand(0);
8859
8860     SDValue Cmp = Cond.getOperand(1);
8861     unsigned Opc = Cmp.getOpcode();
8862     EVT VT = Op.getValueType();
8863
8864     bool IllegalFPCMov = false;
8865     if (VT.isFloatingPoint() && !VT.isVector() &&
8866         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8867       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8868
8869     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8870         Opc == X86ISD::BT) { // FIXME
8871       Cond = Cmp;
8872       addTest = false;
8873     }
8874   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8875              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8876              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8877               Cond.getOperand(0).getValueType() != MVT::i8)) {
8878     SDValue LHS = Cond.getOperand(0);
8879     SDValue RHS = Cond.getOperand(1);
8880     unsigned X86Opcode;
8881     unsigned X86Cond;
8882     SDVTList VTs;
8883     switch (CondOpcode) {
8884     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8885     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8886     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8887     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8888     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8889     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8890     default: llvm_unreachable("unexpected overflowing operator");
8891     }
8892     if (CondOpcode == ISD::UMULO)
8893       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8894                           MVT::i32);
8895     else
8896       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8897
8898     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8899
8900     if (CondOpcode == ISD::UMULO)
8901       Cond = X86Op.getValue(2);
8902     else
8903       Cond = X86Op.getValue(1);
8904
8905     CC = DAG.getConstant(X86Cond, MVT::i8);
8906     addTest = false;
8907   }
8908
8909   if (addTest) {
8910     // Look pass the truncate.
8911     if (Cond.getOpcode() == ISD::TRUNCATE)
8912       Cond = Cond.getOperand(0);
8913
8914     // We know the result of AND is compared against zero. Try to match
8915     // it to BT.
8916     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8917       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8918       if (NewSetCC.getNode()) {
8919         CC = NewSetCC.getOperand(0);
8920         Cond = NewSetCC.getOperand(1);
8921         addTest = false;
8922       }
8923     }
8924   }
8925
8926   if (addTest) {
8927     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8928     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8929   }
8930
8931   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8932   // a <  b ?  0 : -1 -> RES = setcc_carry
8933   // a >= b ? -1 :  0 -> RES = setcc_carry
8934   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8935   if (Cond.getOpcode() == X86ISD::CMP) {
8936     Cond = ConvertCmpIfNecessary(Cond, DAG);
8937     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8938
8939     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8940         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8941       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8942                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8943       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8944         return DAG.getNOT(DL, Res, Res.getValueType());
8945       return Res;
8946     }
8947   }
8948
8949   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8950   // condition is true.
8951   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8952   SDValue Ops[] = { Op2, Op1, CC, Cond };
8953   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8954 }
8955
8956 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8957 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8958 // from the AND / OR.
8959 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8960   Opc = Op.getOpcode();
8961   if (Opc != ISD::OR && Opc != ISD::AND)
8962     return false;
8963   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8964           Op.getOperand(0).hasOneUse() &&
8965           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8966           Op.getOperand(1).hasOneUse());
8967 }
8968
8969 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8970 // 1 and that the SETCC node has a single use.
8971 static bool isXor1OfSetCC(SDValue Op) {
8972   if (Op.getOpcode() != ISD::XOR)
8973     return false;
8974   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8975   if (N1C && N1C->getAPIntValue() == 1) {
8976     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8977       Op.getOperand(0).hasOneUse();
8978   }
8979   return false;
8980 }
8981
8982 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8983   bool addTest = true;
8984   SDValue Chain = Op.getOperand(0);
8985   SDValue Cond  = Op.getOperand(1);
8986   SDValue Dest  = Op.getOperand(2);
8987   DebugLoc dl = Op.getDebugLoc();
8988   SDValue CC;
8989   bool Inverted = false;
8990
8991   if (Cond.getOpcode() == ISD::SETCC) {
8992     // Check for setcc([su]{add,sub,mul}o == 0).
8993     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8994         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8995         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8996         Cond.getOperand(0).getResNo() == 1 &&
8997         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8998          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8999          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9000          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9001          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9002          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9003       Inverted = true;
9004       Cond = Cond.getOperand(0);
9005     } else {
9006       SDValue NewCond = LowerSETCC(Cond, DAG);
9007       if (NewCond.getNode())
9008         Cond = NewCond;
9009     }
9010   }
9011 #if 0
9012   // FIXME: LowerXALUO doesn't handle these!!
9013   else if (Cond.getOpcode() == X86ISD::ADD  ||
9014            Cond.getOpcode() == X86ISD::SUB  ||
9015            Cond.getOpcode() == X86ISD::SMUL ||
9016            Cond.getOpcode() == X86ISD::UMUL)
9017     Cond = LowerXALUO(Cond, DAG);
9018 #endif
9019
9020   // Look pass (and (setcc_carry (cmp ...)), 1).
9021   if (Cond.getOpcode() == ISD::AND &&
9022       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9023     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9024     if (C && C->getAPIntValue() == 1)
9025       Cond = Cond.getOperand(0);
9026   }
9027
9028   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9029   // setting operand in place of the X86ISD::SETCC.
9030   unsigned CondOpcode = Cond.getOpcode();
9031   if (CondOpcode == X86ISD::SETCC ||
9032       CondOpcode == X86ISD::SETCC_CARRY) {
9033     CC = Cond.getOperand(0);
9034
9035     SDValue Cmp = Cond.getOperand(1);
9036     unsigned Opc = Cmp.getOpcode();
9037     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9038     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9039       Cond = Cmp;
9040       addTest = false;
9041     } else {
9042       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9043       default: break;
9044       case X86::COND_O:
9045       case X86::COND_B:
9046         // These can only come from an arithmetic instruction with overflow,
9047         // e.g. SADDO, UADDO.
9048         Cond = Cond.getNode()->getOperand(1);
9049         addTest = false;
9050         break;
9051       }
9052     }
9053   }
9054   CondOpcode = Cond.getOpcode();
9055   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9056       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9057       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9058        Cond.getOperand(0).getValueType() != MVT::i8)) {
9059     SDValue LHS = Cond.getOperand(0);
9060     SDValue RHS = Cond.getOperand(1);
9061     unsigned X86Opcode;
9062     unsigned X86Cond;
9063     SDVTList VTs;
9064     switch (CondOpcode) {
9065     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9066     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9067     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9068     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9069     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9070     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9071     default: llvm_unreachable("unexpected overflowing operator");
9072     }
9073     if (Inverted)
9074       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9075     if (CondOpcode == ISD::UMULO)
9076       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9077                           MVT::i32);
9078     else
9079       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9080
9081     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9082
9083     if (CondOpcode == ISD::UMULO)
9084       Cond = X86Op.getValue(2);
9085     else
9086       Cond = X86Op.getValue(1);
9087
9088     CC = DAG.getConstant(X86Cond, MVT::i8);
9089     addTest = false;
9090   } else {
9091     unsigned CondOpc;
9092     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9093       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9094       if (CondOpc == ISD::OR) {
9095         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9096         // two branches instead of an explicit OR instruction with a
9097         // separate test.
9098         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9099             isX86LogicalCmp(Cmp)) {
9100           CC = Cond.getOperand(0).getOperand(0);
9101           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9102                               Chain, Dest, CC, Cmp);
9103           CC = Cond.getOperand(1).getOperand(0);
9104           Cond = Cmp;
9105           addTest = false;
9106         }
9107       } else { // ISD::AND
9108         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9109         // two branches instead of an explicit AND instruction with a
9110         // separate test. However, we only do this if this block doesn't
9111         // have a fall-through edge, because this requires an explicit
9112         // jmp when the condition is false.
9113         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9114             isX86LogicalCmp(Cmp) &&
9115             Op.getNode()->hasOneUse()) {
9116           X86::CondCode CCode =
9117             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9118           CCode = X86::GetOppositeBranchCondition(CCode);
9119           CC = DAG.getConstant(CCode, MVT::i8);
9120           SDNode *User = *Op.getNode()->use_begin();
9121           // Look for an unconditional branch following this conditional branch.
9122           // We need this because we need to reverse the successors in order
9123           // to implement FCMP_OEQ.
9124           if (User->getOpcode() == ISD::BR) {
9125             SDValue FalseBB = User->getOperand(1);
9126             SDNode *NewBR =
9127               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9128             assert(NewBR == User);
9129             (void)NewBR;
9130             Dest = FalseBB;
9131
9132             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9133                                 Chain, Dest, CC, Cmp);
9134             X86::CondCode CCode =
9135               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9136             CCode = X86::GetOppositeBranchCondition(CCode);
9137             CC = DAG.getConstant(CCode, MVT::i8);
9138             Cond = Cmp;
9139             addTest = false;
9140           }
9141         }
9142       }
9143     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9144       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9145       // It should be transformed during dag combiner except when the condition
9146       // is set by a arithmetics with overflow node.
9147       X86::CondCode CCode =
9148         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9149       CCode = X86::GetOppositeBranchCondition(CCode);
9150       CC = DAG.getConstant(CCode, MVT::i8);
9151       Cond = Cond.getOperand(0).getOperand(1);
9152       addTest = false;
9153     } else if (Cond.getOpcode() == ISD::SETCC &&
9154                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9155       // For FCMP_OEQ, we can emit
9156       // two branches instead of an explicit AND instruction with a
9157       // separate test. However, we only do this if this block doesn't
9158       // have a fall-through edge, because this requires an explicit
9159       // jmp when the condition is false.
9160       if (Op.getNode()->hasOneUse()) {
9161         SDNode *User = *Op.getNode()->use_begin();
9162         // Look for an unconditional branch following this conditional branch.
9163         // We need this because we need to reverse the successors in order
9164         // to implement FCMP_OEQ.
9165         if (User->getOpcode() == ISD::BR) {
9166           SDValue FalseBB = User->getOperand(1);
9167           SDNode *NewBR =
9168             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9169           assert(NewBR == User);
9170           (void)NewBR;
9171           Dest = FalseBB;
9172
9173           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9174                                     Cond.getOperand(0), Cond.getOperand(1));
9175           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9176           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9177           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9178                               Chain, Dest, CC, Cmp);
9179           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9180           Cond = Cmp;
9181           addTest = false;
9182         }
9183       }
9184     } else if (Cond.getOpcode() == ISD::SETCC &&
9185                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9186       // For FCMP_UNE, we can emit
9187       // two branches instead of an explicit AND instruction with a
9188       // separate test. However, we only do this if this block doesn't
9189       // have a fall-through edge, because this requires an explicit
9190       // jmp when the condition is false.
9191       if (Op.getNode()->hasOneUse()) {
9192         SDNode *User = *Op.getNode()->use_begin();
9193         // Look for an unconditional branch following this conditional branch.
9194         // We need this because we need to reverse the successors in order
9195         // to implement FCMP_UNE.
9196         if (User->getOpcode() == ISD::BR) {
9197           SDValue FalseBB = User->getOperand(1);
9198           SDNode *NewBR =
9199             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9200           assert(NewBR == User);
9201           (void)NewBR;
9202
9203           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9204                                     Cond.getOperand(0), Cond.getOperand(1));
9205           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9206           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9207           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9208                               Chain, Dest, CC, Cmp);
9209           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9210           Cond = Cmp;
9211           addTest = false;
9212           Dest = FalseBB;
9213         }
9214       }
9215     }
9216   }
9217
9218   if (addTest) {
9219     // Look pass the truncate.
9220     if (Cond.getOpcode() == ISD::TRUNCATE)
9221       Cond = Cond.getOperand(0);
9222
9223     // We know the result of AND is compared against zero. Try to match
9224     // it to BT.
9225     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9226       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9227       if (NewSetCC.getNode()) {
9228         CC = NewSetCC.getOperand(0);
9229         Cond = NewSetCC.getOperand(1);
9230         addTest = false;
9231       }
9232     }
9233   }
9234
9235   if (addTest) {
9236     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9237     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9238   }
9239   Cond = ConvertCmpIfNecessary(Cond, DAG);
9240   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9241                      Chain, Dest, CC, Cond);
9242 }
9243
9244
9245 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9246 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9247 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9248 // that the guard pages used by the OS virtual memory manager are allocated in
9249 // correct sequence.
9250 SDValue
9251 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9252                                            SelectionDAG &DAG) const {
9253   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9254           getTargetMachine().Options.EnableSegmentedStacks) &&
9255          "This should be used only on Windows targets or when segmented stacks "
9256          "are being used");
9257   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9258   DebugLoc dl = Op.getDebugLoc();
9259
9260   // Get the inputs.
9261   SDValue Chain = Op.getOperand(0);
9262   SDValue Size  = Op.getOperand(1);
9263   // FIXME: Ensure alignment here
9264
9265   bool Is64Bit = Subtarget->is64Bit();
9266   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9267
9268   if (getTargetMachine().Options.EnableSegmentedStacks) {
9269     MachineFunction &MF = DAG.getMachineFunction();
9270     MachineRegisterInfo &MRI = MF.getRegInfo();
9271
9272     if (Is64Bit) {
9273       // The 64 bit implementation of segmented stacks needs to clobber both r10
9274       // r11. This makes it impossible to use it along with nested parameters.
9275       const Function *F = MF.getFunction();
9276
9277       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9278            I != E; ++I)
9279         if (I->hasNestAttr())
9280           report_fatal_error("Cannot use segmented stacks with functions that "
9281                              "have nested arguments.");
9282     }
9283
9284     const TargetRegisterClass *AddrRegClass =
9285       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9286     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9287     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9288     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9289                                 DAG.getRegister(Vreg, SPTy));
9290     SDValue Ops1[2] = { Value, Chain };
9291     return DAG.getMergeValues(Ops1, 2, dl);
9292   } else {
9293     SDValue Flag;
9294     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9295
9296     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9297     Flag = Chain.getValue(1);
9298     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9299
9300     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9301     Flag = Chain.getValue(1);
9302
9303     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9304
9305     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9306     return DAG.getMergeValues(Ops1, 2, dl);
9307   }
9308 }
9309
9310 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9311   MachineFunction &MF = DAG.getMachineFunction();
9312   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9313
9314   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9315   DebugLoc DL = Op.getDebugLoc();
9316
9317   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9318     // vastart just stores the address of the VarArgsFrameIndex slot into the
9319     // memory location argument.
9320     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9321                                    getPointerTy());
9322     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9323                         MachinePointerInfo(SV), false, false, 0);
9324   }
9325
9326   // __va_list_tag:
9327   //   gp_offset         (0 - 6 * 8)
9328   //   fp_offset         (48 - 48 + 8 * 16)
9329   //   overflow_arg_area (point to parameters coming in memory).
9330   //   reg_save_area
9331   SmallVector<SDValue, 8> MemOps;
9332   SDValue FIN = Op.getOperand(1);
9333   // Store gp_offset
9334   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9335                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9336                                                MVT::i32),
9337                                FIN, MachinePointerInfo(SV), false, false, 0);
9338   MemOps.push_back(Store);
9339
9340   // Store fp_offset
9341   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9342                     FIN, DAG.getIntPtrConstant(4));
9343   Store = DAG.getStore(Op.getOperand(0), DL,
9344                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9345                                        MVT::i32),
9346                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9347   MemOps.push_back(Store);
9348
9349   // Store ptr to overflow_arg_area
9350   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9351                     FIN, DAG.getIntPtrConstant(4));
9352   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9353                                     getPointerTy());
9354   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9355                        MachinePointerInfo(SV, 8),
9356                        false, false, 0);
9357   MemOps.push_back(Store);
9358
9359   // Store ptr to reg_save_area.
9360   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9361                     FIN, DAG.getIntPtrConstant(8));
9362   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9363                                     getPointerTy());
9364   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9365                        MachinePointerInfo(SV, 16), false, false, 0);
9366   MemOps.push_back(Store);
9367   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9368                      &MemOps[0], MemOps.size());
9369 }
9370
9371 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9372   assert(Subtarget->is64Bit() &&
9373          "LowerVAARG only handles 64-bit va_arg!");
9374   assert((Subtarget->isTargetLinux() ||
9375           Subtarget->isTargetDarwin()) &&
9376           "Unhandled target in LowerVAARG");
9377   assert(Op.getNode()->getNumOperands() == 4);
9378   SDValue Chain = Op.getOperand(0);
9379   SDValue SrcPtr = Op.getOperand(1);
9380   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9381   unsigned Align = Op.getConstantOperandVal(3);
9382   DebugLoc dl = Op.getDebugLoc();
9383
9384   EVT ArgVT = Op.getNode()->getValueType(0);
9385   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9386   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9387   uint8_t ArgMode;
9388
9389   // Decide which area this value should be read from.
9390   // TODO: Implement the AMD64 ABI in its entirety. This simple
9391   // selection mechanism works only for the basic types.
9392   if (ArgVT == MVT::f80) {
9393     llvm_unreachable("va_arg for f80 not yet implemented");
9394   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9395     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9396   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9397     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9398   } else {
9399     llvm_unreachable("Unhandled argument type in LowerVAARG");
9400   }
9401
9402   if (ArgMode == 2) {
9403     // Sanity Check: Make sure using fp_offset makes sense.
9404     assert(!getTargetMachine().Options.UseSoftFloat &&
9405            !(DAG.getMachineFunction()
9406                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9407            Subtarget->hasSSE1());
9408   }
9409
9410   // Insert VAARG_64 node into the DAG
9411   // VAARG_64 returns two values: Variable Argument Address, Chain
9412   SmallVector<SDValue, 11> InstOps;
9413   InstOps.push_back(Chain);
9414   InstOps.push_back(SrcPtr);
9415   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9416   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9417   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9418   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9419   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9420                                           VTs, &InstOps[0], InstOps.size(),
9421                                           MVT::i64,
9422                                           MachinePointerInfo(SV),
9423                                           /*Align=*/0,
9424                                           /*Volatile=*/false,
9425                                           /*ReadMem=*/true,
9426                                           /*WriteMem=*/true);
9427   Chain = VAARG.getValue(1);
9428
9429   // Load the next argument and return it
9430   return DAG.getLoad(ArgVT, dl,
9431                      Chain,
9432                      VAARG,
9433                      MachinePointerInfo(),
9434                      false, false, false, 0);
9435 }
9436
9437 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9438   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9439   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9440   SDValue Chain = Op.getOperand(0);
9441   SDValue DstPtr = Op.getOperand(1);
9442   SDValue SrcPtr = Op.getOperand(2);
9443   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9444   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9445   DebugLoc DL = Op.getDebugLoc();
9446
9447   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9448                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9449                        false,
9450                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9451 }
9452
9453 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9454 // may or may not be a constant. Takes immediate version of shift as input.
9455 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9456                                    SDValue SrcOp, SDValue ShAmt,
9457                                    SelectionDAG &DAG) {
9458   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9459
9460   if (isa<ConstantSDNode>(ShAmt)) {
9461     switch (Opc) {
9462       default: llvm_unreachable("Unknown target vector shift node");
9463       case X86ISD::VSHLI:
9464       case X86ISD::VSRLI:
9465       case X86ISD::VSRAI:
9466         return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9467     }
9468   }
9469
9470   // Change opcode to non-immediate version
9471   switch (Opc) {
9472     default: llvm_unreachable("Unknown target vector shift node");
9473     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9474     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9475     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9476   }
9477
9478   // Need to build a vector containing shift amount
9479   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9480   SDValue ShOps[4];
9481   ShOps[0] = ShAmt;
9482   ShOps[1] = DAG.getConstant(0, MVT::i32);
9483   ShOps[2] = DAG.getUNDEF(MVT::i32);
9484   ShOps[3] = DAG.getUNDEF(MVT::i32);
9485   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9486   ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9487   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9488 }
9489
9490 SDValue
9491 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9492   DebugLoc dl = Op.getDebugLoc();
9493   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9494   switch (IntNo) {
9495   default: return SDValue();    // Don't custom lower most intrinsics.
9496   // Comparison intrinsics.
9497   case Intrinsic::x86_sse_comieq_ss:
9498   case Intrinsic::x86_sse_comilt_ss:
9499   case Intrinsic::x86_sse_comile_ss:
9500   case Intrinsic::x86_sse_comigt_ss:
9501   case Intrinsic::x86_sse_comige_ss:
9502   case Intrinsic::x86_sse_comineq_ss:
9503   case Intrinsic::x86_sse_ucomieq_ss:
9504   case Intrinsic::x86_sse_ucomilt_ss:
9505   case Intrinsic::x86_sse_ucomile_ss:
9506   case Intrinsic::x86_sse_ucomigt_ss:
9507   case Intrinsic::x86_sse_ucomige_ss:
9508   case Intrinsic::x86_sse_ucomineq_ss:
9509   case Intrinsic::x86_sse2_comieq_sd:
9510   case Intrinsic::x86_sse2_comilt_sd:
9511   case Intrinsic::x86_sse2_comile_sd:
9512   case Intrinsic::x86_sse2_comigt_sd:
9513   case Intrinsic::x86_sse2_comige_sd:
9514   case Intrinsic::x86_sse2_comineq_sd:
9515   case Intrinsic::x86_sse2_ucomieq_sd:
9516   case Intrinsic::x86_sse2_ucomilt_sd:
9517   case Intrinsic::x86_sse2_ucomile_sd:
9518   case Intrinsic::x86_sse2_ucomigt_sd:
9519   case Intrinsic::x86_sse2_ucomige_sd:
9520   case Intrinsic::x86_sse2_ucomineq_sd: {
9521     unsigned Opc = 0;
9522     ISD::CondCode CC = ISD::SETCC_INVALID;
9523     switch (IntNo) {
9524     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9525     case Intrinsic::x86_sse_comieq_ss:
9526     case Intrinsic::x86_sse2_comieq_sd:
9527       Opc = X86ISD::COMI;
9528       CC = ISD::SETEQ;
9529       break;
9530     case Intrinsic::x86_sse_comilt_ss:
9531     case Intrinsic::x86_sse2_comilt_sd:
9532       Opc = X86ISD::COMI;
9533       CC = ISD::SETLT;
9534       break;
9535     case Intrinsic::x86_sse_comile_ss:
9536     case Intrinsic::x86_sse2_comile_sd:
9537       Opc = X86ISD::COMI;
9538       CC = ISD::SETLE;
9539       break;
9540     case Intrinsic::x86_sse_comigt_ss:
9541     case Intrinsic::x86_sse2_comigt_sd:
9542       Opc = X86ISD::COMI;
9543       CC = ISD::SETGT;
9544       break;
9545     case Intrinsic::x86_sse_comige_ss:
9546     case Intrinsic::x86_sse2_comige_sd:
9547       Opc = X86ISD::COMI;
9548       CC = ISD::SETGE;
9549       break;
9550     case Intrinsic::x86_sse_comineq_ss:
9551     case Intrinsic::x86_sse2_comineq_sd:
9552       Opc = X86ISD::COMI;
9553       CC = ISD::SETNE;
9554       break;
9555     case Intrinsic::x86_sse_ucomieq_ss:
9556     case Intrinsic::x86_sse2_ucomieq_sd:
9557       Opc = X86ISD::UCOMI;
9558       CC = ISD::SETEQ;
9559       break;
9560     case Intrinsic::x86_sse_ucomilt_ss:
9561     case Intrinsic::x86_sse2_ucomilt_sd:
9562       Opc = X86ISD::UCOMI;
9563       CC = ISD::SETLT;
9564       break;
9565     case Intrinsic::x86_sse_ucomile_ss:
9566     case Intrinsic::x86_sse2_ucomile_sd:
9567       Opc = X86ISD::UCOMI;
9568       CC = ISD::SETLE;
9569       break;
9570     case Intrinsic::x86_sse_ucomigt_ss:
9571     case Intrinsic::x86_sse2_ucomigt_sd:
9572       Opc = X86ISD::UCOMI;
9573       CC = ISD::SETGT;
9574       break;
9575     case Intrinsic::x86_sse_ucomige_ss:
9576     case Intrinsic::x86_sse2_ucomige_sd:
9577       Opc = X86ISD::UCOMI;
9578       CC = ISD::SETGE;
9579       break;
9580     case Intrinsic::x86_sse_ucomineq_ss:
9581     case Intrinsic::x86_sse2_ucomineq_sd:
9582       Opc = X86ISD::UCOMI;
9583       CC = ISD::SETNE;
9584       break;
9585     }
9586
9587     SDValue LHS = Op.getOperand(1);
9588     SDValue RHS = Op.getOperand(2);
9589     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9590     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9591     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9592     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9593                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9594     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9595   }
9596   // Arithmetic intrinsics.
9597   case Intrinsic::x86_sse2_pmulu_dq:
9598   case Intrinsic::x86_avx2_pmulu_dq:
9599     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9600                        Op.getOperand(1), Op.getOperand(2));
9601   case Intrinsic::x86_sse3_hadd_ps:
9602   case Intrinsic::x86_sse3_hadd_pd:
9603   case Intrinsic::x86_avx_hadd_ps_256:
9604   case Intrinsic::x86_avx_hadd_pd_256:
9605     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9606                        Op.getOperand(1), Op.getOperand(2));
9607   case Intrinsic::x86_sse3_hsub_ps:
9608   case Intrinsic::x86_sse3_hsub_pd:
9609   case Intrinsic::x86_avx_hsub_ps_256:
9610   case Intrinsic::x86_avx_hsub_pd_256:
9611     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9612                        Op.getOperand(1), Op.getOperand(2));
9613   case Intrinsic::x86_ssse3_phadd_w_128:
9614   case Intrinsic::x86_ssse3_phadd_d_128:
9615   case Intrinsic::x86_avx2_phadd_w:
9616   case Intrinsic::x86_avx2_phadd_d:
9617     return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9618                        Op.getOperand(1), Op.getOperand(2));
9619   case Intrinsic::x86_ssse3_phsub_w_128:
9620   case Intrinsic::x86_ssse3_phsub_d_128:
9621   case Intrinsic::x86_avx2_phsub_w:
9622   case Intrinsic::x86_avx2_phsub_d:
9623     return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9624                        Op.getOperand(1), Op.getOperand(2));
9625   case Intrinsic::x86_avx2_psllv_d:
9626   case Intrinsic::x86_avx2_psllv_q:
9627   case Intrinsic::x86_avx2_psllv_d_256:
9628   case Intrinsic::x86_avx2_psllv_q_256:
9629     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9630                       Op.getOperand(1), Op.getOperand(2));
9631   case Intrinsic::x86_avx2_psrlv_d:
9632   case Intrinsic::x86_avx2_psrlv_q:
9633   case Intrinsic::x86_avx2_psrlv_d_256:
9634   case Intrinsic::x86_avx2_psrlv_q_256:
9635     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9636                       Op.getOperand(1), Op.getOperand(2));
9637   case Intrinsic::x86_avx2_psrav_d:
9638   case Intrinsic::x86_avx2_psrav_d_256:
9639     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9640                       Op.getOperand(1), Op.getOperand(2));
9641   case Intrinsic::x86_ssse3_pshuf_b_128:
9642   case Intrinsic::x86_avx2_pshuf_b:
9643     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9644                        Op.getOperand(1), Op.getOperand(2));
9645   case Intrinsic::x86_ssse3_psign_b_128:
9646   case Intrinsic::x86_ssse3_psign_w_128:
9647   case Intrinsic::x86_ssse3_psign_d_128:
9648   case Intrinsic::x86_avx2_psign_b:
9649   case Intrinsic::x86_avx2_psign_w:
9650   case Intrinsic::x86_avx2_psign_d:
9651     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9652                        Op.getOperand(1), Op.getOperand(2));
9653   case Intrinsic::x86_sse41_insertps:
9654     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9655                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9656   case Intrinsic::x86_avx_vperm2f128_ps_256:
9657   case Intrinsic::x86_avx_vperm2f128_pd_256:
9658   case Intrinsic::x86_avx_vperm2f128_si_256:
9659   case Intrinsic::x86_avx2_vperm2i128:
9660     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9661                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9662   case Intrinsic::x86_avx2_permd:
9663   case Intrinsic::x86_avx2_permps:
9664     // Operands intentionally swapped. Mask is last operand to intrinsic,
9665     // but second operand for node/intruction.
9666     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9667                        Op.getOperand(2), Op.getOperand(1));
9668
9669   // ptest and testp intrinsics. The intrinsic these come from are designed to
9670   // return an integer value, not just an instruction so lower it to the ptest
9671   // or testp pattern and a setcc for the result.
9672   case Intrinsic::x86_sse41_ptestz:
9673   case Intrinsic::x86_sse41_ptestc:
9674   case Intrinsic::x86_sse41_ptestnzc:
9675   case Intrinsic::x86_avx_ptestz_256:
9676   case Intrinsic::x86_avx_ptestc_256:
9677   case Intrinsic::x86_avx_ptestnzc_256:
9678   case Intrinsic::x86_avx_vtestz_ps:
9679   case Intrinsic::x86_avx_vtestc_ps:
9680   case Intrinsic::x86_avx_vtestnzc_ps:
9681   case Intrinsic::x86_avx_vtestz_pd:
9682   case Intrinsic::x86_avx_vtestc_pd:
9683   case Intrinsic::x86_avx_vtestnzc_pd:
9684   case Intrinsic::x86_avx_vtestz_ps_256:
9685   case Intrinsic::x86_avx_vtestc_ps_256:
9686   case Intrinsic::x86_avx_vtestnzc_ps_256:
9687   case Intrinsic::x86_avx_vtestz_pd_256:
9688   case Intrinsic::x86_avx_vtestc_pd_256:
9689   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9690     bool IsTestPacked = false;
9691     unsigned X86CC = 0;
9692     switch (IntNo) {
9693     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9694     case Intrinsic::x86_avx_vtestz_ps:
9695     case Intrinsic::x86_avx_vtestz_pd:
9696     case Intrinsic::x86_avx_vtestz_ps_256:
9697     case Intrinsic::x86_avx_vtestz_pd_256:
9698       IsTestPacked = true; // Fallthrough
9699     case Intrinsic::x86_sse41_ptestz:
9700     case Intrinsic::x86_avx_ptestz_256:
9701       // ZF = 1
9702       X86CC = X86::COND_E;
9703       break;
9704     case Intrinsic::x86_avx_vtestc_ps:
9705     case Intrinsic::x86_avx_vtestc_pd:
9706     case Intrinsic::x86_avx_vtestc_ps_256:
9707     case Intrinsic::x86_avx_vtestc_pd_256:
9708       IsTestPacked = true; // Fallthrough
9709     case Intrinsic::x86_sse41_ptestc:
9710     case Intrinsic::x86_avx_ptestc_256:
9711       // CF = 1
9712       X86CC = X86::COND_B;
9713       break;
9714     case Intrinsic::x86_avx_vtestnzc_ps:
9715     case Intrinsic::x86_avx_vtestnzc_pd:
9716     case Intrinsic::x86_avx_vtestnzc_ps_256:
9717     case Intrinsic::x86_avx_vtestnzc_pd_256:
9718       IsTestPacked = true; // Fallthrough
9719     case Intrinsic::x86_sse41_ptestnzc:
9720     case Intrinsic::x86_avx_ptestnzc_256:
9721       // ZF and CF = 0
9722       X86CC = X86::COND_A;
9723       break;
9724     }
9725
9726     SDValue LHS = Op.getOperand(1);
9727     SDValue RHS = Op.getOperand(2);
9728     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9729     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9730     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9731     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9732     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9733   }
9734
9735   // SSE/AVX shift intrinsics
9736   case Intrinsic::x86_sse2_psll_w:
9737   case Intrinsic::x86_sse2_psll_d:
9738   case Intrinsic::x86_sse2_psll_q:
9739   case Intrinsic::x86_avx2_psll_w:
9740   case Intrinsic::x86_avx2_psll_d:
9741   case Intrinsic::x86_avx2_psll_q:
9742     return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9743                        Op.getOperand(1), Op.getOperand(2));
9744   case Intrinsic::x86_sse2_psrl_w:
9745   case Intrinsic::x86_sse2_psrl_d:
9746   case Intrinsic::x86_sse2_psrl_q:
9747   case Intrinsic::x86_avx2_psrl_w:
9748   case Intrinsic::x86_avx2_psrl_d:
9749   case Intrinsic::x86_avx2_psrl_q:
9750     return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9751                        Op.getOperand(1), Op.getOperand(2));
9752   case Intrinsic::x86_sse2_psra_w:
9753   case Intrinsic::x86_sse2_psra_d:
9754   case Intrinsic::x86_avx2_psra_w:
9755   case Intrinsic::x86_avx2_psra_d:
9756     return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9757                        Op.getOperand(1), Op.getOperand(2));
9758   case Intrinsic::x86_sse2_pslli_w:
9759   case Intrinsic::x86_sse2_pslli_d:
9760   case Intrinsic::x86_sse2_pslli_q:
9761   case Intrinsic::x86_avx2_pslli_w:
9762   case Intrinsic::x86_avx2_pslli_d:
9763   case Intrinsic::x86_avx2_pslli_q:
9764     return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9765                                Op.getOperand(1), Op.getOperand(2), DAG);
9766   case Intrinsic::x86_sse2_psrli_w:
9767   case Intrinsic::x86_sse2_psrli_d:
9768   case Intrinsic::x86_sse2_psrli_q:
9769   case Intrinsic::x86_avx2_psrli_w:
9770   case Intrinsic::x86_avx2_psrli_d:
9771   case Intrinsic::x86_avx2_psrli_q:
9772     return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9773                                Op.getOperand(1), Op.getOperand(2), DAG);
9774   case Intrinsic::x86_sse2_psrai_w:
9775   case Intrinsic::x86_sse2_psrai_d:
9776   case Intrinsic::x86_avx2_psrai_w:
9777   case Intrinsic::x86_avx2_psrai_d:
9778     return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9779                                Op.getOperand(1), Op.getOperand(2), DAG);
9780   // Fix vector shift instructions where the last operand is a non-immediate
9781   // i32 value.
9782   case Intrinsic::x86_mmx_pslli_w:
9783   case Intrinsic::x86_mmx_pslli_d:
9784   case Intrinsic::x86_mmx_pslli_q:
9785   case Intrinsic::x86_mmx_psrli_w:
9786   case Intrinsic::x86_mmx_psrli_d:
9787   case Intrinsic::x86_mmx_psrli_q:
9788   case Intrinsic::x86_mmx_psrai_w:
9789   case Intrinsic::x86_mmx_psrai_d: {
9790     SDValue ShAmt = Op.getOperand(2);
9791     if (isa<ConstantSDNode>(ShAmt))
9792       return SDValue();
9793
9794     unsigned NewIntNo = 0;
9795     switch (IntNo) {
9796     case Intrinsic::x86_mmx_pslli_w:
9797       NewIntNo = Intrinsic::x86_mmx_psll_w;
9798       break;
9799     case Intrinsic::x86_mmx_pslli_d:
9800       NewIntNo = Intrinsic::x86_mmx_psll_d;
9801       break;
9802     case Intrinsic::x86_mmx_pslli_q:
9803       NewIntNo = Intrinsic::x86_mmx_psll_q;
9804       break;
9805     case Intrinsic::x86_mmx_psrli_w:
9806       NewIntNo = Intrinsic::x86_mmx_psrl_w;
9807       break;
9808     case Intrinsic::x86_mmx_psrli_d:
9809       NewIntNo = Intrinsic::x86_mmx_psrl_d;
9810       break;
9811     case Intrinsic::x86_mmx_psrli_q:
9812       NewIntNo = Intrinsic::x86_mmx_psrl_q;
9813       break;
9814     case Intrinsic::x86_mmx_psrai_w:
9815       NewIntNo = Intrinsic::x86_mmx_psra_w;
9816       break;
9817     case Intrinsic::x86_mmx_psrai_d:
9818       NewIntNo = Intrinsic::x86_mmx_psra_d;
9819       break;
9820     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9821     }
9822
9823     // The vector shift intrinsics with scalars uses 32b shift amounts but
9824     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9825     // to be zero.
9826     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9827                          DAG.getConstant(0, MVT::i32));
9828 // FIXME this must be lowered to get rid of the invalid type.
9829
9830     EVT VT = Op.getValueType();
9831     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9832     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9833                        DAG.getConstant(NewIntNo, MVT::i32),
9834                        Op.getOperand(1), ShAmt);
9835   }
9836   }
9837 }
9838
9839 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9840                                            SelectionDAG &DAG) const {
9841   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9842   MFI->setReturnAddressIsTaken(true);
9843
9844   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9845   DebugLoc dl = Op.getDebugLoc();
9846
9847   if (Depth > 0) {
9848     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9849     SDValue Offset =
9850       DAG.getConstant(TD->getPointerSize(),
9851                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9852     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9853                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9854                                    FrameAddr, Offset),
9855                        MachinePointerInfo(), false, false, false, 0);
9856   }
9857
9858   // Just load the return address.
9859   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9860   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9861                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9862 }
9863
9864 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9865   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9866   MFI->setFrameAddressIsTaken(true);
9867
9868   EVT VT = Op.getValueType();
9869   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9870   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9871   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9872   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9873   while (Depth--)
9874     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9875                             MachinePointerInfo(),
9876                             false, false, false, 0);
9877   return FrameAddr;
9878 }
9879
9880 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9881                                                      SelectionDAG &DAG) const {
9882   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9883 }
9884
9885 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9886   SDValue Chain     = Op.getOperand(0);
9887   SDValue Offset    = Op.getOperand(1);
9888   SDValue Handler   = Op.getOperand(2);
9889   DebugLoc dl       = Op.getDebugLoc();
9890
9891   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9892                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9893                                      getPointerTy());
9894   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9895
9896   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9897                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9898   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9899   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9900                        false, false, 0);
9901   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9902
9903   return DAG.getNode(X86ISD::EH_RETURN, dl,
9904                      MVT::Other,
9905                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9906 }
9907
9908 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9909                                                   SelectionDAG &DAG) const {
9910   return Op.getOperand(0);
9911 }
9912
9913 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9914                                                 SelectionDAG &DAG) const {
9915   SDValue Root = Op.getOperand(0);
9916   SDValue Trmp = Op.getOperand(1); // trampoline
9917   SDValue FPtr = Op.getOperand(2); // nested function
9918   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9919   DebugLoc dl  = Op.getDebugLoc();
9920
9921   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9922
9923   if (Subtarget->is64Bit()) {
9924     SDValue OutChains[6];
9925
9926     // Large code-model.
9927     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9928     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9929
9930     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9931     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9932
9933     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9934
9935     // Load the pointer to the nested function into R11.
9936     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9937     SDValue Addr = Trmp;
9938     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9939                                 Addr, MachinePointerInfo(TrmpAddr),
9940                                 false, false, 0);
9941
9942     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9943                        DAG.getConstant(2, MVT::i64));
9944     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9945                                 MachinePointerInfo(TrmpAddr, 2),
9946                                 false, false, 2);
9947
9948     // Load the 'nest' parameter value into R10.
9949     // R10 is specified in X86CallingConv.td
9950     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9951     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9952                        DAG.getConstant(10, MVT::i64));
9953     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9954                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9955                                 false, false, 0);
9956
9957     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9958                        DAG.getConstant(12, MVT::i64));
9959     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9960                                 MachinePointerInfo(TrmpAddr, 12),
9961                                 false, false, 2);
9962
9963     // Jump to the nested function.
9964     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9965     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9966                        DAG.getConstant(20, MVT::i64));
9967     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9968                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9969                                 false, false, 0);
9970
9971     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9972     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9973                        DAG.getConstant(22, MVT::i64));
9974     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9975                                 MachinePointerInfo(TrmpAddr, 22),
9976                                 false, false, 0);
9977
9978     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9979   } else {
9980     const Function *Func =
9981       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9982     CallingConv::ID CC = Func->getCallingConv();
9983     unsigned NestReg;
9984
9985     switch (CC) {
9986     default:
9987       llvm_unreachable("Unsupported calling convention");
9988     case CallingConv::C:
9989     case CallingConv::X86_StdCall: {
9990       // Pass 'nest' parameter in ECX.
9991       // Must be kept in sync with X86CallingConv.td
9992       NestReg = X86::ECX;
9993
9994       // Check that ECX wasn't needed by an 'inreg' parameter.
9995       FunctionType *FTy = Func->getFunctionType();
9996       const AttrListPtr &Attrs = Func->getAttributes();
9997
9998       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9999         unsigned InRegCount = 0;
10000         unsigned Idx = 1;
10001
10002         for (FunctionType::param_iterator I = FTy->param_begin(),
10003              E = FTy->param_end(); I != E; ++I, ++Idx)
10004           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10005             // FIXME: should only count parameters that are lowered to integers.
10006             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10007
10008         if (InRegCount > 2) {
10009           report_fatal_error("Nest register in use - reduce number of inreg"
10010                              " parameters!");
10011         }
10012       }
10013       break;
10014     }
10015     case CallingConv::X86_FastCall:
10016     case CallingConv::X86_ThisCall:
10017     case CallingConv::Fast:
10018       // Pass 'nest' parameter in EAX.
10019       // Must be kept in sync with X86CallingConv.td
10020       NestReg = X86::EAX;
10021       break;
10022     }
10023
10024     SDValue OutChains[4];
10025     SDValue Addr, Disp;
10026
10027     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10028                        DAG.getConstant(10, MVT::i32));
10029     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10030
10031     // This is storing the opcode for MOV32ri.
10032     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10033     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10034     OutChains[0] = DAG.getStore(Root, dl,
10035                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10036                                 Trmp, MachinePointerInfo(TrmpAddr),
10037                                 false, false, 0);
10038
10039     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10040                        DAG.getConstant(1, MVT::i32));
10041     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10042                                 MachinePointerInfo(TrmpAddr, 1),
10043                                 false, false, 1);
10044
10045     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10046     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10047                        DAG.getConstant(5, MVT::i32));
10048     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10049                                 MachinePointerInfo(TrmpAddr, 5),
10050                                 false, false, 1);
10051
10052     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10053                        DAG.getConstant(6, MVT::i32));
10054     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10055                                 MachinePointerInfo(TrmpAddr, 6),
10056                                 false, false, 1);
10057
10058     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10059   }
10060 }
10061
10062 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10063                                             SelectionDAG &DAG) const {
10064   /*
10065    The rounding mode is in bits 11:10 of FPSR, and has the following
10066    settings:
10067      00 Round to nearest
10068      01 Round to -inf
10069      10 Round to +inf
10070      11 Round to 0
10071
10072   FLT_ROUNDS, on the other hand, expects the following:
10073     -1 Undefined
10074      0 Round to 0
10075      1 Round to nearest
10076      2 Round to +inf
10077      3 Round to -inf
10078
10079   To perform the conversion, we do:
10080     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10081   */
10082
10083   MachineFunction &MF = DAG.getMachineFunction();
10084   const TargetMachine &TM = MF.getTarget();
10085   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10086   unsigned StackAlignment = TFI.getStackAlignment();
10087   EVT VT = Op.getValueType();
10088   DebugLoc DL = Op.getDebugLoc();
10089
10090   // Save FP Control Word to stack slot
10091   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10092   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10093
10094
10095   MachineMemOperand *MMO =
10096    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10097                            MachineMemOperand::MOStore, 2, 2);
10098
10099   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10100   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10101                                           DAG.getVTList(MVT::Other),
10102                                           Ops, 2, MVT::i16, MMO);
10103
10104   // Load FP Control Word from stack slot
10105   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10106                             MachinePointerInfo(), false, false, false, 0);
10107
10108   // Transform as necessary
10109   SDValue CWD1 =
10110     DAG.getNode(ISD::SRL, DL, MVT::i16,
10111                 DAG.getNode(ISD::AND, DL, MVT::i16,
10112                             CWD, DAG.getConstant(0x800, MVT::i16)),
10113                 DAG.getConstant(11, MVT::i8));
10114   SDValue CWD2 =
10115     DAG.getNode(ISD::SRL, DL, MVT::i16,
10116                 DAG.getNode(ISD::AND, DL, MVT::i16,
10117                             CWD, DAG.getConstant(0x400, MVT::i16)),
10118                 DAG.getConstant(9, MVT::i8));
10119
10120   SDValue RetVal =
10121     DAG.getNode(ISD::AND, DL, MVT::i16,
10122                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10123                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10124                             DAG.getConstant(1, MVT::i16)),
10125                 DAG.getConstant(3, MVT::i16));
10126
10127
10128   return DAG.getNode((VT.getSizeInBits() < 16 ?
10129                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10130 }
10131
10132 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10133   EVT VT = Op.getValueType();
10134   EVT OpVT = VT;
10135   unsigned NumBits = VT.getSizeInBits();
10136   DebugLoc dl = Op.getDebugLoc();
10137
10138   Op = Op.getOperand(0);
10139   if (VT == MVT::i8) {
10140     // Zero extend to i32 since there is not an i8 bsr.
10141     OpVT = MVT::i32;
10142     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10143   }
10144
10145   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10146   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10147   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10148
10149   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10150   SDValue Ops[] = {
10151     Op,
10152     DAG.getConstant(NumBits+NumBits-1, OpVT),
10153     DAG.getConstant(X86::COND_E, MVT::i8),
10154     Op.getValue(1)
10155   };
10156   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10157
10158   // Finally xor with NumBits-1.
10159   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10160
10161   if (VT == MVT::i8)
10162     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10163   return Op;
10164 }
10165
10166 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10167                                                 SelectionDAG &DAG) const {
10168   EVT VT = Op.getValueType();
10169   EVT OpVT = VT;
10170   unsigned NumBits = VT.getSizeInBits();
10171   DebugLoc dl = Op.getDebugLoc();
10172
10173   Op = Op.getOperand(0);
10174   if (VT == MVT::i8) {
10175     // Zero extend to i32 since there is not an i8 bsr.
10176     OpVT = MVT::i32;
10177     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10178   }
10179
10180   // Issue a bsr (scan bits in reverse).
10181   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10182   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10183
10184   // And xor with NumBits-1.
10185   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10186
10187   if (VT == MVT::i8)
10188     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10189   return Op;
10190 }
10191
10192 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10193   EVT VT = Op.getValueType();
10194   unsigned NumBits = VT.getSizeInBits();
10195   DebugLoc dl = Op.getDebugLoc();
10196   Op = Op.getOperand(0);
10197
10198   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10199   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10200   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10201
10202   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10203   SDValue Ops[] = {
10204     Op,
10205     DAG.getConstant(NumBits, VT),
10206     DAG.getConstant(X86::COND_E, MVT::i8),
10207     Op.getValue(1)
10208   };
10209   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10210 }
10211
10212 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10213 // ones, and then concatenate the result back.
10214 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10215   EVT VT = Op.getValueType();
10216
10217   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10218          "Unsupported value type for operation");
10219
10220   unsigned NumElems = VT.getVectorNumElements();
10221   DebugLoc dl = Op.getDebugLoc();
10222
10223   // Extract the LHS vectors
10224   SDValue LHS = Op.getOperand(0);
10225   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10226   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10227
10228   // Extract the RHS vectors
10229   SDValue RHS = Op.getOperand(1);
10230   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10231   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10232
10233   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10234   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10235
10236   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10237                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10238                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10239 }
10240
10241 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10242   assert(Op.getValueType().getSizeInBits() == 256 &&
10243          Op.getValueType().isInteger() &&
10244          "Only handle AVX 256-bit vector integer operation");
10245   return Lower256IntArith(Op, DAG);
10246 }
10247
10248 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10249   assert(Op.getValueType().getSizeInBits() == 256 &&
10250          Op.getValueType().isInteger() &&
10251          "Only handle AVX 256-bit vector integer operation");
10252   return Lower256IntArith(Op, DAG);
10253 }
10254
10255 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10256   EVT VT = Op.getValueType();
10257
10258   // Decompose 256-bit ops into smaller 128-bit ops.
10259   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10260     return Lower256IntArith(Op, DAG);
10261
10262   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10263          "Only know how to lower V2I64/V4I64 multiply");
10264
10265   DebugLoc dl = Op.getDebugLoc();
10266
10267   //  Ahi = psrlqi(a, 32);
10268   //  Bhi = psrlqi(b, 32);
10269   //
10270   //  AloBlo = pmuludq(a, b);
10271   //  AloBhi = pmuludq(a, Bhi);
10272   //  AhiBlo = pmuludq(Ahi, b);
10273
10274   //  AloBhi = psllqi(AloBhi, 32);
10275   //  AhiBlo = psllqi(AhiBlo, 32);
10276   //  return AloBlo + AloBhi + AhiBlo;
10277
10278   SDValue A = Op.getOperand(0);
10279   SDValue B = Op.getOperand(1);
10280
10281   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10282
10283   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10284   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10285
10286   // Bit cast to 32-bit vectors for MULUDQ
10287   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10288   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10289   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10290   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10291   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10292
10293   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10294   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10295   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10296
10297   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10298   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10299
10300   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10301   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10302 }
10303
10304 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10305
10306   EVT VT = Op.getValueType();
10307   DebugLoc dl = Op.getDebugLoc();
10308   SDValue R = Op.getOperand(0);
10309   SDValue Amt = Op.getOperand(1);
10310   LLVMContext *Context = DAG.getContext();
10311
10312   if (!Subtarget->hasSSE2())
10313     return SDValue();
10314
10315   // Optimize shl/srl/sra with constant shift amount.
10316   if (isSplatVector(Amt.getNode())) {
10317     SDValue SclrAmt = Amt->getOperand(0);
10318     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10319       uint64_t ShiftAmt = C->getZExtValue();
10320
10321       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10322           (Subtarget->hasAVX2() &&
10323            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10324         if (Op.getOpcode() == ISD::SHL)
10325           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10326                              DAG.getConstant(ShiftAmt, MVT::i32));
10327         if (Op.getOpcode() == ISD::SRL)
10328           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10329                              DAG.getConstant(ShiftAmt, MVT::i32));
10330         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10331           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10332                              DAG.getConstant(ShiftAmt, MVT::i32));
10333       }
10334
10335       if (VT == MVT::v16i8) {
10336         if (Op.getOpcode() == ISD::SHL) {
10337           // Make a large shift.
10338           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10339                                     DAG.getConstant(ShiftAmt, MVT::i32));
10340           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10341           // Zero out the rightmost bits.
10342           SmallVector<SDValue, 16> V(16,
10343                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10344                                                      MVT::i8));
10345           return DAG.getNode(ISD::AND, dl, VT, SHL,
10346                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10347         }
10348         if (Op.getOpcode() == ISD::SRL) {
10349           // Make a large shift.
10350           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10351                                     DAG.getConstant(ShiftAmt, MVT::i32));
10352           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10353           // Zero out the leftmost bits.
10354           SmallVector<SDValue, 16> V(16,
10355                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10356                                                      MVT::i8));
10357           return DAG.getNode(ISD::AND, dl, VT, SRL,
10358                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10359         }
10360         if (Op.getOpcode() == ISD::SRA) {
10361           if (ShiftAmt == 7) {
10362             // R s>> 7  ===  R s< 0
10363             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10364             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10365           }
10366
10367           // R s>> a === ((R u>> a) ^ m) - m
10368           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10369           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10370                                                          MVT::i8));
10371           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10372           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10373           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10374           return Res;
10375         }
10376         llvm_unreachable("Unknown shift opcode.");
10377       }
10378
10379       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10380         if (Op.getOpcode() == ISD::SHL) {
10381           // Make a large shift.
10382           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10383                                     DAG.getConstant(ShiftAmt, MVT::i32));
10384           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10385           // Zero out the rightmost bits.
10386           SmallVector<SDValue, 32> V(32,
10387                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10388                                                      MVT::i8));
10389           return DAG.getNode(ISD::AND, dl, VT, SHL,
10390                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10391         }
10392         if (Op.getOpcode() == ISD::SRL) {
10393           // Make a large shift.
10394           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10395                                     DAG.getConstant(ShiftAmt, MVT::i32));
10396           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10397           // Zero out the leftmost bits.
10398           SmallVector<SDValue, 32> V(32,
10399                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10400                                                      MVT::i8));
10401           return DAG.getNode(ISD::AND, dl, VT, SRL,
10402                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10403         }
10404         if (Op.getOpcode() == ISD::SRA) {
10405           if (ShiftAmt == 7) {
10406             // R s>> 7  ===  R s< 0
10407             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10408             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10409           }
10410
10411           // R s>> a === ((R u>> a) ^ m) - m
10412           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10413           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10414                                                          MVT::i8));
10415           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10416           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10417           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10418           return Res;
10419         }
10420         llvm_unreachable("Unknown shift opcode.");
10421       }
10422     }
10423   }
10424
10425   // Lower SHL with variable shift amount.
10426   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10427     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10428                      DAG.getConstant(23, MVT::i32));
10429
10430     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10431     Constant *C = ConstantDataVector::get(*Context, CV);
10432     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10433     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10434                                  MachinePointerInfo::getConstantPool(),
10435                                  false, false, false, 16);
10436
10437     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10438     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10439     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10440     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10441   }
10442   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10443     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10444
10445     // a = a << 5;
10446     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10447                      DAG.getConstant(5, MVT::i32));
10448     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10449
10450     // Turn 'a' into a mask suitable for VSELECT
10451     SDValue VSelM = DAG.getConstant(0x80, VT);
10452     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10453     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10454
10455     SDValue CM1 = DAG.getConstant(0x0f, VT);
10456     SDValue CM2 = DAG.getConstant(0x3f, VT);
10457
10458     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10459     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10460     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10461                             DAG.getConstant(4, MVT::i32), DAG);
10462     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10463     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10464
10465     // a += a
10466     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10467     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10468     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10469
10470     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10471     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10472     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10473                             DAG.getConstant(2, MVT::i32), DAG);
10474     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10475     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10476
10477     // a += a
10478     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10479     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10480     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10481
10482     // return VSELECT(r, r+r, a);
10483     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10484                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10485     return R;
10486   }
10487
10488   // Decompose 256-bit shifts into smaller 128-bit shifts.
10489   if (VT.getSizeInBits() == 256) {
10490     unsigned NumElems = VT.getVectorNumElements();
10491     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10492     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10493
10494     // Extract the two vectors
10495     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10496     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10497
10498     // Recreate the shift amount vectors
10499     SDValue Amt1, Amt2;
10500     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10501       // Constant shift amount
10502       SmallVector<SDValue, 4> Amt1Csts;
10503       SmallVector<SDValue, 4> Amt2Csts;
10504       for (unsigned i = 0; i != NumElems/2; ++i)
10505         Amt1Csts.push_back(Amt->getOperand(i));
10506       for (unsigned i = NumElems/2; i != NumElems; ++i)
10507         Amt2Csts.push_back(Amt->getOperand(i));
10508
10509       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10510                                  &Amt1Csts[0], NumElems/2);
10511       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10512                                  &Amt2Csts[0], NumElems/2);
10513     } else {
10514       // Variable shift amount
10515       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10516       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10517     }
10518
10519     // Issue new vector shifts for the smaller types
10520     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10521     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10522
10523     // Concatenate the result back
10524     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10525   }
10526
10527   return SDValue();
10528 }
10529
10530 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10531   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10532   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10533   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10534   // has only one use.
10535   SDNode *N = Op.getNode();
10536   SDValue LHS = N->getOperand(0);
10537   SDValue RHS = N->getOperand(1);
10538   unsigned BaseOp = 0;
10539   unsigned Cond = 0;
10540   DebugLoc DL = Op.getDebugLoc();
10541   switch (Op.getOpcode()) {
10542   default: llvm_unreachable("Unknown ovf instruction!");
10543   case ISD::SADDO:
10544     // A subtract of one will be selected as a INC. Note that INC doesn't
10545     // set CF, so we can't do this for UADDO.
10546     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10547       if (C->isOne()) {
10548         BaseOp = X86ISD::INC;
10549         Cond = X86::COND_O;
10550         break;
10551       }
10552     BaseOp = X86ISD::ADD;
10553     Cond = X86::COND_O;
10554     break;
10555   case ISD::UADDO:
10556     BaseOp = X86ISD::ADD;
10557     Cond = X86::COND_B;
10558     break;
10559   case ISD::SSUBO:
10560     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10561     // set CF, so we can't do this for USUBO.
10562     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10563       if (C->isOne()) {
10564         BaseOp = X86ISD::DEC;
10565         Cond = X86::COND_O;
10566         break;
10567       }
10568     BaseOp = X86ISD::SUB;
10569     Cond = X86::COND_O;
10570     break;
10571   case ISD::USUBO:
10572     BaseOp = X86ISD::SUB;
10573     Cond = X86::COND_B;
10574     break;
10575   case ISD::SMULO:
10576     BaseOp = X86ISD::SMUL;
10577     Cond = X86::COND_O;
10578     break;
10579   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10580     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10581                                  MVT::i32);
10582     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10583
10584     SDValue SetCC =
10585       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10586                   DAG.getConstant(X86::COND_O, MVT::i32),
10587                   SDValue(Sum.getNode(), 2));
10588
10589     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10590   }
10591   }
10592
10593   // Also sets EFLAGS.
10594   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10595   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10596
10597   SDValue SetCC =
10598     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10599                 DAG.getConstant(Cond, MVT::i32),
10600                 SDValue(Sum.getNode(), 1));
10601
10602   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10603 }
10604
10605 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10606                                                   SelectionDAG &DAG) const {
10607   DebugLoc dl = Op.getDebugLoc();
10608   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10609   EVT VT = Op.getValueType();
10610
10611   if (!Subtarget->hasSSE2() || !VT.isVector())
10612     return SDValue();
10613
10614   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10615                       ExtraVT.getScalarType().getSizeInBits();
10616   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10617
10618   switch (VT.getSimpleVT().SimpleTy) {
10619     default: return SDValue();
10620     case MVT::v8i32:
10621     case MVT::v16i16:
10622       if (!Subtarget->hasAVX())
10623         return SDValue();
10624       if (!Subtarget->hasAVX2()) {
10625         // needs to be split
10626         unsigned NumElems = VT.getVectorNumElements();
10627
10628         // Extract the LHS vectors
10629         SDValue LHS = Op.getOperand(0);
10630         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10631         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10632
10633         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10634         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10635
10636         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10637         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10638         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10639                                    ExtraNumElems/2);
10640         SDValue Extra = DAG.getValueType(ExtraVT);
10641
10642         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10643         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10644
10645         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10646       }
10647       // fall through
10648     case MVT::v4i32:
10649     case MVT::v8i16: {
10650       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10651                                          Op.getOperand(0), ShAmt, DAG);
10652       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10653     }
10654   }
10655 }
10656
10657
10658 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10659   DebugLoc dl = Op.getDebugLoc();
10660
10661   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10662   // There isn't any reason to disable it if the target processor supports it.
10663   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10664     SDValue Chain = Op.getOperand(0);
10665     SDValue Zero = DAG.getConstant(0, MVT::i32);
10666     SDValue Ops[] = {
10667       DAG.getRegister(X86::ESP, MVT::i32), // Base
10668       DAG.getTargetConstant(1, MVT::i8),   // Scale
10669       DAG.getRegister(0, MVT::i32),        // Index
10670       DAG.getTargetConstant(0, MVT::i32),  // Disp
10671       DAG.getRegister(0, MVT::i32),        // Segment.
10672       Zero,
10673       Chain
10674     };
10675     SDNode *Res =
10676       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10677                           array_lengthof(Ops));
10678     return SDValue(Res, 0);
10679   }
10680
10681   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10682   if (!isDev)
10683     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10684
10685   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10686   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10687   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10688   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10689
10690   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10691   if (!Op1 && !Op2 && !Op3 && Op4)
10692     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10693
10694   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10695   if (Op1 && !Op2 && !Op3 && !Op4)
10696     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10697
10698   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10699   //           (MFENCE)>;
10700   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10701 }
10702
10703 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10704                                              SelectionDAG &DAG) const {
10705   DebugLoc dl = Op.getDebugLoc();
10706   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10707     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10708   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10709     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10710
10711   // The only fence that needs an instruction is a sequentially-consistent
10712   // cross-thread fence.
10713   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10714     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10715     // no-sse2). There isn't any reason to disable it if the target processor
10716     // supports it.
10717     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10718       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10719
10720     SDValue Chain = Op.getOperand(0);
10721     SDValue Zero = DAG.getConstant(0, MVT::i32);
10722     SDValue Ops[] = {
10723       DAG.getRegister(X86::ESP, MVT::i32), // Base
10724       DAG.getTargetConstant(1, MVT::i8),   // Scale
10725       DAG.getRegister(0, MVT::i32),        // Index
10726       DAG.getTargetConstant(0, MVT::i32),  // Disp
10727       DAG.getRegister(0, MVT::i32),        // Segment.
10728       Zero,
10729       Chain
10730     };
10731     SDNode *Res =
10732       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10733                          array_lengthof(Ops));
10734     return SDValue(Res, 0);
10735   }
10736
10737   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10738   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10739 }
10740
10741
10742 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10743   EVT T = Op.getValueType();
10744   DebugLoc DL = Op.getDebugLoc();
10745   unsigned Reg = 0;
10746   unsigned size = 0;
10747   switch(T.getSimpleVT().SimpleTy) {
10748   default: llvm_unreachable("Invalid value type!");
10749   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10750   case MVT::i16: Reg = X86::AX;  size = 2; break;
10751   case MVT::i32: Reg = X86::EAX; size = 4; break;
10752   case MVT::i64:
10753     assert(Subtarget->is64Bit() && "Node not type legal!");
10754     Reg = X86::RAX; size = 8;
10755     break;
10756   }
10757   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10758                                     Op.getOperand(2), SDValue());
10759   SDValue Ops[] = { cpIn.getValue(0),
10760                     Op.getOperand(1),
10761                     Op.getOperand(3),
10762                     DAG.getTargetConstant(size, MVT::i8),
10763                     cpIn.getValue(1) };
10764   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10765   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10766   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10767                                            Ops, 5, T, MMO);
10768   SDValue cpOut =
10769     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10770   return cpOut;
10771 }
10772
10773 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10774                                                  SelectionDAG &DAG) const {
10775   assert(Subtarget->is64Bit() && "Result not type legalized?");
10776   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10777   SDValue TheChain = Op.getOperand(0);
10778   DebugLoc dl = Op.getDebugLoc();
10779   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10780   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10781   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10782                                    rax.getValue(2));
10783   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10784                             DAG.getConstant(32, MVT::i8));
10785   SDValue Ops[] = {
10786     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10787     rdx.getValue(1)
10788   };
10789   return DAG.getMergeValues(Ops, 2, dl);
10790 }
10791
10792 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10793                                             SelectionDAG &DAG) const {
10794   EVT SrcVT = Op.getOperand(0).getValueType();
10795   EVT DstVT = Op.getValueType();
10796   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10797          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10798   assert((DstVT == MVT::i64 ||
10799           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10800          "Unexpected custom BITCAST");
10801   // i64 <=> MMX conversions are Legal.
10802   if (SrcVT==MVT::i64 && DstVT.isVector())
10803     return Op;
10804   if (DstVT==MVT::i64 && SrcVT.isVector())
10805     return Op;
10806   // MMX <=> MMX conversions are Legal.
10807   if (SrcVT.isVector() && DstVT.isVector())
10808     return Op;
10809   // All other conversions need to be expanded.
10810   return SDValue();
10811 }
10812
10813 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10814   SDNode *Node = Op.getNode();
10815   DebugLoc dl = Node->getDebugLoc();
10816   EVT T = Node->getValueType(0);
10817   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10818                               DAG.getConstant(0, T), Node->getOperand(2));
10819   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10820                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10821                        Node->getOperand(0),
10822                        Node->getOperand(1), negOp,
10823                        cast<AtomicSDNode>(Node)->getSrcValue(),
10824                        cast<AtomicSDNode>(Node)->getAlignment(),
10825                        cast<AtomicSDNode>(Node)->getOrdering(),
10826                        cast<AtomicSDNode>(Node)->getSynchScope());
10827 }
10828
10829 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10830   SDNode *Node = Op.getNode();
10831   DebugLoc dl = Node->getDebugLoc();
10832   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10833
10834   // Convert seq_cst store -> xchg
10835   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10836   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10837   //        (The only way to get a 16-byte store is cmpxchg16b)
10838   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10839   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10840       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10841     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10842                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10843                                  Node->getOperand(0),
10844                                  Node->getOperand(1), Node->getOperand(2),
10845                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10846                                  cast<AtomicSDNode>(Node)->getOrdering(),
10847                                  cast<AtomicSDNode>(Node)->getSynchScope());
10848     return Swap.getValue(1);
10849   }
10850   // Other atomic stores have a simple pattern.
10851   return Op;
10852 }
10853
10854 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10855   EVT VT = Op.getNode()->getValueType(0);
10856
10857   // Let legalize expand this if it isn't a legal type yet.
10858   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10859     return SDValue();
10860
10861   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10862
10863   unsigned Opc;
10864   bool ExtraOp = false;
10865   switch (Op.getOpcode()) {
10866   default: llvm_unreachable("Invalid code");
10867   case ISD::ADDC: Opc = X86ISD::ADD; break;
10868   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10869   case ISD::SUBC: Opc = X86ISD::SUB; break;
10870   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10871   }
10872
10873   if (!ExtraOp)
10874     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10875                        Op.getOperand(1));
10876   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10877                      Op.getOperand(1), Op.getOperand(2));
10878 }
10879
10880 /// LowerOperation - Provide custom lowering hooks for some operations.
10881 ///
10882 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10883   switch (Op.getOpcode()) {
10884   default: llvm_unreachable("Should not custom lower this!");
10885   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10886   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10887   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10888   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10889   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10890   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10891   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10892   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10893   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10894   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10895   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10896   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10897   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10898   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10899   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10900   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10901   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10902   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10903   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10904   case ISD::SHL_PARTS:
10905   case ISD::SRA_PARTS:
10906   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10907   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10908   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10909   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10910   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10911   case ISD::FABS:               return LowerFABS(Op, DAG);
10912   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10913   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10914   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10915   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10916   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10917   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10918   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10919   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10920   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10921   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10922   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10923   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10924   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10925   case ISD::FRAME_TO_ARGS_OFFSET:
10926                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10927   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10928   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10929   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10930   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10931   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10932   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10933   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
10934   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10935   case ISD::MUL:                return LowerMUL(Op, DAG);
10936   case ISD::SRA:
10937   case ISD::SRL:
10938   case ISD::SHL:                return LowerShift(Op, DAG);
10939   case ISD::SADDO:
10940   case ISD::UADDO:
10941   case ISD::SSUBO:
10942   case ISD::USUBO:
10943   case ISD::SMULO:
10944   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10945   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10946   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10947   case ISD::ADDC:
10948   case ISD::ADDE:
10949   case ISD::SUBC:
10950   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10951   case ISD::ADD:                return LowerADD(Op, DAG);
10952   case ISD::SUB:                return LowerSUB(Op, DAG);
10953   }
10954 }
10955
10956 static void ReplaceATOMIC_LOAD(SDNode *Node,
10957                                   SmallVectorImpl<SDValue> &Results,
10958                                   SelectionDAG &DAG) {
10959   DebugLoc dl = Node->getDebugLoc();
10960   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10961
10962   // Convert wide load -> cmpxchg8b/cmpxchg16b
10963   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10964   //        (The only way to get a 16-byte load is cmpxchg16b)
10965   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10966   SDValue Zero = DAG.getConstant(0, VT);
10967   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10968                                Node->getOperand(0),
10969                                Node->getOperand(1), Zero, Zero,
10970                                cast<AtomicSDNode>(Node)->getMemOperand(),
10971                                cast<AtomicSDNode>(Node)->getOrdering(),
10972                                cast<AtomicSDNode>(Node)->getSynchScope());
10973   Results.push_back(Swap.getValue(0));
10974   Results.push_back(Swap.getValue(1));
10975 }
10976
10977 void X86TargetLowering::
10978 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10979                         SelectionDAG &DAG, unsigned NewOp) const {
10980   DebugLoc dl = Node->getDebugLoc();
10981   assert (Node->getValueType(0) == MVT::i64 &&
10982           "Only know how to expand i64 atomics");
10983
10984   SDValue Chain = Node->getOperand(0);
10985   SDValue In1 = Node->getOperand(1);
10986   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10987                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10988   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10989                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10990   SDValue Ops[] = { Chain, In1, In2L, In2H };
10991   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10992   SDValue Result =
10993     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10994                             cast<MemSDNode>(Node)->getMemOperand());
10995   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10996   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10997   Results.push_back(Result.getValue(2));
10998 }
10999
11000 /// ReplaceNodeResults - Replace a node with an illegal result type
11001 /// with a new node built out of custom code.
11002 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11003                                            SmallVectorImpl<SDValue>&Results,
11004                                            SelectionDAG &DAG) const {
11005   DebugLoc dl = N->getDebugLoc();
11006   switch (N->getOpcode()) {
11007   default:
11008     llvm_unreachable("Do not know how to custom type legalize this operation!");
11009   case ISD::SIGN_EXTEND_INREG:
11010   case ISD::ADDC:
11011   case ISD::ADDE:
11012   case ISD::SUBC:
11013   case ISD::SUBE:
11014     // We don't want to expand or promote these.
11015     return;
11016   case ISD::FP_TO_SINT:
11017   case ISD::FP_TO_UINT: {
11018     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11019
11020     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11021       return;
11022
11023     std::pair<SDValue,SDValue> Vals =
11024         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11025     SDValue FIST = Vals.first, StackSlot = Vals.second;
11026     if (FIST.getNode() != 0) {
11027       EVT VT = N->getValueType(0);
11028       // Return a load from the stack slot.
11029       if (StackSlot.getNode() != 0)
11030         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11031                                       MachinePointerInfo(),
11032                                       false, false, false, 0));
11033       else
11034         Results.push_back(FIST);
11035     }
11036     return;
11037   }
11038   case ISD::READCYCLECOUNTER: {
11039     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11040     SDValue TheChain = N->getOperand(0);
11041     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11042     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11043                                      rd.getValue(1));
11044     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11045                                      eax.getValue(2));
11046     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11047     SDValue Ops[] = { eax, edx };
11048     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11049     Results.push_back(edx.getValue(1));
11050     return;
11051   }
11052   case ISD::ATOMIC_CMP_SWAP: {
11053     EVT T = N->getValueType(0);
11054     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11055     bool Regs64bit = T == MVT::i128;
11056     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11057     SDValue cpInL, cpInH;
11058     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11059                         DAG.getConstant(0, HalfT));
11060     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11061                         DAG.getConstant(1, HalfT));
11062     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11063                              Regs64bit ? X86::RAX : X86::EAX,
11064                              cpInL, SDValue());
11065     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11066                              Regs64bit ? X86::RDX : X86::EDX,
11067                              cpInH, cpInL.getValue(1));
11068     SDValue swapInL, swapInH;
11069     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11070                           DAG.getConstant(0, HalfT));
11071     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11072                           DAG.getConstant(1, HalfT));
11073     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11074                                Regs64bit ? X86::RBX : X86::EBX,
11075                                swapInL, cpInH.getValue(1));
11076     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11077                                Regs64bit ? X86::RCX : X86::ECX, 
11078                                swapInH, swapInL.getValue(1));
11079     SDValue Ops[] = { swapInH.getValue(0),
11080                       N->getOperand(1),
11081                       swapInH.getValue(1) };
11082     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11083     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11084     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11085                                   X86ISD::LCMPXCHG8_DAG;
11086     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11087                                              Ops, 3, T, MMO);
11088     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11089                                         Regs64bit ? X86::RAX : X86::EAX,
11090                                         HalfT, Result.getValue(1));
11091     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11092                                         Regs64bit ? X86::RDX : X86::EDX,
11093                                         HalfT, cpOutL.getValue(2));
11094     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11095     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11096     Results.push_back(cpOutH.getValue(1));
11097     return;
11098   }
11099   case ISD::ATOMIC_LOAD_ADD:
11100     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11101     return;
11102   case ISD::ATOMIC_LOAD_AND:
11103     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11104     return;
11105   case ISD::ATOMIC_LOAD_NAND:
11106     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11107     return;
11108   case ISD::ATOMIC_LOAD_OR:
11109     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11110     return;
11111   case ISD::ATOMIC_LOAD_SUB:
11112     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11113     return;
11114   case ISD::ATOMIC_LOAD_XOR:
11115     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11116     return;
11117   case ISD::ATOMIC_SWAP:
11118     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11119     return;
11120   case ISD::ATOMIC_LOAD:
11121     ReplaceATOMIC_LOAD(N, Results, DAG);
11122   }
11123 }
11124
11125 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11126   switch (Opcode) {
11127   default: return NULL;
11128   case X86ISD::BSF:                return "X86ISD::BSF";
11129   case X86ISD::BSR:                return "X86ISD::BSR";
11130   case X86ISD::SHLD:               return "X86ISD::SHLD";
11131   case X86ISD::SHRD:               return "X86ISD::SHRD";
11132   case X86ISD::FAND:               return "X86ISD::FAND";
11133   case X86ISD::FOR:                return "X86ISD::FOR";
11134   case X86ISD::FXOR:               return "X86ISD::FXOR";
11135   case X86ISD::FSRL:               return "X86ISD::FSRL";
11136   case X86ISD::FILD:               return "X86ISD::FILD";
11137   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11138   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11139   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11140   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11141   case X86ISD::FLD:                return "X86ISD::FLD";
11142   case X86ISD::FST:                return "X86ISD::FST";
11143   case X86ISD::CALL:               return "X86ISD::CALL";
11144   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11145   case X86ISD::BT:                 return "X86ISD::BT";
11146   case X86ISD::CMP:                return "X86ISD::CMP";
11147   case X86ISD::COMI:               return "X86ISD::COMI";
11148   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11149   case X86ISD::SETCC:              return "X86ISD::SETCC";
11150   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11151   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11152   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11153   case X86ISD::CMOV:               return "X86ISD::CMOV";
11154   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11155   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11156   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11157   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11158   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11159   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11160   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11161   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11162   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11163   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11164   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11165   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11166   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11167   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11168   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11169   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11170   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11171   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11172   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11173   case X86ISD::HADD:               return "X86ISD::HADD";
11174   case X86ISD::HSUB:               return "X86ISD::HSUB";
11175   case X86ISD::FHADD:              return "X86ISD::FHADD";
11176   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11177   case X86ISD::FMAX:               return "X86ISD::FMAX";
11178   case X86ISD::FMIN:               return "X86ISD::FMIN";
11179   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11180   case X86ISD::FRCP:               return "X86ISD::FRCP";
11181   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11182   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11183   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11184   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11185   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11186   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11187   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11188   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11189   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11190   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11191   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11192   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11193   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11194   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11195   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11196   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11197   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11198   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11199   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11200   case X86ISD::VSHL:               return "X86ISD::VSHL";
11201   case X86ISD::VSRL:               return "X86ISD::VSRL";
11202   case X86ISD::VSRA:               return "X86ISD::VSRA";
11203   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11204   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11205   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11206   case X86ISD::CMPP:               return "X86ISD::CMPP";
11207   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11208   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11209   case X86ISD::ADD:                return "X86ISD::ADD";
11210   case X86ISD::SUB:                return "X86ISD::SUB";
11211   case X86ISD::ADC:                return "X86ISD::ADC";
11212   case X86ISD::SBB:                return "X86ISD::SBB";
11213   case X86ISD::SMUL:               return "X86ISD::SMUL";
11214   case X86ISD::UMUL:               return "X86ISD::UMUL";
11215   case X86ISD::INC:                return "X86ISD::INC";
11216   case X86ISD::DEC:                return "X86ISD::DEC";
11217   case X86ISD::OR:                 return "X86ISD::OR";
11218   case X86ISD::XOR:                return "X86ISD::XOR";
11219   case X86ISD::AND:                return "X86ISD::AND";
11220   case X86ISD::ANDN:               return "X86ISD::ANDN";
11221   case X86ISD::BLSI:               return "X86ISD::BLSI";
11222   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11223   case X86ISD::BLSR:               return "X86ISD::BLSR";
11224   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11225   case X86ISD::PTEST:              return "X86ISD::PTEST";
11226   case X86ISD::TESTP:              return "X86ISD::TESTP";
11227   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11228   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11229   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11230   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11231   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11232   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11233   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11234   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11235   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11236   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11237   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11238   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11239   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11240   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11241   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11242   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11243   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11244   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11245   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11246   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11247   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11248   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11249   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11250   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11251   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11252   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11253   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11254   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11255   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11256   case X86ISD::SAHF:               return "X86ISD::SAHF";
11257   }
11258 }
11259
11260 // isLegalAddressingMode - Return true if the addressing mode represented
11261 // by AM is legal for this target, for a load/store of the specified type.
11262 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11263                                               Type *Ty) const {
11264   // X86 supports extremely general addressing modes.
11265   CodeModel::Model M = getTargetMachine().getCodeModel();
11266   Reloc::Model R = getTargetMachine().getRelocationModel();
11267
11268   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11269   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11270     return false;
11271
11272   if (AM.BaseGV) {
11273     unsigned GVFlags =
11274       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11275
11276     // If a reference to this global requires an extra load, we can't fold it.
11277     if (isGlobalStubReference(GVFlags))
11278       return false;
11279
11280     // If BaseGV requires a register for the PIC base, we cannot also have a
11281     // BaseReg specified.
11282     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11283       return false;
11284
11285     // If lower 4G is not available, then we must use rip-relative addressing.
11286     if ((M != CodeModel::Small || R != Reloc::Static) &&
11287         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11288       return false;
11289   }
11290
11291   switch (AM.Scale) {
11292   case 0:
11293   case 1:
11294   case 2:
11295   case 4:
11296   case 8:
11297     // These scales always work.
11298     break;
11299   case 3:
11300   case 5:
11301   case 9:
11302     // These scales are formed with basereg+scalereg.  Only accept if there is
11303     // no basereg yet.
11304     if (AM.HasBaseReg)
11305       return false;
11306     break;
11307   default:  // Other stuff never works.
11308     return false;
11309   }
11310
11311   return true;
11312 }
11313
11314
11315 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11316   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11317     return false;
11318   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11319   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11320   if (NumBits1 <= NumBits2)
11321     return false;
11322   return true;
11323 }
11324
11325 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11326   if (!VT1.isInteger() || !VT2.isInteger())
11327     return false;
11328   unsigned NumBits1 = VT1.getSizeInBits();
11329   unsigned NumBits2 = VT2.getSizeInBits();
11330   if (NumBits1 <= NumBits2)
11331     return false;
11332   return true;
11333 }
11334
11335 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11336   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11337   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11338 }
11339
11340 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11341   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11342   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11343 }
11344
11345 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11346   // i16 instructions are longer (0x66 prefix) and potentially slower.
11347   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11348 }
11349
11350 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11351 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11352 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11353 /// are assumed to be legal.
11354 bool
11355 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11356                                       EVT VT) const {
11357   // Very little shuffling can be done for 64-bit vectors right now.
11358   if (VT.getSizeInBits() == 64)
11359     return false;
11360
11361   // FIXME: pshufb, blends, shifts.
11362   return (VT.getVectorNumElements() == 2 ||
11363           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11364           isMOVLMask(M, VT) ||
11365           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11366           isPSHUFDMask(M, VT) ||
11367           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11368           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11369           isPALIGNRMask(M, VT, Subtarget) ||
11370           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11371           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11372           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11373           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11374 }
11375
11376 bool
11377 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11378                                           EVT VT) const {
11379   unsigned NumElts = VT.getVectorNumElements();
11380   // FIXME: This collection of masks seems suspect.
11381   if (NumElts == 2)
11382     return true;
11383   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11384     return (isMOVLMask(Mask, VT)  ||
11385             isCommutedMOVLMask(Mask, VT, true) ||
11386             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11387             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11388   }
11389   return false;
11390 }
11391
11392 //===----------------------------------------------------------------------===//
11393 //                           X86 Scheduler Hooks
11394 //===----------------------------------------------------------------------===//
11395
11396 // private utility function
11397 MachineBasicBlock *
11398 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11399                                                        MachineBasicBlock *MBB,
11400                                                        unsigned regOpc,
11401                                                        unsigned immOpc,
11402                                                        unsigned LoadOpc,
11403                                                        unsigned CXchgOpc,
11404                                                        unsigned notOpc,
11405                                                        unsigned EAXreg,
11406                                                  const TargetRegisterClass *RC,
11407                                                        bool Invert) const {
11408   // For the atomic bitwise operator, we generate
11409   //   thisMBB:
11410   //   newMBB:
11411   //     ld  t1 = [bitinstr.addr]
11412   //     op  t2 = t1, [bitinstr.val]
11413   //     not t3 = t2  (if Invert)
11414   //     mov EAX = t1
11415   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11416   //     bz  newMBB
11417   //     fallthrough -->nextMBB
11418   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11419   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11420   MachineFunction::iterator MBBIter = MBB;
11421   ++MBBIter;
11422
11423   /// First build the CFG
11424   MachineFunction *F = MBB->getParent();
11425   MachineBasicBlock *thisMBB = MBB;
11426   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11427   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11428   F->insert(MBBIter, newMBB);
11429   F->insert(MBBIter, nextMBB);
11430
11431   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11432   nextMBB->splice(nextMBB->begin(), thisMBB,
11433                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11434                   thisMBB->end());
11435   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11436
11437   // Update thisMBB to fall through to newMBB
11438   thisMBB->addSuccessor(newMBB);
11439
11440   // newMBB jumps to itself and fall through to nextMBB
11441   newMBB->addSuccessor(nextMBB);
11442   newMBB->addSuccessor(newMBB);
11443
11444   // Insert instructions into newMBB based on incoming instruction
11445   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11446          "unexpected number of operands");
11447   DebugLoc dl = bInstr->getDebugLoc();
11448   MachineOperand& destOper = bInstr->getOperand(0);
11449   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11450   int numArgs = bInstr->getNumOperands() - 1;
11451   for (int i=0; i < numArgs; ++i)
11452     argOpers[i] = &bInstr->getOperand(i+1);
11453
11454   // x86 address has 4 operands: base, index, scale, and displacement
11455   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11456   int valArgIndx = lastAddrIndx + 1;
11457
11458   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11459   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11460   for (int i=0; i <= lastAddrIndx; ++i)
11461     (*MIB).addOperand(*argOpers[i]);
11462
11463   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11464   assert((argOpers[valArgIndx]->isReg() ||
11465           argOpers[valArgIndx]->isImm()) &&
11466          "invalid operand");
11467   if (argOpers[valArgIndx]->isReg())
11468     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11469   else
11470     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11471   MIB.addReg(t1);
11472   (*MIB).addOperand(*argOpers[valArgIndx]);
11473
11474   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11475   if (Invert) {
11476     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11477   }
11478   else
11479     t3 = t2;
11480
11481   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11482   MIB.addReg(t1);
11483
11484   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11485   for (int i=0; i <= lastAddrIndx; ++i)
11486     (*MIB).addOperand(*argOpers[i]);
11487   MIB.addReg(t3);
11488   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11489   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11490                     bInstr->memoperands_end());
11491
11492   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11493   MIB.addReg(EAXreg);
11494
11495   // insert branch
11496   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11497
11498   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11499   return nextMBB;
11500 }
11501
11502 // private utility function:  64 bit atomics on 32 bit host.
11503 MachineBasicBlock *
11504 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11505                                                        MachineBasicBlock *MBB,
11506                                                        unsigned regOpcL,
11507                                                        unsigned regOpcH,
11508                                                        unsigned immOpcL,
11509                                                        unsigned immOpcH,
11510                                                        bool Invert) const {
11511   // For the atomic bitwise operator, we generate
11512   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11513   //     ld t1,t2 = [bitinstr.addr]
11514   //   newMBB:
11515   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11516   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11517   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11518   //     neg t7, t8 < t5, t6  (if Invert)
11519   //     mov ECX, EBX <- t5, t6
11520   //     mov EAX, EDX <- t1, t2
11521   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11522   //     mov t3, t4 <- EAX, EDX
11523   //     bz  newMBB
11524   //     result in out1, out2
11525   //     fallthrough -->nextMBB
11526
11527   const TargetRegisterClass *RC = &X86::GR32RegClass;
11528   const unsigned LoadOpc = X86::MOV32rm;
11529   const unsigned NotOpc = X86::NOT32r;
11530   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11531   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11532   MachineFunction::iterator MBBIter = MBB;
11533   ++MBBIter;
11534
11535   /// First build the CFG
11536   MachineFunction *F = MBB->getParent();
11537   MachineBasicBlock *thisMBB = MBB;
11538   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11539   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11540   F->insert(MBBIter, newMBB);
11541   F->insert(MBBIter, nextMBB);
11542
11543   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11544   nextMBB->splice(nextMBB->begin(), thisMBB,
11545                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11546                   thisMBB->end());
11547   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11548
11549   // Update thisMBB to fall through to newMBB
11550   thisMBB->addSuccessor(newMBB);
11551
11552   // newMBB jumps to itself and fall through to nextMBB
11553   newMBB->addSuccessor(nextMBB);
11554   newMBB->addSuccessor(newMBB);
11555
11556   DebugLoc dl = bInstr->getDebugLoc();
11557   // Insert instructions into newMBB based on incoming instruction
11558   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11559   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11560          "unexpected number of operands");
11561   MachineOperand& dest1Oper = bInstr->getOperand(0);
11562   MachineOperand& dest2Oper = bInstr->getOperand(1);
11563   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11564   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11565     argOpers[i] = &bInstr->getOperand(i+2);
11566
11567     // We use some of the operands multiple times, so conservatively just
11568     // clear any kill flags that might be present.
11569     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11570       argOpers[i]->setIsKill(false);
11571   }
11572
11573   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11574   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11575
11576   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11577   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11578   for (int i=0; i <= lastAddrIndx; ++i)
11579     (*MIB).addOperand(*argOpers[i]);
11580   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11581   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11582   // add 4 to displacement.
11583   for (int i=0; i <= lastAddrIndx-2; ++i)
11584     (*MIB).addOperand(*argOpers[i]);
11585   MachineOperand newOp3 = *(argOpers[3]);
11586   if (newOp3.isImm())
11587     newOp3.setImm(newOp3.getImm()+4);
11588   else
11589     newOp3.setOffset(newOp3.getOffset()+4);
11590   (*MIB).addOperand(newOp3);
11591   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11592
11593   // t3/4 are defined later, at the bottom of the loop
11594   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11595   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11596   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11597     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11598   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11599     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11600
11601   // The subsequent operations should be using the destination registers of
11602   // the PHI instructions.
11603   t1 = dest1Oper.getReg();
11604   t2 = dest2Oper.getReg();
11605
11606   int valArgIndx = lastAddrIndx + 1;
11607   assert((argOpers[valArgIndx]->isReg() ||
11608           argOpers[valArgIndx]->isImm()) &&
11609          "invalid operand");
11610   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11611   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11612   if (argOpers[valArgIndx]->isReg())
11613     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11614   else
11615     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11616   if (regOpcL != X86::MOV32rr)
11617     MIB.addReg(t1);
11618   (*MIB).addOperand(*argOpers[valArgIndx]);
11619   assert(argOpers[valArgIndx + 1]->isReg() ==
11620          argOpers[valArgIndx]->isReg());
11621   assert(argOpers[valArgIndx + 1]->isImm() ==
11622          argOpers[valArgIndx]->isImm());
11623   if (argOpers[valArgIndx + 1]->isReg())
11624     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11625   else
11626     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11627   if (regOpcH != X86::MOV32rr)
11628     MIB.addReg(t2);
11629   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11630
11631   unsigned t7, t8;
11632   if (Invert) {
11633     t7 = F->getRegInfo().createVirtualRegister(RC);
11634     t8 = F->getRegInfo().createVirtualRegister(RC);
11635     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11636     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11637   } else {
11638     t7 = t5;
11639     t8 = t6;
11640   }
11641
11642   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11643   MIB.addReg(t1);
11644   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11645   MIB.addReg(t2);
11646
11647   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11648   MIB.addReg(t7);
11649   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11650   MIB.addReg(t8);
11651
11652   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11653   for (int i=0; i <= lastAddrIndx; ++i)
11654     (*MIB).addOperand(*argOpers[i]);
11655
11656   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11657   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11658                     bInstr->memoperands_end());
11659
11660   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11661   MIB.addReg(X86::EAX);
11662   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11663   MIB.addReg(X86::EDX);
11664
11665   // insert branch
11666   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11667
11668   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11669   return nextMBB;
11670 }
11671
11672 // private utility function
11673 MachineBasicBlock *
11674 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11675                                                       MachineBasicBlock *MBB,
11676                                                       unsigned cmovOpc) const {
11677   // For the atomic min/max operator, we generate
11678   //   thisMBB:
11679   //   newMBB:
11680   //     ld t1 = [min/max.addr]
11681   //     mov t2 = [min/max.val]
11682   //     cmp  t1, t2
11683   //     cmov[cond] t2 = t1
11684   //     mov EAX = t1
11685   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11686   //     bz   newMBB
11687   //     fallthrough -->nextMBB
11688   //
11689   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11690   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11691   MachineFunction::iterator MBBIter = MBB;
11692   ++MBBIter;
11693
11694   /// First build the CFG
11695   MachineFunction *F = MBB->getParent();
11696   MachineBasicBlock *thisMBB = MBB;
11697   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11698   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11699   F->insert(MBBIter, newMBB);
11700   F->insert(MBBIter, nextMBB);
11701
11702   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11703   nextMBB->splice(nextMBB->begin(), thisMBB,
11704                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11705                   thisMBB->end());
11706   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11707
11708   // Update thisMBB to fall through to newMBB
11709   thisMBB->addSuccessor(newMBB);
11710
11711   // newMBB jumps to newMBB and fall through to nextMBB
11712   newMBB->addSuccessor(nextMBB);
11713   newMBB->addSuccessor(newMBB);
11714
11715   DebugLoc dl = mInstr->getDebugLoc();
11716   // Insert instructions into newMBB based on incoming instruction
11717   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11718          "unexpected number of operands");
11719   MachineOperand& destOper = mInstr->getOperand(0);
11720   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11721   int numArgs = mInstr->getNumOperands() - 1;
11722   for (int i=0; i < numArgs; ++i)
11723     argOpers[i] = &mInstr->getOperand(i+1);
11724
11725   // x86 address has 4 operands: base, index, scale, and displacement
11726   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11727   int valArgIndx = lastAddrIndx + 1;
11728
11729   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11730   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11731   for (int i=0; i <= lastAddrIndx; ++i)
11732     (*MIB).addOperand(*argOpers[i]);
11733
11734   // We only support register and immediate values
11735   assert((argOpers[valArgIndx]->isReg() ||
11736           argOpers[valArgIndx]->isImm()) &&
11737          "invalid operand");
11738
11739   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11740   if (argOpers[valArgIndx]->isReg())
11741     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11742   else
11743     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11744   (*MIB).addOperand(*argOpers[valArgIndx]);
11745
11746   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11747   MIB.addReg(t1);
11748
11749   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11750   MIB.addReg(t1);
11751   MIB.addReg(t2);
11752
11753   // Generate movc
11754   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11755   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11756   MIB.addReg(t2);
11757   MIB.addReg(t1);
11758
11759   // Cmp and exchange if none has modified the memory location
11760   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11761   for (int i=0; i <= lastAddrIndx; ++i)
11762     (*MIB).addOperand(*argOpers[i]);
11763   MIB.addReg(t3);
11764   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11765   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11766                     mInstr->memoperands_end());
11767
11768   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11769   MIB.addReg(X86::EAX);
11770
11771   // insert branch
11772   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11773
11774   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11775   return nextMBB;
11776 }
11777
11778 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11779 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11780 // in the .td file.
11781 MachineBasicBlock *
11782 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11783                             unsigned numArgs, bool memArg) const {
11784   assert(Subtarget->hasSSE42() &&
11785          "Target must have SSE4.2 or AVX features enabled");
11786
11787   DebugLoc dl = MI->getDebugLoc();
11788   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11789   unsigned Opc;
11790   if (!Subtarget->hasAVX()) {
11791     if (memArg)
11792       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11793     else
11794       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11795   } else {
11796     if (memArg)
11797       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11798     else
11799       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11800   }
11801
11802   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11803   for (unsigned i = 0; i < numArgs; ++i) {
11804     MachineOperand &Op = MI->getOperand(i+1);
11805     if (!(Op.isReg() && Op.isImplicit()))
11806       MIB.addOperand(Op);
11807   }
11808   BuildMI(*BB, MI, dl,
11809     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11810              MI->getOperand(0).getReg())
11811     .addReg(X86::XMM0);
11812
11813   MI->eraseFromParent();
11814   return BB;
11815 }
11816
11817 MachineBasicBlock *
11818 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11819   DebugLoc dl = MI->getDebugLoc();
11820   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11821
11822   // Address into RAX/EAX, other two args into ECX, EDX.
11823   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11824   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11825   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11826   for (int i = 0; i < X86::AddrNumOperands; ++i)
11827     MIB.addOperand(MI->getOperand(i));
11828
11829   unsigned ValOps = X86::AddrNumOperands;
11830   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11831     .addReg(MI->getOperand(ValOps).getReg());
11832   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11833     .addReg(MI->getOperand(ValOps+1).getReg());
11834
11835   // The instruction doesn't actually take any operands though.
11836   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11837
11838   MI->eraseFromParent(); // The pseudo is gone now.
11839   return BB;
11840 }
11841
11842 MachineBasicBlock *
11843 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11844   DebugLoc dl = MI->getDebugLoc();
11845   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11846
11847   // First arg in ECX, the second in EAX.
11848   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11849     .addReg(MI->getOperand(0).getReg());
11850   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11851     .addReg(MI->getOperand(1).getReg());
11852
11853   // The instruction doesn't actually take any operands though.
11854   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11855
11856   MI->eraseFromParent(); // The pseudo is gone now.
11857   return BB;
11858 }
11859
11860 MachineBasicBlock *
11861 X86TargetLowering::EmitVAARG64WithCustomInserter(
11862                    MachineInstr *MI,
11863                    MachineBasicBlock *MBB) const {
11864   // Emit va_arg instruction on X86-64.
11865
11866   // Operands to this pseudo-instruction:
11867   // 0  ) Output        : destination address (reg)
11868   // 1-5) Input         : va_list address (addr, i64mem)
11869   // 6  ) ArgSize       : Size (in bytes) of vararg type
11870   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11871   // 8  ) Align         : Alignment of type
11872   // 9  ) EFLAGS (implicit-def)
11873
11874   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11875   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11876
11877   unsigned DestReg = MI->getOperand(0).getReg();
11878   MachineOperand &Base = MI->getOperand(1);
11879   MachineOperand &Scale = MI->getOperand(2);
11880   MachineOperand &Index = MI->getOperand(3);
11881   MachineOperand &Disp = MI->getOperand(4);
11882   MachineOperand &Segment = MI->getOperand(5);
11883   unsigned ArgSize = MI->getOperand(6).getImm();
11884   unsigned ArgMode = MI->getOperand(7).getImm();
11885   unsigned Align = MI->getOperand(8).getImm();
11886
11887   // Memory Reference
11888   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11889   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11890   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11891
11892   // Machine Information
11893   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11894   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11895   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11896   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11897   DebugLoc DL = MI->getDebugLoc();
11898
11899   // struct va_list {
11900   //   i32   gp_offset
11901   //   i32   fp_offset
11902   //   i64   overflow_area (address)
11903   //   i64   reg_save_area (address)
11904   // }
11905   // sizeof(va_list) = 24
11906   // alignment(va_list) = 8
11907
11908   unsigned TotalNumIntRegs = 6;
11909   unsigned TotalNumXMMRegs = 8;
11910   bool UseGPOffset = (ArgMode == 1);
11911   bool UseFPOffset = (ArgMode == 2);
11912   unsigned MaxOffset = TotalNumIntRegs * 8 +
11913                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11914
11915   /* Align ArgSize to a multiple of 8 */
11916   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11917   bool NeedsAlign = (Align > 8);
11918
11919   MachineBasicBlock *thisMBB = MBB;
11920   MachineBasicBlock *overflowMBB;
11921   MachineBasicBlock *offsetMBB;
11922   MachineBasicBlock *endMBB;
11923
11924   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11925   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11926   unsigned OffsetReg = 0;
11927
11928   if (!UseGPOffset && !UseFPOffset) {
11929     // If we only pull from the overflow region, we don't create a branch.
11930     // We don't need to alter control flow.
11931     OffsetDestReg = 0; // unused
11932     OverflowDestReg = DestReg;
11933
11934     offsetMBB = NULL;
11935     overflowMBB = thisMBB;
11936     endMBB = thisMBB;
11937   } else {
11938     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11939     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11940     // If not, pull from overflow_area. (branch to overflowMBB)
11941     //
11942     //       thisMBB
11943     //         |     .
11944     //         |        .
11945     //     offsetMBB   overflowMBB
11946     //         |        .
11947     //         |     .
11948     //        endMBB
11949
11950     // Registers for the PHI in endMBB
11951     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11952     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11953
11954     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11955     MachineFunction *MF = MBB->getParent();
11956     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11957     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11958     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11959
11960     MachineFunction::iterator MBBIter = MBB;
11961     ++MBBIter;
11962
11963     // Insert the new basic blocks
11964     MF->insert(MBBIter, offsetMBB);
11965     MF->insert(MBBIter, overflowMBB);
11966     MF->insert(MBBIter, endMBB);
11967
11968     // Transfer the remainder of MBB and its successor edges to endMBB.
11969     endMBB->splice(endMBB->begin(), thisMBB,
11970                     llvm::next(MachineBasicBlock::iterator(MI)),
11971                     thisMBB->end());
11972     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11973
11974     // Make offsetMBB and overflowMBB successors of thisMBB
11975     thisMBB->addSuccessor(offsetMBB);
11976     thisMBB->addSuccessor(overflowMBB);
11977
11978     // endMBB is a successor of both offsetMBB and overflowMBB
11979     offsetMBB->addSuccessor(endMBB);
11980     overflowMBB->addSuccessor(endMBB);
11981
11982     // Load the offset value into a register
11983     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11984     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11985       .addOperand(Base)
11986       .addOperand(Scale)
11987       .addOperand(Index)
11988       .addDisp(Disp, UseFPOffset ? 4 : 0)
11989       .addOperand(Segment)
11990       .setMemRefs(MMOBegin, MMOEnd);
11991
11992     // Check if there is enough room left to pull this argument.
11993     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11994       .addReg(OffsetReg)
11995       .addImm(MaxOffset + 8 - ArgSizeA8);
11996
11997     // Branch to "overflowMBB" if offset >= max
11998     // Fall through to "offsetMBB" otherwise
11999     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12000       .addMBB(overflowMBB);
12001   }
12002
12003   // In offsetMBB, emit code to use the reg_save_area.
12004   if (offsetMBB) {
12005     assert(OffsetReg != 0);
12006
12007     // Read the reg_save_area address.
12008     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12009     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12010       .addOperand(Base)
12011       .addOperand(Scale)
12012       .addOperand(Index)
12013       .addDisp(Disp, 16)
12014       .addOperand(Segment)
12015       .setMemRefs(MMOBegin, MMOEnd);
12016
12017     // Zero-extend the offset
12018     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12019       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12020         .addImm(0)
12021         .addReg(OffsetReg)
12022         .addImm(X86::sub_32bit);
12023
12024     // Add the offset to the reg_save_area to get the final address.
12025     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12026       .addReg(OffsetReg64)
12027       .addReg(RegSaveReg);
12028
12029     // Compute the offset for the next argument
12030     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12031     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12032       .addReg(OffsetReg)
12033       .addImm(UseFPOffset ? 16 : 8);
12034
12035     // Store it back into the va_list.
12036     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12037       .addOperand(Base)
12038       .addOperand(Scale)
12039       .addOperand(Index)
12040       .addDisp(Disp, UseFPOffset ? 4 : 0)
12041       .addOperand(Segment)
12042       .addReg(NextOffsetReg)
12043       .setMemRefs(MMOBegin, MMOEnd);
12044
12045     // Jump to endMBB
12046     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12047       .addMBB(endMBB);
12048   }
12049
12050   //
12051   // Emit code to use overflow area
12052   //
12053
12054   // Load the overflow_area address into a register.
12055   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12056   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12057     .addOperand(Base)
12058     .addOperand(Scale)
12059     .addOperand(Index)
12060     .addDisp(Disp, 8)
12061     .addOperand(Segment)
12062     .setMemRefs(MMOBegin, MMOEnd);
12063
12064   // If we need to align it, do so. Otherwise, just copy the address
12065   // to OverflowDestReg.
12066   if (NeedsAlign) {
12067     // Align the overflow address
12068     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12069     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12070
12071     // aligned_addr = (addr + (align-1)) & ~(align-1)
12072     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12073       .addReg(OverflowAddrReg)
12074       .addImm(Align-1);
12075
12076     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12077       .addReg(TmpReg)
12078       .addImm(~(uint64_t)(Align-1));
12079   } else {
12080     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12081       .addReg(OverflowAddrReg);
12082   }
12083
12084   // Compute the next overflow address after this argument.
12085   // (the overflow address should be kept 8-byte aligned)
12086   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12087   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12088     .addReg(OverflowDestReg)
12089     .addImm(ArgSizeA8);
12090
12091   // Store the new overflow address.
12092   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12093     .addOperand(Base)
12094     .addOperand(Scale)
12095     .addOperand(Index)
12096     .addDisp(Disp, 8)
12097     .addOperand(Segment)
12098     .addReg(NextAddrReg)
12099     .setMemRefs(MMOBegin, MMOEnd);
12100
12101   // If we branched, emit the PHI to the front of endMBB.
12102   if (offsetMBB) {
12103     BuildMI(*endMBB, endMBB->begin(), DL,
12104             TII->get(X86::PHI), DestReg)
12105       .addReg(OffsetDestReg).addMBB(offsetMBB)
12106       .addReg(OverflowDestReg).addMBB(overflowMBB);
12107   }
12108
12109   // Erase the pseudo instruction
12110   MI->eraseFromParent();
12111
12112   return endMBB;
12113 }
12114
12115 MachineBasicBlock *
12116 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12117                                                  MachineInstr *MI,
12118                                                  MachineBasicBlock *MBB) const {
12119   // Emit code to save XMM registers to the stack. The ABI says that the
12120   // number of registers to save is given in %al, so it's theoretically
12121   // possible to do an indirect jump trick to avoid saving all of them,
12122   // however this code takes a simpler approach and just executes all
12123   // of the stores if %al is non-zero. It's less code, and it's probably
12124   // easier on the hardware branch predictor, and stores aren't all that
12125   // expensive anyway.
12126
12127   // Create the new basic blocks. One block contains all the XMM stores,
12128   // and one block is the final destination regardless of whether any
12129   // stores were performed.
12130   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12131   MachineFunction *F = MBB->getParent();
12132   MachineFunction::iterator MBBIter = MBB;
12133   ++MBBIter;
12134   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12135   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12136   F->insert(MBBIter, XMMSaveMBB);
12137   F->insert(MBBIter, EndMBB);
12138
12139   // Transfer the remainder of MBB and its successor edges to EndMBB.
12140   EndMBB->splice(EndMBB->begin(), MBB,
12141                  llvm::next(MachineBasicBlock::iterator(MI)),
12142                  MBB->end());
12143   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12144
12145   // The original block will now fall through to the XMM save block.
12146   MBB->addSuccessor(XMMSaveMBB);
12147   // The XMMSaveMBB will fall through to the end block.
12148   XMMSaveMBB->addSuccessor(EndMBB);
12149
12150   // Now add the instructions.
12151   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12152   DebugLoc DL = MI->getDebugLoc();
12153
12154   unsigned CountReg = MI->getOperand(0).getReg();
12155   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12156   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12157
12158   if (!Subtarget->isTargetWin64()) {
12159     // If %al is 0, branch around the XMM save block.
12160     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12161     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12162     MBB->addSuccessor(EndMBB);
12163   }
12164
12165   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12166   // In the XMM save block, save all the XMM argument registers.
12167   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12168     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12169     MachineMemOperand *MMO =
12170       F->getMachineMemOperand(
12171           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12172         MachineMemOperand::MOStore,
12173         /*Size=*/16, /*Align=*/16);
12174     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12175       .addFrameIndex(RegSaveFrameIndex)
12176       .addImm(/*Scale=*/1)
12177       .addReg(/*IndexReg=*/0)
12178       .addImm(/*Disp=*/Offset)
12179       .addReg(/*Segment=*/0)
12180       .addReg(MI->getOperand(i).getReg())
12181       .addMemOperand(MMO);
12182   }
12183
12184   MI->eraseFromParent();   // The pseudo instruction is gone now.
12185
12186   return EndMBB;
12187 }
12188
12189 // The EFLAGS operand of SelectItr might be missing a kill marker
12190 // because there were multiple uses of EFLAGS, and ISel didn't know
12191 // which to mark. Figure out whether SelectItr should have had a
12192 // kill marker, and set it if it should. Returns the correct kill
12193 // marker value.
12194 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12195                                      MachineBasicBlock* BB,
12196                                      const TargetRegisterInfo* TRI) {
12197   // Scan forward through BB for a use/def of EFLAGS.
12198   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12199   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12200     const MachineInstr& mi = *miI;
12201     if (mi.readsRegister(X86::EFLAGS))
12202       return false;
12203     if (mi.definesRegister(X86::EFLAGS))
12204       break; // Should have kill-flag - update below.
12205   }
12206
12207   // If we hit the end of the block, check whether EFLAGS is live into a
12208   // successor.
12209   if (miI == BB->end()) {
12210     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12211                                           sEnd = BB->succ_end();
12212          sItr != sEnd; ++sItr) {
12213       MachineBasicBlock* succ = *sItr;
12214       if (succ->isLiveIn(X86::EFLAGS))
12215         return false;
12216     }
12217   }
12218
12219   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12220   // out. SelectMI should have a kill flag on EFLAGS.
12221   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12222   return true;
12223 }
12224
12225 MachineBasicBlock *
12226 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12227                                      MachineBasicBlock *BB) const {
12228   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12229   DebugLoc DL = MI->getDebugLoc();
12230
12231   // To "insert" a SELECT_CC instruction, we actually have to insert the
12232   // diamond control-flow pattern.  The incoming instruction knows the
12233   // destination vreg to set, the condition code register to branch on, the
12234   // true/false values to select between, and a branch opcode to use.
12235   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12236   MachineFunction::iterator It = BB;
12237   ++It;
12238
12239   //  thisMBB:
12240   //  ...
12241   //   TrueVal = ...
12242   //   cmpTY ccX, r1, r2
12243   //   bCC copy1MBB
12244   //   fallthrough --> copy0MBB
12245   MachineBasicBlock *thisMBB = BB;
12246   MachineFunction *F = BB->getParent();
12247   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12248   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12249   F->insert(It, copy0MBB);
12250   F->insert(It, sinkMBB);
12251
12252   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12253   // live into the sink and copy blocks.
12254   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12255   if (!MI->killsRegister(X86::EFLAGS) &&
12256       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12257     copy0MBB->addLiveIn(X86::EFLAGS);
12258     sinkMBB->addLiveIn(X86::EFLAGS);
12259   }
12260
12261   // Transfer the remainder of BB and its successor edges to sinkMBB.
12262   sinkMBB->splice(sinkMBB->begin(), BB,
12263                   llvm::next(MachineBasicBlock::iterator(MI)),
12264                   BB->end());
12265   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12266
12267   // Add the true and fallthrough blocks as its successors.
12268   BB->addSuccessor(copy0MBB);
12269   BB->addSuccessor(sinkMBB);
12270
12271   // Create the conditional branch instruction.
12272   unsigned Opc =
12273     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12274   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12275
12276   //  copy0MBB:
12277   //   %FalseValue = ...
12278   //   # fallthrough to sinkMBB
12279   copy0MBB->addSuccessor(sinkMBB);
12280
12281   //  sinkMBB:
12282   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12283   //  ...
12284   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12285           TII->get(X86::PHI), MI->getOperand(0).getReg())
12286     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12287     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12288
12289   MI->eraseFromParent();   // The pseudo instruction is gone now.
12290   return sinkMBB;
12291 }
12292
12293 MachineBasicBlock *
12294 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12295                                         bool Is64Bit) const {
12296   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12297   DebugLoc DL = MI->getDebugLoc();
12298   MachineFunction *MF = BB->getParent();
12299   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12300
12301   assert(getTargetMachine().Options.EnableSegmentedStacks);
12302
12303   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12304   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12305
12306   // BB:
12307   //  ... [Till the alloca]
12308   // If stacklet is not large enough, jump to mallocMBB
12309   //
12310   // bumpMBB:
12311   //  Allocate by subtracting from RSP
12312   //  Jump to continueMBB
12313   //
12314   // mallocMBB:
12315   //  Allocate by call to runtime
12316   //
12317   // continueMBB:
12318   //  ...
12319   //  [rest of original BB]
12320   //
12321
12322   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12323   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12324   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12325
12326   MachineRegisterInfo &MRI = MF->getRegInfo();
12327   const TargetRegisterClass *AddrRegClass =
12328     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12329
12330   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12331     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12332     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12333     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12334     sizeVReg = MI->getOperand(1).getReg(),
12335     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12336
12337   MachineFunction::iterator MBBIter = BB;
12338   ++MBBIter;
12339
12340   MF->insert(MBBIter, bumpMBB);
12341   MF->insert(MBBIter, mallocMBB);
12342   MF->insert(MBBIter, continueMBB);
12343
12344   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12345                       (MachineBasicBlock::iterator(MI)), BB->end());
12346   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12347
12348   // Add code to the main basic block to check if the stack limit has been hit,
12349   // and if so, jump to mallocMBB otherwise to bumpMBB.
12350   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12351   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12352     .addReg(tmpSPVReg).addReg(sizeVReg);
12353   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12354     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12355     .addReg(SPLimitVReg);
12356   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12357
12358   // bumpMBB simply decreases the stack pointer, since we know the current
12359   // stacklet has enough space.
12360   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12361     .addReg(SPLimitVReg);
12362   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12363     .addReg(SPLimitVReg);
12364   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12365
12366   // Calls into a routine in libgcc to allocate more space from the heap.
12367   const uint32_t *RegMask =
12368     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12369   if (Is64Bit) {
12370     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12371       .addReg(sizeVReg);
12372     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12373       .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI)
12374       .addRegMask(RegMask)
12375       .addReg(X86::RAX, RegState::ImplicitDefine);
12376   } else {
12377     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12378       .addImm(12);
12379     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12380     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12381       .addExternalSymbol("__morestack_allocate_stack_space")
12382       .addRegMask(RegMask)
12383       .addReg(X86::EAX, RegState::ImplicitDefine);
12384   }
12385
12386   if (!Is64Bit)
12387     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12388       .addImm(16);
12389
12390   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12391     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12392   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12393
12394   // Set up the CFG correctly.
12395   BB->addSuccessor(bumpMBB);
12396   BB->addSuccessor(mallocMBB);
12397   mallocMBB->addSuccessor(continueMBB);
12398   bumpMBB->addSuccessor(continueMBB);
12399
12400   // Take care of the PHI nodes.
12401   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12402           MI->getOperand(0).getReg())
12403     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12404     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12405
12406   // Delete the original pseudo instruction.
12407   MI->eraseFromParent();
12408
12409   // And we're done.
12410   return continueMBB;
12411 }
12412
12413 MachineBasicBlock *
12414 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12415                                           MachineBasicBlock *BB) const {
12416   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12417   DebugLoc DL = MI->getDebugLoc();
12418
12419   assert(!Subtarget->isTargetEnvMacho());
12420
12421   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12422   // non-trivial part is impdef of ESP.
12423
12424   if (Subtarget->isTargetWin64()) {
12425     if (Subtarget->isTargetCygMing()) {
12426       // ___chkstk(Mingw64):
12427       // Clobbers R10, R11, RAX and EFLAGS.
12428       // Updates RSP.
12429       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12430         .addExternalSymbol("___chkstk")
12431         .addReg(X86::RAX, RegState::Implicit)
12432         .addReg(X86::RSP, RegState::Implicit)
12433         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12434         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12435         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12436     } else {
12437       // __chkstk(MSVCRT): does not update stack pointer.
12438       // Clobbers R10, R11 and EFLAGS.
12439       // FIXME: RAX(allocated size) might be reused and not killed.
12440       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12441         .addExternalSymbol("__chkstk")
12442         .addReg(X86::RAX, RegState::Implicit)
12443         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12444       // RAX has the offset to subtracted from RSP.
12445       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12446         .addReg(X86::RSP)
12447         .addReg(X86::RAX);
12448     }
12449   } else {
12450     const char *StackProbeSymbol =
12451       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12452
12453     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12454       .addExternalSymbol(StackProbeSymbol)
12455       .addReg(X86::EAX, RegState::Implicit)
12456       .addReg(X86::ESP, RegState::Implicit)
12457       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12458       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12459       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12460   }
12461
12462   MI->eraseFromParent();   // The pseudo instruction is gone now.
12463   return BB;
12464 }
12465
12466 MachineBasicBlock *
12467 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12468                                       MachineBasicBlock *BB) const {
12469   // This is pretty easy.  We're taking the value that we received from
12470   // our load from the relocation, sticking it in either RDI (x86-64)
12471   // or EAX and doing an indirect call.  The return value will then
12472   // be in the normal return register.
12473   const X86InstrInfo *TII
12474     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12475   DebugLoc DL = MI->getDebugLoc();
12476   MachineFunction *F = BB->getParent();
12477
12478   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12479   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12480
12481   // Get a register mask for the lowered call.
12482   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12483   // proper register mask.
12484   const uint32_t *RegMask =
12485     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12486   if (Subtarget->is64Bit()) {
12487     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12488                                       TII->get(X86::MOV64rm), X86::RDI)
12489     .addReg(X86::RIP)
12490     .addImm(0).addReg(0)
12491     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12492                       MI->getOperand(3).getTargetFlags())
12493     .addReg(0);
12494     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12495     addDirectMem(MIB, X86::RDI);
12496     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12497   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12498     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12499                                       TII->get(X86::MOV32rm), X86::EAX)
12500     .addReg(0)
12501     .addImm(0).addReg(0)
12502     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12503                       MI->getOperand(3).getTargetFlags())
12504     .addReg(0);
12505     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12506     addDirectMem(MIB, X86::EAX);
12507     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12508   } else {
12509     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12510                                       TII->get(X86::MOV32rm), X86::EAX)
12511     .addReg(TII->getGlobalBaseReg(F))
12512     .addImm(0).addReg(0)
12513     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12514                       MI->getOperand(3).getTargetFlags())
12515     .addReg(0);
12516     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12517     addDirectMem(MIB, X86::EAX);
12518     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12519   }
12520
12521   MI->eraseFromParent(); // The pseudo instruction is gone now.
12522   return BB;
12523 }
12524
12525 MachineBasicBlock *
12526 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12527                                                MachineBasicBlock *BB) const {
12528   switch (MI->getOpcode()) {
12529   default: llvm_unreachable("Unexpected instr type to insert");
12530   case X86::TAILJMPd64:
12531   case X86::TAILJMPr64:
12532   case X86::TAILJMPm64:
12533     llvm_unreachable("TAILJMP64 would not be touched here.");
12534   case X86::TCRETURNdi64:
12535   case X86::TCRETURNri64:
12536   case X86::TCRETURNmi64:
12537     return BB;
12538   case X86::WIN_ALLOCA:
12539     return EmitLoweredWinAlloca(MI, BB);
12540   case X86::SEG_ALLOCA_32:
12541     return EmitLoweredSegAlloca(MI, BB, false);
12542   case X86::SEG_ALLOCA_64:
12543     return EmitLoweredSegAlloca(MI, BB, true);
12544   case X86::TLSCall_32:
12545   case X86::TLSCall_64:
12546     return EmitLoweredTLSCall(MI, BB);
12547   case X86::CMOV_GR8:
12548   case X86::CMOV_FR32:
12549   case X86::CMOV_FR64:
12550   case X86::CMOV_V4F32:
12551   case X86::CMOV_V2F64:
12552   case X86::CMOV_V2I64:
12553   case X86::CMOV_V8F32:
12554   case X86::CMOV_V4F64:
12555   case X86::CMOV_V4I64:
12556   case X86::CMOV_GR16:
12557   case X86::CMOV_GR32:
12558   case X86::CMOV_RFP32:
12559   case X86::CMOV_RFP64:
12560   case X86::CMOV_RFP80:
12561     return EmitLoweredSelect(MI, BB);
12562
12563   case X86::FP32_TO_INT16_IN_MEM:
12564   case X86::FP32_TO_INT32_IN_MEM:
12565   case X86::FP32_TO_INT64_IN_MEM:
12566   case X86::FP64_TO_INT16_IN_MEM:
12567   case X86::FP64_TO_INT32_IN_MEM:
12568   case X86::FP64_TO_INT64_IN_MEM:
12569   case X86::FP80_TO_INT16_IN_MEM:
12570   case X86::FP80_TO_INT32_IN_MEM:
12571   case X86::FP80_TO_INT64_IN_MEM: {
12572     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12573     DebugLoc DL = MI->getDebugLoc();
12574
12575     // Change the floating point control register to use "round towards zero"
12576     // mode when truncating to an integer value.
12577     MachineFunction *F = BB->getParent();
12578     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12579     addFrameReference(BuildMI(*BB, MI, DL,
12580                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12581
12582     // Load the old value of the high byte of the control word...
12583     unsigned OldCW =
12584       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12585     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12586                       CWFrameIdx);
12587
12588     // Set the high part to be round to zero...
12589     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12590       .addImm(0xC7F);
12591
12592     // Reload the modified control word now...
12593     addFrameReference(BuildMI(*BB, MI, DL,
12594                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12595
12596     // Restore the memory image of control word to original value
12597     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12598       .addReg(OldCW);
12599
12600     // Get the X86 opcode to use.
12601     unsigned Opc;
12602     switch (MI->getOpcode()) {
12603     default: llvm_unreachable("illegal opcode!");
12604     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12605     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12606     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12607     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12608     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12609     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12610     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12611     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12612     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12613     }
12614
12615     X86AddressMode AM;
12616     MachineOperand &Op = MI->getOperand(0);
12617     if (Op.isReg()) {
12618       AM.BaseType = X86AddressMode::RegBase;
12619       AM.Base.Reg = Op.getReg();
12620     } else {
12621       AM.BaseType = X86AddressMode::FrameIndexBase;
12622       AM.Base.FrameIndex = Op.getIndex();
12623     }
12624     Op = MI->getOperand(1);
12625     if (Op.isImm())
12626       AM.Scale = Op.getImm();
12627     Op = MI->getOperand(2);
12628     if (Op.isImm())
12629       AM.IndexReg = Op.getImm();
12630     Op = MI->getOperand(3);
12631     if (Op.isGlobal()) {
12632       AM.GV = Op.getGlobal();
12633     } else {
12634       AM.Disp = Op.getImm();
12635     }
12636     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12637                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12638
12639     // Reload the original control word now.
12640     addFrameReference(BuildMI(*BB, MI, DL,
12641                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12642
12643     MI->eraseFromParent();   // The pseudo instruction is gone now.
12644     return BB;
12645   }
12646     // String/text processing lowering.
12647   case X86::PCMPISTRM128REG:
12648   case X86::VPCMPISTRM128REG:
12649     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12650   case X86::PCMPISTRM128MEM:
12651   case X86::VPCMPISTRM128MEM:
12652     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12653   case X86::PCMPESTRM128REG:
12654   case X86::VPCMPESTRM128REG:
12655     return EmitPCMP(MI, BB, 5, false /* in mem */);
12656   case X86::PCMPESTRM128MEM:
12657   case X86::VPCMPESTRM128MEM:
12658     return EmitPCMP(MI, BB, 5, true /* in mem */);
12659
12660     // Thread synchronization.
12661   case X86::MONITOR:
12662     return EmitMonitor(MI, BB);
12663   case X86::MWAIT:
12664     return EmitMwait(MI, BB);
12665
12666     // Atomic Lowering.
12667   case X86::ATOMAND32:
12668     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12669                                                X86::AND32ri, X86::MOV32rm,
12670                                                X86::LCMPXCHG32,
12671                                                X86::NOT32r, X86::EAX,
12672                                                &X86::GR32RegClass);
12673   case X86::ATOMOR32:
12674     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12675                                                X86::OR32ri, X86::MOV32rm,
12676                                                X86::LCMPXCHG32,
12677                                                X86::NOT32r, X86::EAX,
12678                                                &X86::GR32RegClass);
12679   case X86::ATOMXOR32:
12680     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12681                                                X86::XOR32ri, X86::MOV32rm,
12682                                                X86::LCMPXCHG32,
12683                                                X86::NOT32r, X86::EAX,
12684                                                &X86::GR32RegClass);
12685   case X86::ATOMNAND32:
12686     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12687                                                X86::AND32ri, X86::MOV32rm,
12688                                                X86::LCMPXCHG32,
12689                                                X86::NOT32r, X86::EAX,
12690                                                &X86::GR32RegClass, true);
12691   case X86::ATOMMIN32:
12692     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12693   case X86::ATOMMAX32:
12694     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12695   case X86::ATOMUMIN32:
12696     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12697   case X86::ATOMUMAX32:
12698     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12699
12700   case X86::ATOMAND16:
12701     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12702                                                X86::AND16ri, X86::MOV16rm,
12703                                                X86::LCMPXCHG16,
12704                                                X86::NOT16r, X86::AX,
12705                                                &X86::GR16RegClass);
12706   case X86::ATOMOR16:
12707     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12708                                                X86::OR16ri, X86::MOV16rm,
12709                                                X86::LCMPXCHG16,
12710                                                X86::NOT16r, X86::AX,
12711                                                &X86::GR16RegClass);
12712   case X86::ATOMXOR16:
12713     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12714                                                X86::XOR16ri, X86::MOV16rm,
12715                                                X86::LCMPXCHG16,
12716                                                X86::NOT16r, X86::AX,
12717                                                &X86::GR16RegClass);
12718   case X86::ATOMNAND16:
12719     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12720                                                X86::AND16ri, X86::MOV16rm,
12721                                                X86::LCMPXCHG16,
12722                                                X86::NOT16r, X86::AX,
12723                                                &X86::GR16RegClass, true);
12724   case X86::ATOMMIN16:
12725     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12726   case X86::ATOMMAX16:
12727     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12728   case X86::ATOMUMIN16:
12729     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12730   case X86::ATOMUMAX16:
12731     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12732
12733   case X86::ATOMAND8:
12734     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12735                                                X86::AND8ri, X86::MOV8rm,
12736                                                X86::LCMPXCHG8,
12737                                                X86::NOT8r, X86::AL,
12738                                                &X86::GR8RegClass);
12739   case X86::ATOMOR8:
12740     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12741                                                X86::OR8ri, X86::MOV8rm,
12742                                                X86::LCMPXCHG8,
12743                                                X86::NOT8r, X86::AL,
12744                                                &X86::GR8RegClass);
12745   case X86::ATOMXOR8:
12746     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12747                                                X86::XOR8ri, X86::MOV8rm,
12748                                                X86::LCMPXCHG8,
12749                                                X86::NOT8r, X86::AL,
12750                                                &X86::GR8RegClass);
12751   case X86::ATOMNAND8:
12752     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12753                                                X86::AND8ri, X86::MOV8rm,
12754                                                X86::LCMPXCHG8,
12755                                                X86::NOT8r, X86::AL,
12756                                                &X86::GR8RegClass, true);
12757   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12758   // This group is for 64-bit host.
12759   case X86::ATOMAND64:
12760     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12761                                                X86::AND64ri32, X86::MOV64rm,
12762                                                X86::LCMPXCHG64,
12763                                                X86::NOT64r, X86::RAX,
12764                                                &X86::GR64RegClass);
12765   case X86::ATOMOR64:
12766     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12767                                                X86::OR64ri32, X86::MOV64rm,
12768                                                X86::LCMPXCHG64,
12769                                                X86::NOT64r, X86::RAX,
12770                                                &X86::GR64RegClass);
12771   case X86::ATOMXOR64:
12772     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12773                                                X86::XOR64ri32, X86::MOV64rm,
12774                                                X86::LCMPXCHG64,
12775                                                X86::NOT64r, X86::RAX,
12776                                                &X86::GR64RegClass);
12777   case X86::ATOMNAND64:
12778     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12779                                                X86::AND64ri32, X86::MOV64rm,
12780                                                X86::LCMPXCHG64,
12781                                                X86::NOT64r, X86::RAX,
12782                                                &X86::GR64RegClass, true);
12783   case X86::ATOMMIN64:
12784     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12785   case X86::ATOMMAX64:
12786     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12787   case X86::ATOMUMIN64:
12788     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12789   case X86::ATOMUMAX64:
12790     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12791
12792   // This group does 64-bit operations on a 32-bit host.
12793   case X86::ATOMAND6432:
12794     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12795                                                X86::AND32rr, X86::AND32rr,
12796                                                X86::AND32ri, X86::AND32ri,
12797                                                false);
12798   case X86::ATOMOR6432:
12799     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12800                                                X86::OR32rr, X86::OR32rr,
12801                                                X86::OR32ri, X86::OR32ri,
12802                                                false);
12803   case X86::ATOMXOR6432:
12804     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12805                                                X86::XOR32rr, X86::XOR32rr,
12806                                                X86::XOR32ri, X86::XOR32ri,
12807                                                false);
12808   case X86::ATOMNAND6432:
12809     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12810                                                X86::AND32rr, X86::AND32rr,
12811                                                X86::AND32ri, X86::AND32ri,
12812                                                true);
12813   case X86::ATOMADD6432:
12814     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12815                                                X86::ADD32rr, X86::ADC32rr,
12816                                                X86::ADD32ri, X86::ADC32ri,
12817                                                false);
12818   case X86::ATOMSUB6432:
12819     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12820                                                X86::SUB32rr, X86::SBB32rr,
12821                                                X86::SUB32ri, X86::SBB32ri,
12822                                                false);
12823   case X86::ATOMSWAP6432:
12824     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12825                                                X86::MOV32rr, X86::MOV32rr,
12826                                                X86::MOV32ri, X86::MOV32ri,
12827                                                false);
12828   case X86::VASTART_SAVE_XMM_REGS:
12829     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12830
12831   case X86::VAARG_64:
12832     return EmitVAARG64WithCustomInserter(MI, BB);
12833   }
12834 }
12835
12836 //===----------------------------------------------------------------------===//
12837 //                           X86 Optimization Hooks
12838 //===----------------------------------------------------------------------===//
12839
12840 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12841                                                        APInt &KnownZero,
12842                                                        APInt &KnownOne,
12843                                                        const SelectionDAG &DAG,
12844                                                        unsigned Depth) const {
12845   unsigned BitWidth = KnownZero.getBitWidth();
12846   unsigned Opc = Op.getOpcode();
12847   assert((Opc >= ISD::BUILTIN_OP_END ||
12848           Opc == ISD::INTRINSIC_WO_CHAIN ||
12849           Opc == ISD::INTRINSIC_W_CHAIN ||
12850           Opc == ISD::INTRINSIC_VOID) &&
12851          "Should use MaskedValueIsZero if you don't know whether Op"
12852          " is a target node!");
12853
12854   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
12855   switch (Opc) {
12856   default: break;
12857   case X86ISD::ADD:
12858   case X86ISD::SUB:
12859   case X86ISD::ADC:
12860   case X86ISD::SBB:
12861   case X86ISD::SMUL:
12862   case X86ISD::UMUL:
12863   case X86ISD::INC:
12864   case X86ISD::DEC:
12865   case X86ISD::OR:
12866   case X86ISD::XOR:
12867   case X86ISD::AND:
12868     // These nodes' second result is a boolean.
12869     if (Op.getResNo() == 0)
12870       break;
12871     // Fallthrough
12872   case X86ISD::SETCC:
12873     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12874     break;
12875   case ISD::INTRINSIC_WO_CHAIN: {
12876     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12877     unsigned NumLoBits = 0;
12878     switch (IntId) {
12879     default: break;
12880     case Intrinsic::x86_sse_movmsk_ps:
12881     case Intrinsic::x86_avx_movmsk_ps_256:
12882     case Intrinsic::x86_sse2_movmsk_pd:
12883     case Intrinsic::x86_avx_movmsk_pd_256:
12884     case Intrinsic::x86_mmx_pmovmskb:
12885     case Intrinsic::x86_sse2_pmovmskb_128:
12886     case Intrinsic::x86_avx2_pmovmskb: {
12887       // High bits of movmskp{s|d}, pmovmskb are known zero.
12888       switch (IntId) {
12889         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12890         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12891         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12892         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12893         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12894         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12895         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12896         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
12897       }
12898       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
12899       break;
12900     }
12901     }
12902     break;
12903   }
12904   }
12905 }
12906
12907 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12908                                                          unsigned Depth) const {
12909   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12910   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12911     return Op.getValueType().getScalarType().getSizeInBits();
12912
12913   // Fallback case.
12914   return 1;
12915 }
12916
12917 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12918 /// node is a GlobalAddress + offset.
12919 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12920                                        const GlobalValue* &GA,
12921                                        int64_t &Offset) const {
12922   if (N->getOpcode() == X86ISD::Wrapper) {
12923     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12924       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12925       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12926       return true;
12927     }
12928   }
12929   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12930 }
12931
12932 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12933 /// same as extracting the high 128-bit part of 256-bit vector and then
12934 /// inserting the result into the low part of a new 256-bit vector
12935 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12936   EVT VT = SVOp->getValueType(0);
12937   unsigned NumElems = VT.getVectorNumElements();
12938
12939   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12940   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
12941     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12942         SVOp->getMaskElt(j) >= 0)
12943       return false;
12944
12945   return true;
12946 }
12947
12948 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12949 /// same as extracting the low 128-bit part of 256-bit vector and then
12950 /// inserting the result into the high part of a new 256-bit vector
12951 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12952   EVT VT = SVOp->getValueType(0);
12953   unsigned NumElems = VT.getVectorNumElements();
12954
12955   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12956   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
12957     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12958         SVOp->getMaskElt(j) >= 0)
12959       return false;
12960
12961   return true;
12962 }
12963
12964 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12965 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12966                                         TargetLowering::DAGCombinerInfo &DCI,
12967                                         const X86Subtarget* Subtarget) {
12968   DebugLoc dl = N->getDebugLoc();
12969   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12970   SDValue V1 = SVOp->getOperand(0);
12971   SDValue V2 = SVOp->getOperand(1);
12972   EVT VT = SVOp->getValueType(0);
12973   unsigned NumElems = VT.getVectorNumElements();
12974
12975   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12976       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12977     //
12978     //                   0,0,0,...
12979     //                      |
12980     //    V      UNDEF    BUILD_VECTOR    UNDEF
12981     //     \      /           \           /
12982     //  CONCAT_VECTOR         CONCAT_VECTOR
12983     //         \                  /
12984     //          \                /
12985     //          RESULT: V + zero extended
12986     //
12987     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12988         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12989         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12990       return SDValue();
12991
12992     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12993       return SDValue();
12994
12995     // To match the shuffle mask, the first half of the mask should
12996     // be exactly the first vector, and all the rest a splat with the
12997     // first element of the second one.
12998     for (unsigned i = 0; i != NumElems/2; ++i)
12999       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13000           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13001         return SDValue();
13002
13003     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13004     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13005       if (Ld->hasNUsesOfValue(1, 0)) {
13006         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13007         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13008         SDValue ResNode =
13009           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13010                                   Ld->getMemoryVT(),
13011                                   Ld->getPointerInfo(),
13012                                   Ld->getAlignment(),
13013                                   false/*isVolatile*/, true/*ReadMem*/,
13014                                   false/*WriteMem*/);
13015         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13016       }
13017     } 
13018
13019     // Emit a zeroed vector and insert the desired subvector on its
13020     // first half.
13021     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13022     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13023     return DCI.CombineTo(N, InsV);
13024   }
13025
13026   //===--------------------------------------------------------------------===//
13027   // Combine some shuffles into subvector extracts and inserts:
13028   //
13029
13030   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13031   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13032     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13033     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13034     return DCI.CombineTo(N, InsV);
13035   }
13036
13037   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13038   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13039     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13040     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13041     return DCI.CombineTo(N, InsV);
13042   }
13043
13044   return SDValue();
13045 }
13046
13047 /// PerformShuffleCombine - Performs several different shuffle combines.
13048 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13049                                      TargetLowering::DAGCombinerInfo &DCI,
13050                                      const X86Subtarget *Subtarget) {
13051   DebugLoc dl = N->getDebugLoc();
13052   EVT VT = N->getValueType(0);
13053
13054   // Don't create instructions with illegal types after legalize types has run.
13055   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13056   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13057     return SDValue();
13058
13059   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13060   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13061       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13062     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13063
13064   // Only handle 128 wide vector from here on.
13065   if (VT.getSizeInBits() != 128)
13066     return SDValue();
13067
13068   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13069   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13070   // consecutive, non-overlapping, and in the right order.
13071   SmallVector<SDValue, 16> Elts;
13072   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13073     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13074
13075   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13076 }
13077
13078
13079 /// DCI, PerformTruncateCombine - Converts truncate operation to
13080 /// a sequence of vector shuffle operations.
13081 /// It is possible when we truncate 256-bit vector to 128-bit vector
13082
13083 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG, 
13084                                                   DAGCombinerInfo &DCI) const {
13085   if (!DCI.isBeforeLegalizeOps())
13086     return SDValue();
13087
13088   if (!Subtarget->hasAVX())
13089     return SDValue();
13090
13091   EVT VT = N->getValueType(0);
13092   SDValue Op = N->getOperand(0);
13093   EVT OpVT = Op.getValueType();
13094   DebugLoc dl = N->getDebugLoc();
13095
13096   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13097
13098     if (Subtarget->hasAVX2()) {
13099       // AVX2: v4i64 -> v4i32
13100
13101       // VPERMD
13102       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13103
13104       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13105       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13106                                 ShufMask);
13107
13108       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13109                          DAG.getIntPtrConstant(0));
13110     }
13111
13112     // AVX: v4i64 -> v4i32
13113     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13114                                DAG.getIntPtrConstant(0));
13115
13116     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13117                                DAG.getIntPtrConstant(2));
13118
13119     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13120     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13121
13122     // PSHUFD
13123     static const int ShufMask1[] = {0, 2, 0, 0};
13124
13125     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1);
13126     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1);
13127
13128     // MOVLHPS
13129     static const int ShufMask2[] = {0, 1, 4, 5};
13130
13131     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13132   }
13133
13134   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13135
13136     if (Subtarget->hasAVX2()) {
13137       // AVX2: v8i32 -> v8i16
13138
13139       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13140
13141       // PSHUFB
13142       SmallVector<SDValue,32> pshufbMask;
13143       for (unsigned i = 0; i < 2; ++i) {
13144         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13145         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13146         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13147         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13148         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13149         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13150         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13151         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13152         for (unsigned j = 0; j < 8; ++j)
13153           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13154       }
13155       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13156                                &pshufbMask[0], 32);
13157       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13158
13159       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13160
13161       static const int ShufMask[] = {0,  2,  -1,  -1};
13162       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13163                                 &ShufMask[0]);
13164
13165       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13166                        DAG.getIntPtrConstant(0));
13167
13168       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13169     }
13170
13171     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13172                                DAG.getIntPtrConstant(0));
13173
13174     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13175                                DAG.getIntPtrConstant(4));
13176
13177     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13178     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13179
13180     // PSHUFB
13181     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13182                                    -1, -1, -1, -1, -1, -1, -1, -1};
13183
13184     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8),
13185                                 ShufMask1);
13186     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8),
13187                                 ShufMask1);
13188
13189     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13190     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13191
13192     // MOVLHPS
13193     static const int ShufMask2[] = {0, 1, 4, 5};
13194
13195     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13196     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13197   }
13198
13199   return SDValue();
13200 }
13201
13202 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13203 /// specific shuffle of a load can be folded into a single element load.
13204 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13205 /// shuffles have been customed lowered so we need to handle those here.
13206 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13207                                          TargetLowering::DAGCombinerInfo &DCI) {
13208   if (DCI.isBeforeLegalizeOps())
13209     return SDValue();
13210
13211   SDValue InVec = N->getOperand(0);
13212   SDValue EltNo = N->getOperand(1);
13213
13214   if (!isa<ConstantSDNode>(EltNo))
13215     return SDValue();
13216
13217   EVT VT = InVec.getValueType();
13218
13219   bool HasShuffleIntoBitcast = false;
13220   if (InVec.getOpcode() == ISD::BITCAST) {
13221     // Don't duplicate a load with other uses.
13222     if (!InVec.hasOneUse())
13223       return SDValue();
13224     EVT BCVT = InVec.getOperand(0).getValueType();
13225     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13226       return SDValue();
13227     InVec = InVec.getOperand(0);
13228     HasShuffleIntoBitcast = true;
13229   }
13230
13231   if (!isTargetShuffle(InVec.getOpcode()))
13232     return SDValue();
13233
13234   // Don't duplicate a load with other uses.
13235   if (!InVec.hasOneUse())
13236     return SDValue();
13237
13238   SmallVector<int, 16> ShuffleMask;
13239   bool UnaryShuffle;
13240   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13241                             UnaryShuffle))
13242     return SDValue();
13243
13244   // Select the input vector, guarding against out of range extract vector.
13245   unsigned NumElems = VT.getVectorNumElements();
13246   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13247   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13248   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13249                                          : InVec.getOperand(1);
13250
13251   // If inputs to shuffle are the same for both ops, then allow 2 uses
13252   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13253
13254   if (LdNode.getOpcode() == ISD::BITCAST) {
13255     // Don't duplicate a load with other uses.
13256     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13257       return SDValue();
13258
13259     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13260     LdNode = LdNode.getOperand(0);
13261   }
13262
13263   if (!ISD::isNormalLoad(LdNode.getNode()))
13264     return SDValue();
13265
13266   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13267
13268   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13269     return SDValue();
13270
13271   if (HasShuffleIntoBitcast) {
13272     // If there's a bitcast before the shuffle, check if the load type and
13273     // alignment is valid.
13274     unsigned Align = LN0->getAlignment();
13275     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13276     unsigned NewAlign = TLI.getTargetData()->
13277       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13278
13279     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13280       return SDValue();
13281   }
13282
13283   // All checks match so transform back to vector_shuffle so that DAG combiner
13284   // can finish the job
13285   DebugLoc dl = N->getDebugLoc();
13286
13287   // Create shuffle node taking into account the case that its a unary shuffle
13288   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13289   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13290                                  InVec.getOperand(0), Shuffle,
13291                                  &ShuffleMask[0]);
13292   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13293   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13294                      EltNo);
13295 }
13296
13297 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13298 /// generation and convert it from being a bunch of shuffles and extracts
13299 /// to a simple store and scalar loads to extract the elements.
13300 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13301                                          TargetLowering::DAGCombinerInfo &DCI) {
13302   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13303   if (NewOp.getNode())
13304     return NewOp;
13305
13306   SDValue InputVector = N->getOperand(0);
13307
13308   // Only operate on vectors of 4 elements, where the alternative shuffling
13309   // gets to be more expensive.
13310   if (InputVector.getValueType() != MVT::v4i32)
13311     return SDValue();
13312
13313   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13314   // single use which is a sign-extend or zero-extend, and all elements are
13315   // used.
13316   SmallVector<SDNode *, 4> Uses;
13317   unsigned ExtractedElements = 0;
13318   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13319        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13320     if (UI.getUse().getResNo() != InputVector.getResNo())
13321       return SDValue();
13322
13323     SDNode *Extract = *UI;
13324     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13325       return SDValue();
13326
13327     if (Extract->getValueType(0) != MVT::i32)
13328       return SDValue();
13329     if (!Extract->hasOneUse())
13330       return SDValue();
13331     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13332         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13333       return SDValue();
13334     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13335       return SDValue();
13336
13337     // Record which element was extracted.
13338     ExtractedElements |=
13339       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13340
13341     Uses.push_back(Extract);
13342   }
13343
13344   // If not all the elements were used, this may not be worthwhile.
13345   if (ExtractedElements != 15)
13346     return SDValue();
13347
13348   // Ok, we've now decided to do the transformation.
13349   DebugLoc dl = InputVector.getDebugLoc();
13350
13351   // Store the value to a temporary stack slot.
13352   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13353   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13354                             MachinePointerInfo(), false, false, 0);
13355
13356   // Replace each use (extract) with a load of the appropriate element.
13357   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13358        UE = Uses.end(); UI != UE; ++UI) {
13359     SDNode *Extract = *UI;
13360
13361     // cOMpute the element's address.
13362     SDValue Idx = Extract->getOperand(1);
13363     unsigned EltSize =
13364         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13365     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13366     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13367     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13368
13369     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13370                                      StackPtr, OffsetVal);
13371
13372     // Load the scalar.
13373     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13374                                      ScalarAddr, MachinePointerInfo(),
13375                                      false, false, false, 0);
13376
13377     // Replace the exact with the load.
13378     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13379   }
13380
13381   // The replacement was made in place; don't return anything.
13382   return SDValue();
13383 }
13384
13385 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13386 /// nodes.
13387 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13388                                     TargetLowering::DAGCombinerInfo &DCI,
13389                                     const X86Subtarget *Subtarget) {
13390   DebugLoc DL = N->getDebugLoc();
13391   SDValue Cond = N->getOperand(0);
13392   // Get the LHS/RHS of the select.
13393   SDValue LHS = N->getOperand(1);
13394   SDValue RHS = N->getOperand(2);
13395   EVT VT = LHS.getValueType();
13396
13397   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13398   // instructions match the semantics of the common C idiom x<y?x:y but not
13399   // x<=y?x:y, because of how they handle negative zero (which can be
13400   // ignored in unsafe-math mode).
13401   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13402       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13403       (Subtarget->hasSSE2() ||
13404        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13405     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13406
13407     unsigned Opcode = 0;
13408     // Check for x CC y ? x : y.
13409     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13410         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13411       switch (CC) {
13412       default: break;
13413       case ISD::SETULT:
13414         // Converting this to a min would handle NaNs incorrectly, and swapping
13415         // the operands would cause it to handle comparisons between positive
13416         // and negative zero incorrectly.
13417         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13418           if (!DAG.getTarget().Options.UnsafeFPMath &&
13419               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13420             break;
13421           std::swap(LHS, RHS);
13422         }
13423         Opcode = X86ISD::FMIN;
13424         break;
13425       case ISD::SETOLE:
13426         // Converting this to a min would handle comparisons between positive
13427         // and negative zero incorrectly.
13428         if (!DAG.getTarget().Options.UnsafeFPMath &&
13429             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13430           break;
13431         Opcode = X86ISD::FMIN;
13432         break;
13433       case ISD::SETULE:
13434         // Converting this to a min would handle both negative zeros and NaNs
13435         // incorrectly, but we can swap the operands to fix both.
13436         std::swap(LHS, RHS);
13437       case ISD::SETOLT:
13438       case ISD::SETLT:
13439       case ISD::SETLE:
13440         Opcode = X86ISD::FMIN;
13441         break;
13442
13443       case ISD::SETOGE:
13444         // Converting this to a max would handle comparisons between positive
13445         // and negative zero incorrectly.
13446         if (!DAG.getTarget().Options.UnsafeFPMath &&
13447             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13448           break;
13449         Opcode = X86ISD::FMAX;
13450         break;
13451       case ISD::SETUGT:
13452         // Converting this to a max would handle NaNs incorrectly, and swapping
13453         // the operands would cause it to handle comparisons between positive
13454         // and negative zero incorrectly.
13455         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13456           if (!DAG.getTarget().Options.UnsafeFPMath &&
13457               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13458             break;
13459           std::swap(LHS, RHS);
13460         }
13461         Opcode = X86ISD::FMAX;
13462         break;
13463       case ISD::SETUGE:
13464         // Converting this to a max would handle both negative zeros and NaNs
13465         // incorrectly, but we can swap the operands to fix both.
13466         std::swap(LHS, RHS);
13467       case ISD::SETOGT:
13468       case ISD::SETGT:
13469       case ISD::SETGE:
13470         Opcode = X86ISD::FMAX;
13471         break;
13472       }
13473     // Check for x CC y ? y : x -- a min/max with reversed arms.
13474     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13475                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13476       switch (CC) {
13477       default: break;
13478       case ISD::SETOGE:
13479         // Converting this to a min would handle comparisons between positive
13480         // and negative zero incorrectly, and swapping the operands would
13481         // cause it to handle NaNs incorrectly.
13482         if (!DAG.getTarget().Options.UnsafeFPMath &&
13483             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13484           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13485             break;
13486           std::swap(LHS, RHS);
13487         }
13488         Opcode = X86ISD::FMIN;
13489         break;
13490       case ISD::SETUGT:
13491         // Converting this to a min would handle NaNs incorrectly.
13492         if (!DAG.getTarget().Options.UnsafeFPMath &&
13493             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13494           break;
13495         Opcode = X86ISD::FMIN;
13496         break;
13497       case ISD::SETUGE:
13498         // Converting this to a min would handle both negative zeros and NaNs
13499         // incorrectly, but we can swap the operands to fix both.
13500         std::swap(LHS, RHS);
13501       case ISD::SETOGT:
13502       case ISD::SETGT:
13503       case ISD::SETGE:
13504         Opcode = X86ISD::FMIN;
13505         break;
13506
13507       case ISD::SETULT:
13508         // Converting this to a max would handle NaNs incorrectly.
13509         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13510           break;
13511         Opcode = X86ISD::FMAX;
13512         break;
13513       case ISD::SETOLE:
13514         // Converting this to a max would handle comparisons between positive
13515         // and negative zero incorrectly, and swapping the operands would
13516         // cause it to handle NaNs incorrectly.
13517         if (!DAG.getTarget().Options.UnsafeFPMath &&
13518             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13519           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13520             break;
13521           std::swap(LHS, RHS);
13522         }
13523         Opcode = X86ISD::FMAX;
13524         break;
13525       case ISD::SETULE:
13526         // Converting this to a max would handle both negative zeros and NaNs
13527         // incorrectly, but we can swap the operands to fix both.
13528         std::swap(LHS, RHS);
13529       case ISD::SETOLT:
13530       case ISD::SETLT:
13531       case ISD::SETLE:
13532         Opcode = X86ISD::FMAX;
13533         break;
13534       }
13535     }
13536
13537     if (Opcode)
13538       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13539   }
13540
13541   // If this is a select between two integer constants, try to do some
13542   // optimizations.
13543   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13544     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13545       // Don't do this for crazy integer types.
13546       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13547         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13548         // so that TrueC (the true value) is larger than FalseC.
13549         bool NeedsCondInvert = false;
13550
13551         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13552             // Efficiently invertible.
13553             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13554              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13555               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13556           NeedsCondInvert = true;
13557           std::swap(TrueC, FalseC);
13558         }
13559
13560         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13561         if (FalseC->getAPIntValue() == 0 &&
13562             TrueC->getAPIntValue().isPowerOf2()) {
13563           if (NeedsCondInvert) // Invert the condition if needed.
13564             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13565                                DAG.getConstant(1, Cond.getValueType()));
13566
13567           // Zero extend the condition if needed.
13568           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13569
13570           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13571           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13572                              DAG.getConstant(ShAmt, MVT::i8));
13573         }
13574
13575         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13576         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13577           if (NeedsCondInvert) // Invert the condition if needed.
13578             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13579                                DAG.getConstant(1, Cond.getValueType()));
13580
13581           // Zero extend the condition if needed.
13582           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13583                              FalseC->getValueType(0), Cond);
13584           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13585                              SDValue(FalseC, 0));
13586         }
13587
13588         // Optimize cases that will turn into an LEA instruction.  This requires
13589         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13590         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13591           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13592           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13593
13594           bool isFastMultiplier = false;
13595           if (Diff < 10) {
13596             switch ((unsigned char)Diff) {
13597               default: break;
13598               case 1:  // result = add base, cond
13599               case 2:  // result = lea base(    , cond*2)
13600               case 3:  // result = lea base(cond, cond*2)
13601               case 4:  // result = lea base(    , cond*4)
13602               case 5:  // result = lea base(cond, cond*4)
13603               case 8:  // result = lea base(    , cond*8)
13604               case 9:  // result = lea base(cond, cond*8)
13605                 isFastMultiplier = true;
13606                 break;
13607             }
13608           }
13609
13610           if (isFastMultiplier) {
13611             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13612             if (NeedsCondInvert) // Invert the condition if needed.
13613               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13614                                  DAG.getConstant(1, Cond.getValueType()));
13615
13616             // Zero extend the condition if needed.
13617             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13618                                Cond);
13619             // Scale the condition by the difference.
13620             if (Diff != 1)
13621               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13622                                  DAG.getConstant(Diff, Cond.getValueType()));
13623
13624             // Add the base if non-zero.
13625             if (FalseC->getAPIntValue() != 0)
13626               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13627                                  SDValue(FalseC, 0));
13628             return Cond;
13629           }
13630         }
13631       }
13632   }
13633
13634   // Canonicalize max and min:
13635   // (x > y) ? x : y -> (x >= y) ? x : y
13636   // (x < y) ? x : y -> (x <= y) ? x : y
13637   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13638   // the need for an extra compare
13639   // against zero. e.g.
13640   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13641   // subl   %esi, %edi
13642   // testl  %edi, %edi
13643   // movl   $0, %eax
13644   // cmovgl %edi, %eax
13645   // =>
13646   // xorl   %eax, %eax
13647   // subl   %esi, $edi
13648   // cmovsl %eax, %edi
13649   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13650       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13651       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13652     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13653     switch (CC) {
13654     default: break;
13655     case ISD::SETLT:
13656     case ISD::SETGT: {
13657       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13658       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13659                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
13660       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13661     }
13662     }
13663   }
13664
13665   // If we know that this node is legal then we know that it is going to be
13666   // matched by one of the SSE/AVX BLEND instructions. These instructions only
13667   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13668   // to simplify previous instructions.
13669   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13670   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13671       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
13672     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13673
13674     // Don't optimize vector selects that map to mask-registers.
13675     if (BitWidth == 1)
13676       return SDValue();
13677
13678     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13679     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13680
13681     APInt KnownZero, KnownOne;
13682     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13683                                           DCI.isBeforeLegalizeOps());
13684     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13685         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13686       DCI.CommitTargetLoweringOpt(TLO);
13687   }
13688
13689   return SDValue();
13690 }
13691
13692 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13693 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13694                                   TargetLowering::DAGCombinerInfo &DCI) {
13695   DebugLoc DL = N->getDebugLoc();
13696
13697   // If the flag operand isn't dead, don't touch this CMOV.
13698   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13699     return SDValue();
13700
13701   SDValue FalseOp = N->getOperand(0);
13702   SDValue TrueOp = N->getOperand(1);
13703   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13704   SDValue Cond = N->getOperand(3);
13705   if (CC == X86::COND_E || CC == X86::COND_NE) {
13706     switch (Cond.getOpcode()) {
13707     default: break;
13708     case X86ISD::BSR:
13709     case X86ISD::BSF:
13710       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13711       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13712         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13713     }
13714   }
13715
13716   // If this is a select between two integer constants, try to do some
13717   // optimizations.  Note that the operands are ordered the opposite of SELECT
13718   // operands.
13719   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13720     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13721       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13722       // larger than FalseC (the false value).
13723       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13724         CC = X86::GetOppositeBranchCondition(CC);
13725         std::swap(TrueC, FalseC);
13726       }
13727
13728       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13729       // This is efficient for any integer data type (including i8/i16) and
13730       // shift amount.
13731       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13732         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13733                            DAG.getConstant(CC, MVT::i8), Cond);
13734
13735         // Zero extend the condition if needed.
13736         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13737
13738         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13739         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13740                            DAG.getConstant(ShAmt, MVT::i8));
13741         if (N->getNumValues() == 2)  // Dead flag value?
13742           return DCI.CombineTo(N, Cond, SDValue());
13743         return Cond;
13744       }
13745
13746       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13747       // for any integer data type, including i8/i16.
13748       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13749         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13750                            DAG.getConstant(CC, MVT::i8), Cond);
13751
13752         // Zero extend the condition if needed.
13753         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13754                            FalseC->getValueType(0), Cond);
13755         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13756                            SDValue(FalseC, 0));
13757
13758         if (N->getNumValues() == 2)  // Dead flag value?
13759           return DCI.CombineTo(N, Cond, SDValue());
13760         return Cond;
13761       }
13762
13763       // Optimize cases that will turn into an LEA instruction.  This requires
13764       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13765       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13766         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13767         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13768
13769         bool isFastMultiplier = false;
13770         if (Diff < 10) {
13771           switch ((unsigned char)Diff) {
13772           default: break;
13773           case 1:  // result = add base, cond
13774           case 2:  // result = lea base(    , cond*2)
13775           case 3:  // result = lea base(cond, cond*2)
13776           case 4:  // result = lea base(    , cond*4)
13777           case 5:  // result = lea base(cond, cond*4)
13778           case 8:  // result = lea base(    , cond*8)
13779           case 9:  // result = lea base(cond, cond*8)
13780             isFastMultiplier = true;
13781             break;
13782           }
13783         }
13784
13785         if (isFastMultiplier) {
13786           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13787           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13788                              DAG.getConstant(CC, MVT::i8), Cond);
13789           // Zero extend the condition if needed.
13790           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13791                              Cond);
13792           // Scale the condition by the difference.
13793           if (Diff != 1)
13794             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13795                                DAG.getConstant(Diff, Cond.getValueType()));
13796
13797           // Add the base if non-zero.
13798           if (FalseC->getAPIntValue() != 0)
13799             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13800                                SDValue(FalseC, 0));
13801           if (N->getNumValues() == 2)  // Dead flag value?
13802             return DCI.CombineTo(N, Cond, SDValue());
13803           return Cond;
13804         }
13805       }
13806     }
13807   }
13808   return SDValue();
13809 }
13810
13811
13812 /// PerformMulCombine - Optimize a single multiply with constant into two
13813 /// in order to implement it with two cheaper instructions, e.g.
13814 /// LEA + SHL, LEA + LEA.
13815 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13816                                  TargetLowering::DAGCombinerInfo &DCI) {
13817   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13818     return SDValue();
13819
13820   EVT VT = N->getValueType(0);
13821   if (VT != MVT::i64)
13822     return SDValue();
13823
13824   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13825   if (!C)
13826     return SDValue();
13827   uint64_t MulAmt = C->getZExtValue();
13828   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13829     return SDValue();
13830
13831   uint64_t MulAmt1 = 0;
13832   uint64_t MulAmt2 = 0;
13833   if ((MulAmt % 9) == 0) {
13834     MulAmt1 = 9;
13835     MulAmt2 = MulAmt / 9;
13836   } else if ((MulAmt % 5) == 0) {
13837     MulAmt1 = 5;
13838     MulAmt2 = MulAmt / 5;
13839   } else if ((MulAmt % 3) == 0) {
13840     MulAmt1 = 3;
13841     MulAmt2 = MulAmt / 3;
13842   }
13843   if (MulAmt2 &&
13844       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13845     DebugLoc DL = N->getDebugLoc();
13846
13847     if (isPowerOf2_64(MulAmt2) &&
13848         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13849       // If second multiplifer is pow2, issue it first. We want the multiply by
13850       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13851       // is an add.
13852       std::swap(MulAmt1, MulAmt2);
13853
13854     SDValue NewMul;
13855     if (isPowerOf2_64(MulAmt1))
13856       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13857                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13858     else
13859       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13860                            DAG.getConstant(MulAmt1, VT));
13861
13862     if (isPowerOf2_64(MulAmt2))
13863       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13864                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13865     else
13866       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13867                            DAG.getConstant(MulAmt2, VT));
13868
13869     // Do not add new nodes to DAG combiner worklist.
13870     DCI.CombineTo(N, NewMul, false);
13871   }
13872   return SDValue();
13873 }
13874
13875 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13876   SDValue N0 = N->getOperand(0);
13877   SDValue N1 = N->getOperand(1);
13878   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13879   EVT VT = N0.getValueType();
13880
13881   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13882   // since the result of setcc_c is all zero's or all ones.
13883   if (VT.isInteger() && !VT.isVector() &&
13884       N1C && N0.getOpcode() == ISD::AND &&
13885       N0.getOperand(1).getOpcode() == ISD::Constant) {
13886     SDValue N00 = N0.getOperand(0);
13887     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13888         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13889           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13890          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13891       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13892       APInt ShAmt = N1C->getAPIntValue();
13893       Mask = Mask.shl(ShAmt);
13894       if (Mask != 0)
13895         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13896                            N00, DAG.getConstant(Mask, VT));
13897     }
13898   }
13899
13900
13901   // Hardware support for vector shifts is sparse which makes us scalarize the
13902   // vector operations in many cases. Also, on sandybridge ADD is faster than
13903   // shl.
13904   // (shl V, 1) -> add V,V
13905   if (isSplatVector(N1.getNode())) {
13906     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13907     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13908     // We shift all of the values by one. In many cases we do not have
13909     // hardware support for this operation. This is better expressed as an ADD
13910     // of two values.
13911     if (N1C && (1 == N1C->getZExtValue())) {
13912       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13913     }
13914   }
13915
13916   return SDValue();
13917 }
13918
13919 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13920 ///                       when possible.
13921 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13922                                    TargetLowering::DAGCombinerInfo &DCI,
13923                                    const X86Subtarget *Subtarget) {
13924   EVT VT = N->getValueType(0);
13925   if (N->getOpcode() == ISD::SHL) {
13926     SDValue V = PerformSHLCombine(N, DAG);
13927     if (V.getNode()) return V;
13928   }
13929
13930   // On X86 with SSE2 support, we can transform this to a vector shift if
13931   // all elements are shifted by the same amount.  We can't do this in legalize
13932   // because the a constant vector is typically transformed to a constant pool
13933   // so we have no knowledge of the shift amount.
13934   if (!Subtarget->hasSSE2())
13935     return SDValue();
13936
13937   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13938       (!Subtarget->hasAVX2() ||
13939        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13940     return SDValue();
13941
13942   SDValue ShAmtOp = N->getOperand(1);
13943   EVT EltVT = VT.getVectorElementType();
13944   DebugLoc DL = N->getDebugLoc();
13945   SDValue BaseShAmt = SDValue();
13946   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13947     unsigned NumElts = VT.getVectorNumElements();
13948     unsigned i = 0;
13949     for (; i != NumElts; ++i) {
13950       SDValue Arg = ShAmtOp.getOperand(i);
13951       if (Arg.getOpcode() == ISD::UNDEF) continue;
13952       BaseShAmt = Arg;
13953       break;
13954     }
13955     // Handle the case where the build_vector is all undef
13956     // FIXME: Should DAG allow this?
13957     if (i == NumElts)
13958       return SDValue();
13959
13960     for (; i != NumElts; ++i) {
13961       SDValue Arg = ShAmtOp.getOperand(i);
13962       if (Arg.getOpcode() == ISD::UNDEF) continue;
13963       if (Arg != BaseShAmt) {
13964         return SDValue();
13965       }
13966     }
13967   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13968              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13969     SDValue InVec = ShAmtOp.getOperand(0);
13970     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13971       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13972       unsigned i = 0;
13973       for (; i != NumElts; ++i) {
13974         SDValue Arg = InVec.getOperand(i);
13975         if (Arg.getOpcode() == ISD::UNDEF) continue;
13976         BaseShAmt = Arg;
13977         break;
13978       }
13979     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13980        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13981          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13982          if (C->getZExtValue() == SplatIdx)
13983            BaseShAmt = InVec.getOperand(1);
13984        }
13985     }
13986     if (BaseShAmt.getNode() == 0) {
13987       // Don't create instructions with illegal types after legalize
13988       // types has run.
13989       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
13990           !DCI.isBeforeLegalize())
13991         return SDValue();
13992
13993       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13994                               DAG.getIntPtrConstant(0));
13995     }
13996   } else
13997     return SDValue();
13998
13999   // The shift amount is an i32.
14000   if (EltVT.bitsGT(MVT::i32))
14001     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14002   else if (EltVT.bitsLT(MVT::i32))
14003     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14004
14005   // The shift amount is identical so we can do a vector shift.
14006   SDValue  ValOp = N->getOperand(0);
14007   switch (N->getOpcode()) {
14008   default:
14009     llvm_unreachable("Unknown shift opcode!");
14010   case ISD::SHL:
14011     switch (VT.getSimpleVT().SimpleTy) {
14012     default: return SDValue();
14013     case MVT::v2i64:
14014     case MVT::v4i32:
14015     case MVT::v8i16:
14016     case MVT::v4i64:
14017     case MVT::v8i32:
14018     case MVT::v16i16:
14019       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14020     }
14021   case ISD::SRA:
14022     switch (VT.getSimpleVT().SimpleTy) {
14023     default: return SDValue();
14024     case MVT::v4i32:
14025     case MVT::v8i16:
14026     case MVT::v8i32:
14027     case MVT::v16i16:
14028       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14029     }
14030   case ISD::SRL:
14031     switch (VT.getSimpleVT().SimpleTy) {
14032     default: return SDValue();
14033     case MVT::v2i64:
14034     case MVT::v4i32:
14035     case MVT::v8i16:
14036     case MVT::v4i64:
14037     case MVT::v8i32:
14038     case MVT::v16i16:
14039       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14040     }
14041   }
14042 }
14043
14044
14045 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14046 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14047 // and friends.  Likewise for OR -> CMPNEQSS.
14048 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14049                             TargetLowering::DAGCombinerInfo &DCI,
14050                             const X86Subtarget *Subtarget) {
14051   unsigned opcode;
14052
14053   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14054   // we're requiring SSE2 for both.
14055   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14056     SDValue N0 = N->getOperand(0);
14057     SDValue N1 = N->getOperand(1);
14058     SDValue CMP0 = N0->getOperand(1);
14059     SDValue CMP1 = N1->getOperand(1);
14060     DebugLoc DL = N->getDebugLoc();
14061
14062     // The SETCCs should both refer to the same CMP.
14063     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14064       return SDValue();
14065
14066     SDValue CMP00 = CMP0->getOperand(0);
14067     SDValue CMP01 = CMP0->getOperand(1);
14068     EVT     VT    = CMP00.getValueType();
14069
14070     if (VT == MVT::f32 || VT == MVT::f64) {
14071       bool ExpectingFlags = false;
14072       // Check for any users that want flags:
14073       for (SDNode::use_iterator UI = N->use_begin(),
14074              UE = N->use_end();
14075            !ExpectingFlags && UI != UE; ++UI)
14076         switch (UI->getOpcode()) {
14077         default:
14078         case ISD::BR_CC:
14079         case ISD::BRCOND:
14080         case ISD::SELECT:
14081           ExpectingFlags = true;
14082           break;
14083         case ISD::CopyToReg:
14084         case ISD::SIGN_EXTEND:
14085         case ISD::ZERO_EXTEND:
14086         case ISD::ANY_EXTEND:
14087           break;
14088         }
14089
14090       if (!ExpectingFlags) {
14091         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14092         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14093
14094         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14095           X86::CondCode tmp = cc0;
14096           cc0 = cc1;
14097           cc1 = tmp;
14098         }
14099
14100         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14101             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14102           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14103           X86ISD::NodeType NTOperator = is64BitFP ?
14104             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14105           // FIXME: need symbolic constants for these magic numbers.
14106           // See X86ATTInstPrinter.cpp:printSSECC().
14107           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14108           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14109                                               DAG.getConstant(x86cc, MVT::i8));
14110           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14111                                               OnesOrZeroesF);
14112           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14113                                       DAG.getConstant(1, MVT::i32));
14114           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14115           return OneBitOfTruth;
14116         }
14117       }
14118     }
14119   }
14120   return SDValue();
14121 }
14122
14123 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14124 /// so it can be folded inside ANDNP.
14125 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14126   EVT VT = N->getValueType(0);
14127
14128   // Match direct AllOnes for 128 and 256-bit vectors
14129   if (ISD::isBuildVectorAllOnes(N))
14130     return true;
14131
14132   // Look through a bit convert.
14133   if (N->getOpcode() == ISD::BITCAST)
14134     N = N->getOperand(0).getNode();
14135
14136   // Sometimes the operand may come from a insert_subvector building a 256-bit
14137   // allones vector
14138   if (VT.getSizeInBits() == 256 &&
14139       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14140     SDValue V1 = N->getOperand(0);
14141     SDValue V2 = N->getOperand(1);
14142
14143     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14144         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14145         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14146         ISD::isBuildVectorAllOnes(V2.getNode()))
14147       return true;
14148   }
14149
14150   return false;
14151 }
14152
14153 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14154                                  TargetLowering::DAGCombinerInfo &DCI,
14155                                  const X86Subtarget *Subtarget) {
14156   if (DCI.isBeforeLegalizeOps())
14157     return SDValue();
14158
14159   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14160   if (R.getNode())
14161     return R;
14162
14163   EVT VT = N->getValueType(0);
14164
14165   // Create ANDN, BLSI, and BLSR instructions
14166   // BLSI is X & (-X)
14167   // BLSR is X & (X-1)
14168   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14169     SDValue N0 = N->getOperand(0);
14170     SDValue N1 = N->getOperand(1);
14171     DebugLoc DL = N->getDebugLoc();
14172
14173     // Check LHS for not
14174     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14175       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14176     // Check RHS for not
14177     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14178       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14179
14180     // Check LHS for neg
14181     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14182         isZero(N0.getOperand(0)))
14183       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14184
14185     // Check RHS for neg
14186     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14187         isZero(N1.getOperand(0)))
14188       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14189
14190     // Check LHS for X-1
14191     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14192         isAllOnes(N0.getOperand(1)))
14193       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14194
14195     // Check RHS for X-1
14196     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14197         isAllOnes(N1.getOperand(1)))
14198       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14199
14200     return SDValue();
14201   }
14202
14203   // Want to form ANDNP nodes:
14204   // 1) In the hopes of then easily combining them with OR and AND nodes
14205   //    to form PBLEND/PSIGN.
14206   // 2) To match ANDN packed intrinsics
14207   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14208     return SDValue();
14209
14210   SDValue N0 = N->getOperand(0);
14211   SDValue N1 = N->getOperand(1);
14212   DebugLoc DL = N->getDebugLoc();
14213
14214   // Check LHS for vnot
14215   if (N0.getOpcode() == ISD::XOR &&
14216       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14217       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14218     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14219
14220   // Check RHS for vnot
14221   if (N1.getOpcode() == ISD::XOR &&
14222       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14223       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14224     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14225
14226   return SDValue();
14227 }
14228
14229 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14230                                 TargetLowering::DAGCombinerInfo &DCI,
14231                                 const X86Subtarget *Subtarget) {
14232   if (DCI.isBeforeLegalizeOps())
14233     return SDValue();
14234
14235   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14236   if (R.getNode())
14237     return R;
14238
14239   EVT VT = N->getValueType(0);
14240
14241   SDValue N0 = N->getOperand(0);
14242   SDValue N1 = N->getOperand(1);
14243
14244   // look for psign/blend
14245   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14246     if (!Subtarget->hasSSSE3() ||
14247         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14248       return SDValue();
14249
14250     // Canonicalize pandn to RHS
14251     if (N0.getOpcode() == X86ISD::ANDNP)
14252       std::swap(N0, N1);
14253     // or (and (m, y), (pandn m, x))
14254     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14255       SDValue Mask = N1.getOperand(0);
14256       SDValue X    = N1.getOperand(1);
14257       SDValue Y;
14258       if (N0.getOperand(0) == Mask)
14259         Y = N0.getOperand(1);
14260       if (N0.getOperand(1) == Mask)
14261         Y = N0.getOperand(0);
14262
14263       // Check to see if the mask appeared in both the AND and ANDNP and
14264       if (!Y.getNode())
14265         return SDValue();
14266
14267       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14268       // Look through mask bitcast.
14269       if (Mask.getOpcode() == ISD::BITCAST)
14270         Mask = Mask.getOperand(0);
14271       if (X.getOpcode() == ISD::BITCAST)
14272         X = X.getOperand(0);
14273       if (Y.getOpcode() == ISD::BITCAST)
14274         Y = Y.getOperand(0);
14275
14276       EVT MaskVT = Mask.getValueType();
14277
14278       // Validate that the Mask operand is a vector sra node.
14279       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14280       // there is no psrai.b
14281       if (Mask.getOpcode() != X86ISD::VSRAI)
14282         return SDValue();
14283
14284       // Check that the SRA is all signbits.
14285       SDValue SraC = Mask.getOperand(1);
14286       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14287       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14288       if ((SraAmt + 1) != EltBits)
14289         return SDValue();
14290
14291       DebugLoc DL = N->getDebugLoc();
14292
14293       // Now we know we at least have a plendvb with the mask val.  See if
14294       // we can form a psignb/w/d.
14295       // psign = x.type == y.type == mask.type && y = sub(0, x);
14296       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14297           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14298           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14299         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14300                "Unsupported VT for PSIGN");
14301         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14302         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14303       }
14304       // PBLENDVB only available on SSE 4.1
14305       if (!Subtarget->hasSSE41())
14306         return SDValue();
14307
14308       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14309
14310       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14311       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14312       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14313       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14314       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14315     }
14316   }
14317
14318   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14319     return SDValue();
14320
14321   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14322   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14323     std::swap(N0, N1);
14324   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14325     return SDValue();
14326   if (!N0.hasOneUse() || !N1.hasOneUse())
14327     return SDValue();
14328
14329   SDValue ShAmt0 = N0.getOperand(1);
14330   if (ShAmt0.getValueType() != MVT::i8)
14331     return SDValue();
14332   SDValue ShAmt1 = N1.getOperand(1);
14333   if (ShAmt1.getValueType() != MVT::i8)
14334     return SDValue();
14335   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14336     ShAmt0 = ShAmt0.getOperand(0);
14337   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14338     ShAmt1 = ShAmt1.getOperand(0);
14339
14340   DebugLoc DL = N->getDebugLoc();
14341   unsigned Opc = X86ISD::SHLD;
14342   SDValue Op0 = N0.getOperand(0);
14343   SDValue Op1 = N1.getOperand(0);
14344   if (ShAmt0.getOpcode() == ISD::SUB) {
14345     Opc = X86ISD::SHRD;
14346     std::swap(Op0, Op1);
14347     std::swap(ShAmt0, ShAmt1);
14348   }
14349
14350   unsigned Bits = VT.getSizeInBits();
14351   if (ShAmt1.getOpcode() == ISD::SUB) {
14352     SDValue Sum = ShAmt1.getOperand(0);
14353     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14354       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14355       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14356         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14357       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14358         return DAG.getNode(Opc, DL, VT,
14359                            Op0, Op1,
14360                            DAG.getNode(ISD::TRUNCATE, DL,
14361                                        MVT::i8, ShAmt0));
14362     }
14363   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14364     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14365     if (ShAmt0C &&
14366         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14367       return DAG.getNode(Opc, DL, VT,
14368                          N0.getOperand(0), N1.getOperand(0),
14369                          DAG.getNode(ISD::TRUNCATE, DL,
14370                                        MVT::i8, ShAmt0));
14371   }
14372
14373   return SDValue();
14374 }
14375
14376 // Generate NEG and CMOV for integer abs.
14377 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14378   EVT VT = N->getValueType(0);
14379
14380   // Since X86 does not have CMOV for 8-bit integer, we don't convert
14381   // 8-bit integer abs to NEG and CMOV.
14382   if (VT.isInteger() && VT.getSizeInBits() == 8)
14383     return SDValue();
14384
14385   SDValue N0 = N->getOperand(0);
14386   SDValue N1 = N->getOperand(1);
14387   DebugLoc DL = N->getDebugLoc();
14388
14389   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14390   // and change it to SUB and CMOV.
14391   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14392       N0.getOpcode() == ISD::ADD &&
14393       N0.getOperand(1) == N1 &&
14394       N1.getOpcode() == ISD::SRA &&
14395       N1.getOperand(0) == N0.getOperand(0))
14396     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14397       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14398         // Generate SUB & CMOV.
14399         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14400                                   DAG.getConstant(0, VT), N0.getOperand(0));
14401
14402         SDValue Ops[] = { N0.getOperand(0), Neg,
14403                           DAG.getConstant(X86::COND_GE, MVT::i8),
14404                           SDValue(Neg.getNode(), 1) };
14405         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14406                            Ops, array_lengthof(Ops));
14407       }
14408   return SDValue();
14409 }
14410
14411 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14412 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14413                                  TargetLowering::DAGCombinerInfo &DCI,
14414                                  const X86Subtarget *Subtarget) {
14415   if (DCI.isBeforeLegalizeOps())
14416     return SDValue();
14417
14418   if (Subtarget->hasCMov()) {
14419     SDValue RV = performIntegerAbsCombine(N, DAG);
14420     if (RV.getNode())
14421       return RV;
14422   }
14423
14424   // Try forming BMI if it is available.
14425   if (!Subtarget->hasBMI())
14426     return SDValue();
14427
14428   EVT VT = N->getValueType(0);
14429
14430   if (VT != MVT::i32 && VT != MVT::i64)
14431     return SDValue();
14432
14433   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14434
14435   // Create BLSMSK instructions by finding X ^ (X-1)
14436   SDValue N0 = N->getOperand(0);
14437   SDValue N1 = N->getOperand(1);
14438   DebugLoc DL = N->getDebugLoc();
14439
14440   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14441       isAllOnes(N0.getOperand(1)))
14442     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14443
14444   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14445       isAllOnes(N1.getOperand(1)))
14446     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14447
14448   return SDValue();
14449 }
14450
14451 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14452 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14453                                    const X86Subtarget *Subtarget) {
14454   LoadSDNode *Ld = cast<LoadSDNode>(N);
14455   EVT RegVT = Ld->getValueType(0);
14456   EVT MemVT = Ld->getMemoryVT();
14457   DebugLoc dl = Ld->getDebugLoc();
14458   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14459
14460   ISD::LoadExtType Ext = Ld->getExtensionType();
14461
14462   // If this is a vector EXT Load then attempt to optimize it using a
14463   // shuffle. We need SSE4 for the shuffles.
14464   // TODO: It is possible to support ZExt by zeroing the undef values
14465   // during the shuffle phase or after the shuffle.
14466   if (RegVT.isVector() && RegVT.isInteger() &&
14467       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14468     assert(MemVT != RegVT && "Cannot extend to the same type");
14469     assert(MemVT.isVector() && "Must load a vector from memory");
14470
14471     unsigned NumElems = RegVT.getVectorNumElements();
14472     unsigned RegSz = RegVT.getSizeInBits();
14473     unsigned MemSz = MemVT.getSizeInBits();
14474     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14475     // All sizes must be a power of two
14476     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14477
14478     // Attempt to load the original value using a single load op.
14479     // Find a scalar type which is equal to the loaded word size.
14480     MVT SclrLoadTy = MVT::i8;
14481     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14482          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14483       MVT Tp = (MVT::SimpleValueType)tp;
14484       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
14485         SclrLoadTy = Tp;
14486         break;
14487       }
14488     }
14489
14490     // Proceed if a load word is found.
14491     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14492
14493     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14494       RegSz/SclrLoadTy.getSizeInBits());
14495
14496     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14497                                   RegSz/MemVT.getScalarType().getSizeInBits());
14498     // Can't shuffle using an illegal type.
14499     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14500
14501     // Perform a single load.
14502     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14503                                   Ld->getBasePtr(),
14504                                   Ld->getPointerInfo(), Ld->isVolatile(),
14505                                   Ld->isNonTemporal(), Ld->isInvariant(),
14506                                   Ld->getAlignment());
14507
14508     // Insert the word loaded into a vector.
14509     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14510       LoadUnitVecVT, ScalarLoad);
14511
14512     // Bitcast the loaded value to a vector of the original element type, in
14513     // the size of the target vector type.
14514     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT,
14515                                     ScalarInVector);
14516     unsigned SizeRatio = RegSz/MemSz;
14517
14518     // Redistribute the loaded elements into the different locations.
14519     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14520     for (unsigned i = 0; i != NumElems; ++i)
14521       ShuffleVec[i*SizeRatio] = i;
14522
14523     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14524                                          DAG.getUNDEF(WideVecVT),
14525                                          &ShuffleVec[0]);
14526
14527     // Bitcast to the requested type.
14528     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14529     // Replace the original load with the new sequence
14530     // and return the new chain.
14531     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14532     return SDValue(ScalarLoad.getNode(), 1);
14533   }
14534
14535   return SDValue();
14536 }
14537
14538 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14539 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14540                                    const X86Subtarget *Subtarget) {
14541   StoreSDNode *St = cast<StoreSDNode>(N);
14542   EVT VT = St->getValue().getValueType();
14543   EVT StVT = St->getMemoryVT();
14544   DebugLoc dl = St->getDebugLoc();
14545   SDValue StoredVal = St->getOperand(1);
14546   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14547
14548   // If we are saving a concatenation of two XMM registers, perform two stores.
14549   // On Sandy Bridge, 256-bit memory operations are executed by two
14550   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
14551   // memory  operation.
14552   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2() &&
14553       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14554       StoredVal.getNumOperands() == 2) {
14555     SDValue Value0 = StoredVal.getOperand(0);
14556     SDValue Value1 = StoredVal.getOperand(1);
14557
14558     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14559     SDValue Ptr0 = St->getBasePtr();
14560     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14561
14562     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14563                                 St->getPointerInfo(), St->isVolatile(),
14564                                 St->isNonTemporal(), St->getAlignment());
14565     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14566                                 St->getPointerInfo(), St->isVolatile(),
14567                                 St->isNonTemporal(), St->getAlignment());
14568     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14569   }
14570
14571   // Optimize trunc store (of multiple scalars) to shuffle and store.
14572   // First, pack all of the elements in one place. Next, store to memory
14573   // in fewer chunks.
14574   if (St->isTruncatingStore() && VT.isVector()) {
14575     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14576     unsigned NumElems = VT.getVectorNumElements();
14577     assert(StVT != VT && "Cannot truncate to the same type");
14578     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14579     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14580
14581     // From, To sizes and ElemCount must be pow of two
14582     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14583     // We are going to use the original vector elt for storing.
14584     // Accumulated smaller vector elements must be a multiple of the store size.
14585     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14586
14587     unsigned SizeRatio  = FromSz / ToSz;
14588
14589     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14590
14591     // Create a type on which we perform the shuffle
14592     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14593             StVT.getScalarType(), NumElems*SizeRatio);
14594
14595     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14596
14597     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14598     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14599     for (unsigned i = 0; i != NumElems; ++i)
14600       ShuffleVec[i] = i * SizeRatio;
14601
14602     // Can't shuffle using an illegal type
14603     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14604
14605     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14606                                          DAG.getUNDEF(WideVecVT),
14607                                          &ShuffleVec[0]);
14608     // At this point all of the data is stored at the bottom of the
14609     // register. We now need to save it to mem.
14610
14611     // Find the largest store unit
14612     MVT StoreType = MVT::i8;
14613     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14614          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14615       MVT Tp = (MVT::SimpleValueType)tp;
14616       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14617         StoreType = Tp;
14618     }
14619
14620     // Bitcast the original vector into a vector of store-size units
14621     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14622             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14623     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14624     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14625     SmallVector<SDValue, 8> Chains;
14626     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14627                                         TLI.getPointerTy());
14628     SDValue Ptr = St->getBasePtr();
14629
14630     // Perform one or more big stores into memory.
14631     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
14632       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14633                                    StoreType, ShuffWide,
14634                                    DAG.getIntPtrConstant(i));
14635       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14636                                 St->getPointerInfo(), St->isVolatile(),
14637                                 St->isNonTemporal(), St->getAlignment());
14638       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14639       Chains.push_back(Ch);
14640     }
14641
14642     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14643                                Chains.size());
14644   }
14645
14646
14647   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14648   // the FP state in cases where an emms may be missing.
14649   // A preferable solution to the general problem is to figure out the right
14650   // places to insert EMMS.  This qualifies as a quick hack.
14651
14652   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14653   if (VT.getSizeInBits() != 64)
14654     return SDValue();
14655
14656   const Function *F = DAG.getMachineFunction().getFunction();
14657   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14658   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14659                      && Subtarget->hasSSE2();
14660   if ((VT.isVector() ||
14661        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14662       isa<LoadSDNode>(St->getValue()) &&
14663       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14664       St->getChain().hasOneUse() && !St->isVolatile()) {
14665     SDNode* LdVal = St->getValue().getNode();
14666     LoadSDNode *Ld = 0;
14667     int TokenFactorIndex = -1;
14668     SmallVector<SDValue, 8> Ops;
14669     SDNode* ChainVal = St->getChain().getNode();
14670     // Must be a store of a load.  We currently handle two cases:  the load
14671     // is a direct child, and it's under an intervening TokenFactor.  It is
14672     // possible to dig deeper under nested TokenFactors.
14673     if (ChainVal == LdVal)
14674       Ld = cast<LoadSDNode>(St->getChain());
14675     else if (St->getValue().hasOneUse() &&
14676              ChainVal->getOpcode() == ISD::TokenFactor) {
14677       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14678         if (ChainVal->getOperand(i).getNode() == LdVal) {
14679           TokenFactorIndex = i;
14680           Ld = cast<LoadSDNode>(St->getValue());
14681         } else
14682           Ops.push_back(ChainVal->getOperand(i));
14683       }
14684     }
14685
14686     if (!Ld || !ISD::isNormalLoad(Ld))
14687       return SDValue();
14688
14689     // If this is not the MMX case, i.e. we are just turning i64 load/store
14690     // into f64 load/store, avoid the transformation if there are multiple
14691     // uses of the loaded value.
14692     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14693       return SDValue();
14694
14695     DebugLoc LdDL = Ld->getDebugLoc();
14696     DebugLoc StDL = N->getDebugLoc();
14697     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14698     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14699     // pair instead.
14700     if (Subtarget->is64Bit() || F64IsLegal) {
14701       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14702       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14703                                   Ld->getPointerInfo(), Ld->isVolatile(),
14704                                   Ld->isNonTemporal(), Ld->isInvariant(),
14705                                   Ld->getAlignment());
14706       SDValue NewChain = NewLd.getValue(1);
14707       if (TokenFactorIndex != -1) {
14708         Ops.push_back(NewChain);
14709         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14710                                Ops.size());
14711       }
14712       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14713                           St->getPointerInfo(),
14714                           St->isVolatile(), St->isNonTemporal(),
14715                           St->getAlignment());
14716     }
14717
14718     // Otherwise, lower to two pairs of 32-bit loads / stores.
14719     SDValue LoAddr = Ld->getBasePtr();
14720     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14721                                  DAG.getConstant(4, MVT::i32));
14722
14723     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14724                                Ld->getPointerInfo(),
14725                                Ld->isVolatile(), Ld->isNonTemporal(),
14726                                Ld->isInvariant(), Ld->getAlignment());
14727     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14728                                Ld->getPointerInfo().getWithOffset(4),
14729                                Ld->isVolatile(), Ld->isNonTemporal(),
14730                                Ld->isInvariant(),
14731                                MinAlign(Ld->getAlignment(), 4));
14732
14733     SDValue NewChain = LoLd.getValue(1);
14734     if (TokenFactorIndex != -1) {
14735       Ops.push_back(LoLd);
14736       Ops.push_back(HiLd);
14737       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14738                              Ops.size());
14739     }
14740
14741     LoAddr = St->getBasePtr();
14742     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14743                          DAG.getConstant(4, MVT::i32));
14744
14745     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14746                                 St->getPointerInfo(),
14747                                 St->isVolatile(), St->isNonTemporal(),
14748                                 St->getAlignment());
14749     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14750                                 St->getPointerInfo().getWithOffset(4),
14751                                 St->isVolatile(),
14752                                 St->isNonTemporal(),
14753                                 MinAlign(St->getAlignment(), 4));
14754     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14755   }
14756   return SDValue();
14757 }
14758
14759 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14760 /// and return the operands for the horizontal operation in LHS and RHS.  A
14761 /// horizontal operation performs the binary operation on successive elements
14762 /// of its first operand, then on successive elements of its second operand,
14763 /// returning the resulting values in a vector.  For example, if
14764 ///   A = < float a0, float a1, float a2, float a3 >
14765 /// and
14766 ///   B = < float b0, float b1, float b2, float b3 >
14767 /// then the result of doing a horizontal operation on A and B is
14768 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14769 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14770 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14771 /// set to A, RHS to B, and the routine returns 'true'.
14772 /// Note that the binary operation should have the property that if one of the
14773 /// operands is UNDEF then the result is UNDEF.
14774 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14775   // Look for the following pattern: if
14776   //   A = < float a0, float a1, float a2, float a3 >
14777   //   B = < float b0, float b1, float b2, float b3 >
14778   // and
14779   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14780   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14781   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14782   // which is A horizontal-op B.
14783
14784   // At least one of the operands should be a vector shuffle.
14785   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14786       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14787     return false;
14788
14789   EVT VT = LHS.getValueType();
14790
14791   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14792          "Unsupported vector type for horizontal add/sub");
14793
14794   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14795   // operate independently on 128-bit lanes.
14796   unsigned NumElts = VT.getVectorNumElements();
14797   unsigned NumLanes = VT.getSizeInBits()/128;
14798   unsigned NumLaneElts = NumElts / NumLanes;
14799   assert((NumLaneElts % 2 == 0) &&
14800          "Vector type should have an even number of elements in each lane");
14801   unsigned HalfLaneElts = NumLaneElts/2;
14802
14803   // View LHS in the form
14804   //   LHS = VECTOR_SHUFFLE A, B, LMask
14805   // If LHS is not a shuffle then pretend it is the shuffle
14806   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14807   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14808   // type VT.
14809   SDValue A, B;
14810   SmallVector<int, 16> LMask(NumElts);
14811   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14812     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14813       A = LHS.getOperand(0);
14814     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14815       B = LHS.getOperand(1);
14816     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
14817     std::copy(Mask.begin(), Mask.end(), LMask.begin());
14818   } else {
14819     if (LHS.getOpcode() != ISD::UNDEF)
14820       A = LHS;
14821     for (unsigned i = 0; i != NumElts; ++i)
14822       LMask[i] = i;
14823   }
14824
14825   // Likewise, view RHS in the form
14826   //   RHS = VECTOR_SHUFFLE C, D, RMask
14827   SDValue C, D;
14828   SmallVector<int, 16> RMask(NumElts);
14829   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14830     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14831       C = RHS.getOperand(0);
14832     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14833       D = RHS.getOperand(1);
14834     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
14835     std::copy(Mask.begin(), Mask.end(), RMask.begin());
14836   } else {
14837     if (RHS.getOpcode() != ISD::UNDEF)
14838       C = RHS;
14839     for (unsigned i = 0; i != NumElts; ++i)
14840       RMask[i] = i;
14841   }
14842
14843   // Check that the shuffles are both shuffling the same vectors.
14844   if (!(A == C && B == D) && !(A == D && B == C))
14845     return false;
14846
14847   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14848   if (!A.getNode() && !B.getNode())
14849     return false;
14850
14851   // If A and B occur in reverse order in RHS, then "swap" them (which means
14852   // rewriting the mask).
14853   if (A != C)
14854     CommuteVectorShuffleMask(RMask, NumElts);
14855
14856   // At this point LHS and RHS are equivalent to
14857   //   LHS = VECTOR_SHUFFLE A, B, LMask
14858   //   RHS = VECTOR_SHUFFLE A, B, RMask
14859   // Check that the masks correspond to performing a horizontal operation.
14860   for (unsigned i = 0; i != NumElts; ++i) {
14861     int LIdx = LMask[i], RIdx = RMask[i];
14862
14863     // Ignore any UNDEF components.
14864     if (LIdx < 0 || RIdx < 0 ||
14865         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14866         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14867       continue;
14868
14869     // Check that successive elements are being operated on.  If not, this is
14870     // not a horizontal operation.
14871     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14872     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14873     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14874     if (!(LIdx == Index && RIdx == Index + 1) &&
14875         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14876       return false;
14877   }
14878
14879   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14880   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14881   return true;
14882 }
14883
14884 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14885 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14886                                   const X86Subtarget *Subtarget) {
14887   EVT VT = N->getValueType(0);
14888   SDValue LHS = N->getOperand(0);
14889   SDValue RHS = N->getOperand(1);
14890
14891   // Try to synthesize horizontal adds from adds of shuffles.
14892   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14893        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14894       isHorizontalBinOp(LHS, RHS, true))
14895     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14896   return SDValue();
14897 }
14898
14899 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14900 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14901                                   const X86Subtarget *Subtarget) {
14902   EVT VT = N->getValueType(0);
14903   SDValue LHS = N->getOperand(0);
14904   SDValue RHS = N->getOperand(1);
14905
14906   // Try to synthesize horizontal subs from subs of shuffles.
14907   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14908        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14909       isHorizontalBinOp(LHS, RHS, false))
14910     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14911   return SDValue();
14912 }
14913
14914 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14915 /// X86ISD::FXOR nodes.
14916 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14917   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14918   // F[X]OR(0.0, x) -> x
14919   // F[X]OR(x, 0.0) -> x
14920   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14921     if (C->getValueAPF().isPosZero())
14922       return N->getOperand(1);
14923   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14924     if (C->getValueAPF().isPosZero())
14925       return N->getOperand(0);
14926   return SDValue();
14927 }
14928
14929 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14930 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14931   // FAND(0.0, x) -> 0.0
14932   // FAND(x, 0.0) -> 0.0
14933   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14934     if (C->getValueAPF().isPosZero())
14935       return N->getOperand(0);
14936   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14937     if (C->getValueAPF().isPosZero())
14938       return N->getOperand(1);
14939   return SDValue();
14940 }
14941
14942 static SDValue PerformBTCombine(SDNode *N,
14943                                 SelectionDAG &DAG,
14944                                 TargetLowering::DAGCombinerInfo &DCI) {
14945   // BT ignores high bits in the bit index operand.
14946   SDValue Op1 = N->getOperand(1);
14947   if (Op1.hasOneUse()) {
14948     unsigned BitWidth = Op1.getValueSizeInBits();
14949     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14950     APInt KnownZero, KnownOne;
14951     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14952                                           !DCI.isBeforeLegalizeOps());
14953     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14954     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14955         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14956       DCI.CommitTargetLoweringOpt(TLO);
14957   }
14958   return SDValue();
14959 }
14960
14961 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14962   SDValue Op = N->getOperand(0);
14963   if (Op.getOpcode() == ISD::BITCAST)
14964     Op = Op.getOperand(0);
14965   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14966   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14967       VT.getVectorElementType().getSizeInBits() ==
14968       OpVT.getVectorElementType().getSizeInBits()) {
14969     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14970   }
14971   return SDValue();
14972 }
14973
14974 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
14975                                   TargetLowering::DAGCombinerInfo &DCI,
14976                                   const X86Subtarget *Subtarget) {
14977   if (!DCI.isBeforeLegalizeOps())
14978     return SDValue();
14979
14980   if (!Subtarget->hasAVX())
14981     return SDValue();
14982
14983   EVT VT = N->getValueType(0);
14984   SDValue Op = N->getOperand(0);
14985   EVT OpVT = Op.getValueType();
14986   DebugLoc dl = N->getDebugLoc();
14987
14988   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
14989       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
14990
14991     if (Subtarget->hasAVX2())
14992       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
14993
14994     // Optimize vectors in AVX mode
14995     // Sign extend  v8i16 to v8i32 and
14996     //              v4i32 to v4i64
14997     //
14998     // Divide input vector into two parts
14999     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15000     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15001     // concat the vectors to original VT
15002
15003     unsigned NumElems = OpVT.getVectorNumElements();
15004     SmallVector<int,8> ShufMask1(NumElems, -1);
15005     for (unsigned i = 0; i != NumElems/2; ++i)
15006       ShufMask1[i] = i;
15007
15008     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15009                                         &ShufMask1[0]);
15010
15011     SmallVector<int,8> ShufMask2(NumElems, -1);
15012     for (unsigned i = 0; i != NumElems/2; ++i)
15013       ShufMask2[i] = i + NumElems/2;
15014
15015     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15016                                         &ShufMask2[0]);
15017
15018     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15019                                   VT.getVectorNumElements()/2);
15020
15021     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15022     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15023
15024     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15025   }
15026   return SDValue();
15027 }
15028
15029 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15030                                   TargetLowering::DAGCombinerInfo &DCI,
15031                                   const X86Subtarget *Subtarget) {
15032   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15033   //           (and (i32 x86isd::setcc_carry), 1)
15034   // This eliminates the zext. This transformation is necessary because
15035   // ISD::SETCC is always legalized to i8.
15036   DebugLoc dl = N->getDebugLoc();
15037   SDValue N0 = N->getOperand(0);
15038   EVT VT = N->getValueType(0);
15039   EVT OpVT = N0.getValueType();
15040
15041   if (N0.getOpcode() == ISD::AND &&
15042       N0.hasOneUse() &&
15043       N0.getOperand(0).hasOneUse()) {
15044     SDValue N00 = N0.getOperand(0);
15045     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15046       return SDValue();
15047     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15048     if (!C || C->getZExtValue() != 1)
15049       return SDValue();
15050     return DAG.getNode(ISD::AND, dl, VT,
15051                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15052                                    N00.getOperand(0), N00.getOperand(1)),
15053                        DAG.getConstant(1, VT));
15054   }
15055
15056   // Optimize vectors in AVX mode:
15057   //
15058   //   v8i16 -> v8i32
15059   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15060   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15061   //   Concat upper and lower parts.
15062   //
15063   //   v4i32 -> v4i64
15064   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15065   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15066   //   Concat upper and lower parts.
15067   //
15068   if (!DCI.isBeforeLegalizeOps())
15069     return SDValue();
15070
15071   if (!Subtarget->hasAVX())
15072     return SDValue();
15073
15074   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15075       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15076
15077     if (Subtarget->hasAVX2())
15078       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15079
15080     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15081     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15082     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15083
15084     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15085                                VT.getVectorNumElements()/2);
15086
15087     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15088     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15089
15090     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15091   }
15092
15093   return SDValue();
15094 }
15095
15096 // Optimize x == -y --> x+y == 0
15097 //          x != -y --> x+y != 0
15098 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15099   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15100   SDValue LHS = N->getOperand(0);
15101   SDValue RHS = N->getOperand(1); 
15102
15103   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15104     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15105       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15106         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15107                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15108         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15109                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15110       }
15111   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15112     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15113       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15114         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15115                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15116         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15117                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15118       }
15119   return SDValue();
15120 }
15121
15122 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15123 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15124   unsigned X86CC = N->getConstantOperandVal(0);
15125   SDValue EFLAG = N->getOperand(1);
15126   DebugLoc DL = N->getDebugLoc();
15127
15128   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15129   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15130   // cases.
15131   if (X86CC == X86::COND_B)
15132     return DAG.getNode(ISD::AND, DL, MVT::i8,
15133                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15134                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
15135                        DAG.getConstant(1, MVT::i8));
15136
15137   return SDValue();
15138 }
15139
15140 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15141   SDValue Op0 = N->getOperand(0);
15142   EVT InVT = Op0->getValueType(0);
15143
15144   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15145   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15146     DebugLoc dl = N->getDebugLoc();
15147     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15148     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15149     // Notice that we use SINT_TO_FP because we know that the high bits
15150     // are zero and SINT_TO_FP is better supported by the hardware.
15151     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15152   }
15153
15154   return SDValue();
15155 }
15156
15157 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15158                                         const X86TargetLowering *XTLI) {
15159   SDValue Op0 = N->getOperand(0);
15160   EVT InVT = Op0->getValueType(0);
15161
15162   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15163   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15164     DebugLoc dl = N->getDebugLoc();
15165     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15166     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15167     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15168   }
15169
15170   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15171   // a 32-bit target where SSE doesn't support i64->FP operations.
15172   if (Op0.getOpcode() == ISD::LOAD) {
15173     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15174     EVT VT = Ld->getValueType(0);
15175     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15176         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15177         !XTLI->getSubtarget()->is64Bit() &&
15178         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15179       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15180                                           Ld->getChain(), Op0, DAG);
15181       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15182       return FILDChain;
15183     }
15184   }
15185   return SDValue();
15186 }
15187
15188 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15189   EVT VT = N->getValueType(0);
15190
15191   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15192   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15193     DebugLoc dl = N->getDebugLoc();
15194     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15195     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15196     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15197   }
15198
15199   return SDValue();
15200 }
15201
15202 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15203 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15204                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15205   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15206   // the result is either zero or one (depending on the input carry bit).
15207   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15208   if (X86::isZeroNode(N->getOperand(0)) &&
15209       X86::isZeroNode(N->getOperand(1)) &&
15210       // We don't have a good way to replace an EFLAGS use, so only do this when
15211       // dead right now.
15212       SDValue(N, 1).use_empty()) {
15213     DebugLoc DL = N->getDebugLoc();
15214     EVT VT = N->getValueType(0);
15215     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15216     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15217                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15218                                            DAG.getConstant(X86::COND_B,MVT::i8),
15219                                            N->getOperand(2)),
15220                                DAG.getConstant(1, VT));
15221     return DCI.CombineTo(N, Res1, CarryOut);
15222   }
15223
15224   return SDValue();
15225 }
15226
15227 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15228 //      (add Y, (setne X, 0)) -> sbb -1, Y
15229 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15230 //      (sub (setne X, 0), Y) -> adc -1, Y
15231 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15232   DebugLoc DL = N->getDebugLoc();
15233
15234   // Look through ZExts.
15235   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15236   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15237     return SDValue();
15238
15239   SDValue SetCC = Ext.getOperand(0);
15240   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15241     return SDValue();
15242
15243   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15244   if (CC != X86::COND_E && CC != X86::COND_NE)
15245     return SDValue();
15246
15247   SDValue Cmp = SetCC.getOperand(1);
15248   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15249       !X86::isZeroNode(Cmp.getOperand(1)) ||
15250       !Cmp.getOperand(0).getValueType().isInteger())
15251     return SDValue();
15252
15253   SDValue CmpOp0 = Cmp.getOperand(0);
15254   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15255                                DAG.getConstant(1, CmpOp0.getValueType()));
15256
15257   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15258   if (CC == X86::COND_NE)
15259     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15260                        DL, OtherVal.getValueType(), OtherVal,
15261                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15262   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15263                      DL, OtherVal.getValueType(), OtherVal,
15264                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15265 }
15266
15267 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15268 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15269                                  const X86Subtarget *Subtarget) {
15270   EVT VT = N->getValueType(0);
15271   SDValue Op0 = N->getOperand(0);
15272   SDValue Op1 = N->getOperand(1);
15273
15274   // Try to synthesize horizontal adds from adds of shuffles.
15275   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15276        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15277       isHorizontalBinOp(Op0, Op1, true))
15278     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15279
15280   return OptimizeConditionalInDecrement(N, DAG);
15281 }
15282
15283 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15284                                  const X86Subtarget *Subtarget) {
15285   SDValue Op0 = N->getOperand(0);
15286   SDValue Op1 = N->getOperand(1);
15287
15288   // X86 can't encode an immediate LHS of a sub. See if we can push the
15289   // negation into a preceding instruction.
15290   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15291     // If the RHS of the sub is a XOR with one use and a constant, invert the
15292     // immediate. Then add one to the LHS of the sub so we can turn
15293     // X-Y -> X+~Y+1, saving one register.
15294     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15295         isa<ConstantSDNode>(Op1.getOperand(1))) {
15296       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15297       EVT VT = Op0.getValueType();
15298       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15299                                    Op1.getOperand(0),
15300                                    DAG.getConstant(~XorC, VT));
15301       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15302                          DAG.getConstant(C->getAPIntValue()+1, VT));
15303     }
15304   }
15305
15306   // Try to synthesize horizontal adds from adds of shuffles.
15307   EVT VT = N->getValueType(0);
15308   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15309        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15310       isHorizontalBinOp(Op0, Op1, true))
15311     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15312
15313   return OptimizeConditionalInDecrement(N, DAG);
15314 }
15315
15316 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15317                                              DAGCombinerInfo &DCI) const {
15318   SelectionDAG &DAG = DCI.DAG;
15319   switch (N->getOpcode()) {
15320   default: break;
15321   case ISD::EXTRACT_VECTOR_ELT:
15322     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15323   case ISD::VSELECT:
15324   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15325   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
15326   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
15327   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
15328   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
15329   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
15330   case ISD::SHL:
15331   case ISD::SRA:
15332   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
15333   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
15334   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
15335   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
15336   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
15337   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
15338   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
15339   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
15340   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
15341   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
15342   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
15343   case X86ISD::FXOR:
15344   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
15345   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
15346   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
15347   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
15348   case ISD::ANY_EXTEND:
15349   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
15350   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
15351   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
15352   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
15353   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
15354   case X86ISD::SHUFP:       // Handle all target specific shuffles
15355   case X86ISD::PALIGN:
15356   case X86ISD::UNPCKH:
15357   case X86ISD::UNPCKL:
15358   case X86ISD::MOVHLPS:
15359   case X86ISD::MOVLHPS:
15360   case X86ISD::PSHUFD:
15361   case X86ISD::PSHUFHW:
15362   case X86ISD::PSHUFLW:
15363   case X86ISD::MOVSS:
15364   case X86ISD::MOVSD:
15365   case X86ISD::VPERMILP:
15366   case X86ISD::VPERM2X128:
15367   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
15368   }
15369
15370   return SDValue();
15371 }
15372
15373 /// isTypeDesirableForOp - Return true if the target has native support for
15374 /// the specified value type and it is 'desirable' to use the type for the
15375 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
15376 /// instruction encodings are longer and some i16 instructions are slow.
15377 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
15378   if (!isTypeLegal(VT))
15379     return false;
15380   if (VT != MVT::i16)
15381     return true;
15382
15383   switch (Opc) {
15384   default:
15385     return true;
15386   case ISD::LOAD:
15387   case ISD::SIGN_EXTEND:
15388   case ISD::ZERO_EXTEND:
15389   case ISD::ANY_EXTEND:
15390   case ISD::SHL:
15391   case ISD::SRL:
15392   case ISD::SUB:
15393   case ISD::ADD:
15394   case ISD::MUL:
15395   case ISD::AND:
15396   case ISD::OR:
15397   case ISD::XOR:
15398     return false;
15399   }
15400 }
15401
15402 /// IsDesirableToPromoteOp - This method query the target whether it is
15403 /// beneficial for dag combiner to promote the specified node. If true, it
15404 /// should return the desired promotion type by reference.
15405 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
15406   EVT VT = Op.getValueType();
15407   if (VT != MVT::i16)
15408     return false;
15409
15410   bool Promote = false;
15411   bool Commute = false;
15412   switch (Op.getOpcode()) {
15413   default: break;
15414   case ISD::LOAD: {
15415     LoadSDNode *LD = cast<LoadSDNode>(Op);
15416     // If the non-extending load has a single use and it's not live out, then it
15417     // might be folded.
15418     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
15419                                                      Op.hasOneUse()*/) {
15420       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15421              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
15422         // The only case where we'd want to promote LOAD (rather then it being
15423         // promoted as an operand is when it's only use is liveout.
15424         if (UI->getOpcode() != ISD::CopyToReg)
15425           return false;
15426       }
15427     }
15428     Promote = true;
15429     break;
15430   }
15431   case ISD::SIGN_EXTEND:
15432   case ISD::ZERO_EXTEND:
15433   case ISD::ANY_EXTEND:
15434     Promote = true;
15435     break;
15436   case ISD::SHL:
15437   case ISD::SRL: {
15438     SDValue N0 = Op.getOperand(0);
15439     // Look out for (store (shl (load), x)).
15440     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15441       return false;
15442     Promote = true;
15443     break;
15444   }
15445   case ISD::ADD:
15446   case ISD::MUL:
15447   case ISD::AND:
15448   case ISD::OR:
15449   case ISD::XOR:
15450     Commute = true;
15451     // fallthrough
15452   case ISD::SUB: {
15453     SDValue N0 = Op.getOperand(0);
15454     SDValue N1 = Op.getOperand(1);
15455     if (!Commute && MayFoldLoad(N1))
15456       return false;
15457     // Avoid disabling potential load folding opportunities.
15458     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15459       return false;
15460     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15461       return false;
15462     Promote = true;
15463   }
15464   }
15465
15466   PVT = MVT::i32;
15467   return Promote;
15468 }
15469
15470 //===----------------------------------------------------------------------===//
15471 //                           X86 Inline Assembly Support
15472 //===----------------------------------------------------------------------===//
15473
15474 namespace {
15475   // Helper to match a string separated by whitespace.
15476   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15477     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15478
15479     for (unsigned i = 0, e = args.size(); i != e; ++i) {
15480       StringRef piece(*args[i]);
15481       if (!s.startswith(piece)) // Check if the piece matches.
15482         return false;
15483
15484       s = s.substr(piece.size());
15485       StringRef::size_type pos = s.find_first_not_of(" \t");
15486       if (pos == 0) // We matched a prefix.
15487         return false;
15488
15489       s = s.substr(pos);
15490     }
15491
15492     return s.empty();
15493   }
15494   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15495 }
15496
15497 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15498   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15499
15500   std::string AsmStr = IA->getAsmString();
15501
15502   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15503   if (!Ty || Ty->getBitWidth() % 16 != 0)
15504     return false;
15505
15506   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15507   SmallVector<StringRef, 4> AsmPieces;
15508   SplitString(AsmStr, AsmPieces, ";\n");
15509
15510   switch (AsmPieces.size()) {
15511   default: return false;
15512   case 1:
15513     // FIXME: this should verify that we are targeting a 486 or better.  If not,
15514     // we will turn this bswap into something that will be lowered to logical
15515     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
15516     // lower so don't worry about this.
15517     // bswap $0
15518     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15519         matchAsm(AsmPieces[0], "bswapl", "$0") ||
15520         matchAsm(AsmPieces[0], "bswapq", "$0") ||
15521         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15522         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15523         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15524       // No need to check constraints, nothing other than the equivalent of
15525       // "=r,0" would be valid here.
15526       return IntrinsicLowering::LowerToByteSwap(CI);
15527     }
15528
15529     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15530     if (CI->getType()->isIntegerTy(16) &&
15531         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15532         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15533          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15534       AsmPieces.clear();
15535       const std::string &ConstraintsStr = IA->getConstraintString();
15536       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15537       std::sort(AsmPieces.begin(), AsmPieces.end());
15538       if (AsmPieces.size() == 4 &&
15539           AsmPieces[0] == "~{cc}" &&
15540           AsmPieces[1] == "~{dirflag}" &&
15541           AsmPieces[2] == "~{flags}" &&
15542           AsmPieces[3] == "~{fpsr}")
15543       return IntrinsicLowering::LowerToByteSwap(CI);
15544     }
15545     break;
15546   case 3:
15547     if (CI->getType()->isIntegerTy(32) &&
15548         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15549         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15550         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15551         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15552       AsmPieces.clear();
15553       const std::string &ConstraintsStr = IA->getConstraintString();
15554       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15555       std::sort(AsmPieces.begin(), AsmPieces.end());
15556       if (AsmPieces.size() == 4 &&
15557           AsmPieces[0] == "~{cc}" &&
15558           AsmPieces[1] == "~{dirflag}" &&
15559           AsmPieces[2] == "~{flags}" &&
15560           AsmPieces[3] == "~{fpsr}")
15561         return IntrinsicLowering::LowerToByteSwap(CI);
15562     }
15563
15564     if (CI->getType()->isIntegerTy(64)) {
15565       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15566       if (Constraints.size() >= 2 &&
15567           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15568           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15569         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15570         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15571             matchAsm(AsmPieces[1], "bswap", "%edx") &&
15572             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15573           return IntrinsicLowering::LowerToByteSwap(CI);
15574       }
15575     }
15576     break;
15577   }
15578   return false;
15579 }
15580
15581
15582
15583 /// getConstraintType - Given a constraint letter, return the type of
15584 /// constraint it is for this target.
15585 X86TargetLowering::ConstraintType
15586 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15587   if (Constraint.size() == 1) {
15588     switch (Constraint[0]) {
15589     case 'R':
15590     case 'q':
15591     case 'Q':
15592     case 'f':
15593     case 't':
15594     case 'u':
15595     case 'y':
15596     case 'x':
15597     case 'Y':
15598     case 'l':
15599       return C_RegisterClass;
15600     case 'a':
15601     case 'b':
15602     case 'c':
15603     case 'd':
15604     case 'S':
15605     case 'D':
15606     case 'A':
15607       return C_Register;
15608     case 'I':
15609     case 'J':
15610     case 'K':
15611     case 'L':
15612     case 'M':
15613     case 'N':
15614     case 'G':
15615     case 'C':
15616     case 'e':
15617     case 'Z':
15618       return C_Other;
15619     default:
15620       break;
15621     }
15622   }
15623   return TargetLowering::getConstraintType(Constraint);
15624 }
15625
15626 /// Examine constraint type and operand type and determine a weight value.
15627 /// This object must already have been set up with the operand type
15628 /// and the current alternative constraint selected.
15629 TargetLowering::ConstraintWeight
15630   X86TargetLowering::getSingleConstraintMatchWeight(
15631     AsmOperandInfo &info, const char *constraint) const {
15632   ConstraintWeight weight = CW_Invalid;
15633   Value *CallOperandVal = info.CallOperandVal;
15634     // If we don't have a value, we can't do a match,
15635     // but allow it at the lowest weight.
15636   if (CallOperandVal == NULL)
15637     return CW_Default;
15638   Type *type = CallOperandVal->getType();
15639   // Look at the constraint type.
15640   switch (*constraint) {
15641   default:
15642     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15643   case 'R':
15644   case 'q':
15645   case 'Q':
15646   case 'a':
15647   case 'b':
15648   case 'c':
15649   case 'd':
15650   case 'S':
15651   case 'D':
15652   case 'A':
15653     if (CallOperandVal->getType()->isIntegerTy())
15654       weight = CW_SpecificReg;
15655     break;
15656   case 'f':
15657   case 't':
15658   case 'u':
15659       if (type->isFloatingPointTy())
15660         weight = CW_SpecificReg;
15661       break;
15662   case 'y':
15663       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15664         weight = CW_SpecificReg;
15665       break;
15666   case 'x':
15667   case 'Y':
15668     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15669         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15670       weight = CW_Register;
15671     break;
15672   case 'I':
15673     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15674       if (C->getZExtValue() <= 31)
15675         weight = CW_Constant;
15676     }
15677     break;
15678   case 'J':
15679     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15680       if (C->getZExtValue() <= 63)
15681         weight = CW_Constant;
15682     }
15683     break;
15684   case 'K':
15685     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15686       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15687         weight = CW_Constant;
15688     }
15689     break;
15690   case 'L':
15691     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15692       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15693         weight = CW_Constant;
15694     }
15695     break;
15696   case 'M':
15697     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15698       if (C->getZExtValue() <= 3)
15699         weight = CW_Constant;
15700     }
15701     break;
15702   case 'N':
15703     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15704       if (C->getZExtValue() <= 0xff)
15705         weight = CW_Constant;
15706     }
15707     break;
15708   case 'G':
15709   case 'C':
15710     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15711       weight = CW_Constant;
15712     }
15713     break;
15714   case 'e':
15715     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15716       if ((C->getSExtValue() >= -0x80000000LL) &&
15717           (C->getSExtValue() <= 0x7fffffffLL))
15718         weight = CW_Constant;
15719     }
15720     break;
15721   case 'Z':
15722     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15723       if (C->getZExtValue() <= 0xffffffff)
15724         weight = CW_Constant;
15725     }
15726     break;
15727   }
15728   return weight;
15729 }
15730
15731 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15732 /// with another that has more specific requirements based on the type of the
15733 /// corresponding operand.
15734 const char *X86TargetLowering::
15735 LowerXConstraint(EVT ConstraintVT) const {
15736   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15737   // 'f' like normal targets.
15738   if (ConstraintVT.isFloatingPoint()) {
15739     if (Subtarget->hasSSE2())
15740       return "Y";
15741     if (Subtarget->hasSSE1())
15742       return "x";
15743   }
15744
15745   return TargetLowering::LowerXConstraint(ConstraintVT);
15746 }
15747
15748 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15749 /// vector.  If it is invalid, don't add anything to Ops.
15750 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15751                                                      std::string &Constraint,
15752                                                      std::vector<SDValue>&Ops,
15753                                                      SelectionDAG &DAG) const {
15754   SDValue Result(0, 0);
15755
15756   // Only support length 1 constraints for now.
15757   if (Constraint.length() > 1) return;
15758
15759   char ConstraintLetter = Constraint[0];
15760   switch (ConstraintLetter) {
15761   default: break;
15762   case 'I':
15763     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15764       if (C->getZExtValue() <= 31) {
15765         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15766         break;
15767       }
15768     }
15769     return;
15770   case 'J':
15771     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15772       if (C->getZExtValue() <= 63) {
15773         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15774         break;
15775       }
15776     }
15777     return;
15778   case 'K':
15779     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15780       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15781         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15782         break;
15783       }
15784     }
15785     return;
15786   case 'N':
15787     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15788       if (C->getZExtValue() <= 255) {
15789         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15790         break;
15791       }
15792     }
15793     return;
15794   case 'e': {
15795     // 32-bit signed value
15796     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15797       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15798                                            C->getSExtValue())) {
15799         // Widen to 64 bits here to get it sign extended.
15800         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15801         break;
15802       }
15803     // FIXME gcc accepts some relocatable values here too, but only in certain
15804     // memory models; it's complicated.
15805     }
15806     return;
15807   }
15808   case 'Z': {
15809     // 32-bit unsigned value
15810     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15811       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15812                                            C->getZExtValue())) {
15813         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15814         break;
15815       }
15816     }
15817     // FIXME gcc accepts some relocatable values here too, but only in certain
15818     // memory models; it's complicated.
15819     return;
15820   }
15821   case 'i': {
15822     // Literal immediates are always ok.
15823     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15824       // Widen to 64 bits here to get it sign extended.
15825       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15826       break;
15827     }
15828
15829     // In any sort of PIC mode addresses need to be computed at runtime by
15830     // adding in a register or some sort of table lookup.  These can't
15831     // be used as immediates.
15832     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15833       return;
15834
15835     // If we are in non-pic codegen mode, we allow the address of a global (with
15836     // an optional displacement) to be used with 'i'.
15837     GlobalAddressSDNode *GA = 0;
15838     int64_t Offset = 0;
15839
15840     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15841     while (1) {
15842       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15843         Offset += GA->getOffset();
15844         break;
15845       } else if (Op.getOpcode() == ISD::ADD) {
15846         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15847           Offset += C->getZExtValue();
15848           Op = Op.getOperand(0);
15849           continue;
15850         }
15851       } else if (Op.getOpcode() == ISD::SUB) {
15852         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15853           Offset += -C->getZExtValue();
15854           Op = Op.getOperand(0);
15855           continue;
15856         }
15857       }
15858
15859       // Otherwise, this isn't something we can handle, reject it.
15860       return;
15861     }
15862
15863     const GlobalValue *GV = GA->getGlobal();
15864     // If we require an extra load to get this address, as in PIC mode, we
15865     // can't accept it.
15866     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15867                                                         getTargetMachine())))
15868       return;
15869
15870     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15871                                         GA->getValueType(0), Offset);
15872     break;
15873   }
15874   }
15875
15876   if (Result.getNode()) {
15877     Ops.push_back(Result);
15878     return;
15879   }
15880   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15881 }
15882
15883 std::pair<unsigned, const TargetRegisterClass*>
15884 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15885                                                 EVT VT) const {
15886   // First, see if this is a constraint that directly corresponds to an LLVM
15887   // register class.
15888   if (Constraint.size() == 1) {
15889     // GCC Constraint Letters
15890     switch (Constraint[0]) {
15891     default: break;
15892       // TODO: Slight differences here in allocation order and leaving
15893       // RIP in the class. Do they matter any more here than they do
15894       // in the normal allocation?
15895     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15896       if (Subtarget->is64Bit()) {
15897         if (VT == MVT::i32 || VT == MVT::f32)
15898           return std::make_pair(0U, &X86::GR32RegClass);
15899         if (VT == MVT::i16)
15900           return std::make_pair(0U, &X86::GR16RegClass);
15901         if (VT == MVT::i8 || VT == MVT::i1)
15902           return std::make_pair(0U, &X86::GR8RegClass);
15903         if (VT == MVT::i64 || VT == MVT::f64)
15904           return std::make_pair(0U, &X86::GR64RegClass);
15905         break;
15906       }
15907       // 32-bit fallthrough
15908     case 'Q':   // Q_REGS
15909       if (VT == MVT::i32 || VT == MVT::f32)
15910         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
15911       if (VT == MVT::i16)
15912         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
15913       if (VT == MVT::i8 || VT == MVT::i1)
15914         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
15915       if (VT == MVT::i64)
15916         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
15917       break;
15918     case 'r':   // GENERAL_REGS
15919     case 'l':   // INDEX_REGS
15920       if (VT == MVT::i8 || VT == MVT::i1)
15921         return std::make_pair(0U, &X86::GR8RegClass);
15922       if (VT == MVT::i16)
15923         return std::make_pair(0U, &X86::GR16RegClass);
15924       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15925         return std::make_pair(0U, &X86::GR32RegClass);
15926       return std::make_pair(0U, &X86::GR64RegClass);
15927     case 'R':   // LEGACY_REGS
15928       if (VT == MVT::i8 || VT == MVT::i1)
15929         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
15930       if (VT == MVT::i16)
15931         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
15932       if (VT == MVT::i32 || !Subtarget->is64Bit())
15933         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
15934       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
15935     case 'f':  // FP Stack registers.
15936       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15937       // value to the correct fpstack register class.
15938       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15939         return std::make_pair(0U, &X86::RFP32RegClass);
15940       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15941         return std::make_pair(0U, &X86::RFP64RegClass);
15942       return std::make_pair(0U, &X86::RFP80RegClass);
15943     case 'y':   // MMX_REGS if MMX allowed.
15944       if (!Subtarget->hasMMX()) break;
15945       return std::make_pair(0U, &X86::VR64RegClass);
15946     case 'Y':   // SSE_REGS if SSE2 allowed
15947       if (!Subtarget->hasSSE2()) break;
15948       // FALL THROUGH.
15949     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
15950       if (!Subtarget->hasSSE1()) break;
15951
15952       switch (VT.getSimpleVT().SimpleTy) {
15953       default: break;
15954       // Scalar SSE types.
15955       case MVT::f32:
15956       case MVT::i32:
15957         return std::make_pair(0U, &X86::FR32RegClass);
15958       case MVT::f64:
15959       case MVT::i64:
15960         return std::make_pair(0U, &X86::FR64RegClass);
15961       // Vector types.
15962       case MVT::v16i8:
15963       case MVT::v8i16:
15964       case MVT::v4i32:
15965       case MVT::v2i64:
15966       case MVT::v4f32:
15967       case MVT::v2f64:
15968         return std::make_pair(0U, &X86::VR128RegClass);
15969       // AVX types.
15970       case MVT::v32i8:
15971       case MVT::v16i16:
15972       case MVT::v8i32:
15973       case MVT::v4i64:
15974       case MVT::v8f32:
15975       case MVT::v4f64:
15976         return std::make_pair(0U, &X86::VR256RegClass);
15977       }
15978       break;
15979     }
15980   }
15981
15982   // Use the default implementation in TargetLowering to convert the register
15983   // constraint into a member of a register class.
15984   std::pair<unsigned, const TargetRegisterClass*> Res;
15985   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15986
15987   // Not found as a standard register?
15988   if (Res.second == 0) {
15989     // Map st(0) -> st(7) -> ST0
15990     if (Constraint.size() == 7 && Constraint[0] == '{' &&
15991         tolower(Constraint[1]) == 's' &&
15992         tolower(Constraint[2]) == 't' &&
15993         Constraint[3] == '(' &&
15994         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15995         Constraint[5] == ')' &&
15996         Constraint[6] == '}') {
15997
15998       Res.first = X86::ST0+Constraint[4]-'0';
15999       Res.second = &X86::RFP80RegClass;
16000       return Res;
16001     }
16002
16003     // GCC allows "st(0)" to be called just plain "st".
16004     if (StringRef("{st}").equals_lower(Constraint)) {
16005       Res.first = X86::ST0;
16006       Res.second = &X86::RFP80RegClass;
16007       return Res;
16008     }
16009
16010     // flags -> EFLAGS
16011     if (StringRef("{flags}").equals_lower(Constraint)) {
16012       Res.first = X86::EFLAGS;
16013       Res.second = &X86::CCRRegClass;
16014       return Res;
16015     }
16016
16017     // 'A' means EAX + EDX.
16018     if (Constraint == "A") {
16019       Res.first = X86::EAX;
16020       Res.second = &X86::GR32_ADRegClass;
16021       return Res;
16022     }
16023     return Res;
16024   }
16025
16026   // Otherwise, check to see if this is a register class of the wrong value
16027   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16028   // turn into {ax},{dx}.
16029   if (Res.second->hasType(VT))
16030     return Res;   // Correct type already, nothing to do.
16031
16032   // All of the single-register GCC register classes map their values onto
16033   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16034   // really want an 8-bit or 32-bit register, map to the appropriate register
16035   // class and return the appropriate register.
16036   if (Res.second == &X86::GR16RegClass) {
16037     if (VT == MVT::i8) {
16038       unsigned DestReg = 0;
16039       switch (Res.first) {
16040       default: break;
16041       case X86::AX: DestReg = X86::AL; break;
16042       case X86::DX: DestReg = X86::DL; break;
16043       case X86::CX: DestReg = X86::CL; break;
16044       case X86::BX: DestReg = X86::BL; break;
16045       }
16046       if (DestReg) {
16047         Res.first = DestReg;
16048         Res.second = &X86::GR8RegClass;
16049       }
16050     } else if (VT == MVT::i32) {
16051       unsigned DestReg = 0;
16052       switch (Res.first) {
16053       default: break;
16054       case X86::AX: DestReg = X86::EAX; break;
16055       case X86::DX: DestReg = X86::EDX; break;
16056       case X86::CX: DestReg = X86::ECX; break;
16057       case X86::BX: DestReg = X86::EBX; break;
16058       case X86::SI: DestReg = X86::ESI; break;
16059       case X86::DI: DestReg = X86::EDI; break;
16060       case X86::BP: DestReg = X86::EBP; break;
16061       case X86::SP: DestReg = X86::ESP; break;
16062       }
16063       if (DestReg) {
16064         Res.first = DestReg;
16065         Res.second = &X86::GR32RegClass;
16066       }
16067     } else if (VT == MVT::i64) {
16068       unsigned DestReg = 0;
16069       switch (Res.first) {
16070       default: break;
16071       case X86::AX: DestReg = X86::RAX; break;
16072       case X86::DX: DestReg = X86::RDX; break;
16073       case X86::CX: DestReg = X86::RCX; break;
16074       case X86::BX: DestReg = X86::RBX; break;
16075       case X86::SI: DestReg = X86::RSI; break;
16076       case X86::DI: DestReg = X86::RDI; break;
16077       case X86::BP: DestReg = X86::RBP; break;
16078       case X86::SP: DestReg = X86::RSP; break;
16079       }
16080       if (DestReg) {
16081         Res.first = DestReg;
16082         Res.second = &X86::GR64RegClass;
16083       }
16084     }
16085   } else if (Res.second == &X86::FR32RegClass ||
16086              Res.second == &X86::FR64RegClass ||
16087              Res.second == &X86::VR128RegClass) {
16088     // Handle references to XMM physical registers that got mapped into the
16089     // wrong class.  This can happen with constraints like {xmm0} where the
16090     // target independent register mapper will just pick the first match it can
16091     // find, ignoring the required type.
16092
16093     if (VT == MVT::f32 || VT == MVT::i32)
16094       Res.second = &X86::FR32RegClass;
16095     else if (VT == MVT::f64 || VT == MVT::i64)
16096       Res.second = &X86::FR64RegClass;
16097     else if (X86::VR128RegClass.hasType(VT))
16098       Res.second = &X86::VR128RegClass;
16099     else if (X86::VR256RegClass.hasType(VT))
16100       Res.second = &X86::VR256RegClass;
16101   }
16102
16103   return Res;
16104 }