Use MVT.isXBitVector instead of EVT.isXBitVector when setting up operation actions...
[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 #include <cctype>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference.  Idx is an index in the 128 bits we
64 /// want.  It need not be aligned to a 128-bit bounday.  That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67                                    SelectionDAG &DAG, DebugLoc dl) {
68   EVT VT = Vec.getValueType();
69   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
70   EVT ElVT = VT.getVectorElementType();
71   unsigned Factor = VT.getSizeInBits()/128;
72   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                   VT.getVectorNumElements()/Factor);
74
75   // Extract from UNDEF is UNDEF.
76   if (Vec.getOpcode() == ISD::UNDEF)
77     return DAG.getUNDEF(ResultVT);
78
79   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80   // we can match to VEXTRACTF128.
81   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83   // This is the index of the first element of the 128-bit chunk
84   // we want.
85   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                                * ElemsPerChunk);
87
88   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
89   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
90                                VecIdx);
91
92   return Result;
93 }
94
95 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference.  Idx is an index in the 128 bits
98 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101                                   unsigned IdxVal, SelectionDAG &DAG,
102                                   DebugLoc dl) {
103   // Inserting UNDEF is Result
104   if (Vec.getOpcode() == ISD::UNDEF)
105     return Result;
106
107   EVT VT = Vec.getValueType();
108   assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
109
110   EVT ElVT = VT.getVectorElementType();
111   EVT ResultVT = Result.getValueType();
112
113   // Insert the relevant 128 bits.
114   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
115
116   // This is the index of the first element of the 128-bit chunk
117   // we want.
118   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
119                                * ElemsPerChunk);
120
121   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
122   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
123                      VecIdx);
124 }
125
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131                                    unsigned NumElems, SelectionDAG &DAG,
132                                    DebugLoc dl) {
133   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
135 }
136
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139   bool is64Bit = Subtarget->is64Bit();
140
141   if (Subtarget->isTargetEnvMacho()) {
142     if (is64Bit)
143       return new X86_64MachoTargetObjectFile();
144     return new TargetLoweringObjectFileMachO();
145   }
146
147   if (Subtarget->isTargetLinux())
148     return new X86LinuxTargetObjectFile();
149   if (Subtarget->isTargetELF())
150     return new TargetLoweringObjectFileELF();
151   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152     return new TargetLoweringObjectFileCOFF();
153   llvm_unreachable("unknown subtarget type");
154 }
155
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157   : TargetLowering(TM, createTLOF(TM)) {
158   Subtarget = &TM.getSubtarget<X86Subtarget>();
159   X86ScalarSSEf64 = Subtarget->hasSSE2();
160   X86ScalarSSEf32 = Subtarget->hasSSE1();
161   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
162
163   RegInfo = TM.getRegisterInfo();
164   TD = getTargetData();
165
166   // Set up the TargetLowering object.
167   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168
169   // X86 is weird, it always uses i8 for shift amounts and setcc results.
170   setBooleanContents(ZeroOrOneBooleanContent);
171   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174   // For 64-bit since we have so many registers use the ILP scheduler, for
175   // 32-bit code use the register pressure specific scheduling.
176   // For Atom, always use ILP scheduling.
177   if (Subtarget->isAtom())
178     setSchedulingPreference(Sched::ILP);
179   else if (Subtarget->is64Bit())
180     setSchedulingPreference(Sched::ILP);
181   else
182     setSchedulingPreference(Sched::RegPressure);
183   setStackPointerRegisterToSaveRestore(X86StackPtr);
184
185   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
186     // Setup Windows compiler runtime calls.
187     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
188     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
189     setLibcallName(RTLIB::SREM_I64, "_allrem");
190     setLibcallName(RTLIB::UREM_I64, "_aullrem");
191     setLibcallName(RTLIB::MUL_I64, "_allmul");
192     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
193     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
194     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
195     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
196     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
197
198     // The _ftol2 runtime function has an unusual calling conv, which
199     // is modeled by a special pseudo-instruction.
200     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
201     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
202     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
203     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
204   }
205
206   if (Subtarget->isTargetDarwin()) {
207     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
208     setUseUnderscoreSetJmp(false);
209     setUseUnderscoreLongJmp(false);
210   } else if (Subtarget->isTargetMingw()) {
211     // MS runtime is weird: it exports _setjmp, but longjmp!
212     setUseUnderscoreSetJmp(true);
213     setUseUnderscoreLongJmp(false);
214   } else {
215     setUseUnderscoreSetJmp(true);
216     setUseUnderscoreLongJmp(true);
217   }
218
219   // Set up the register classes.
220   addRegisterClass(MVT::i8, &X86::GR8RegClass);
221   addRegisterClass(MVT::i16, &X86::GR16RegClass);
222   addRegisterClass(MVT::i32, &X86::GR32RegClass);
223   if (Subtarget->is64Bit())
224     addRegisterClass(MVT::i64, &X86::GR64RegClass);
225
226   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
227
228   // We don't accept any truncstore of integer registers.
229   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
230   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
231   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
232   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
233   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
234   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
235
236   // SETOEQ and SETUNE require checking two conditions.
237   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
238   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
239   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
240   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
241   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
242   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
243
244   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
245   // operation.
246   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
247   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
248   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
249
250   if (Subtarget->is64Bit()) {
251     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
252     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
253   } else if (!TM.Options.UseSoftFloat) {
254     // We have an algorithm for SSE2->double, and we turn this into a
255     // 64-bit FILD followed by conditional FADD for other targets.
256     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
257     // We have an algorithm for SSE2, and we turn this into a 64-bit
258     // FILD for other targets.
259     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
260   }
261
262   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
263   // this operation.
264   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
265   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
266
267   if (!TM.Options.UseSoftFloat) {
268     // SSE has no i16 to fp conversion, only i32
269     if (X86ScalarSSEf32) {
270       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
271       // f32 and f64 cases are Legal, f80 case is not
272       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
273     } else {
274       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
275       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
276     }
277   } else {
278     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
279     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
280   }
281
282   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
283   // are Legal, f80 is custom lowered.
284   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
285   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
286
287   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
288   // this operation.
289   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
290   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
291
292   if (X86ScalarSSEf32) {
293     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
294     // f32 and f64 cases are Legal, f80 case is not
295     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
296   } else {
297     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
298     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
299   }
300
301   // Handle FP_TO_UINT by promoting the destination to a larger signed
302   // conversion.
303   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
304   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
305   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
306
307   if (Subtarget->is64Bit()) {
308     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
309     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
310   } else if (!TM.Options.UseSoftFloat) {
311     // Since AVX is a superset of SSE3, only check for SSE here.
312     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
313       // Expand FP_TO_UINT into a select.
314       // FIXME: We would like to use a Custom expander here eventually to do
315       // the optimal thing for SSE vs. the default expansion in the legalizer.
316       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
317     else
318       // With SSE3 we can use fisttpll to convert to a signed i64; without
319       // SSE, we're stuck with a fistpll.
320       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
321   }
322
323   if (isTargetFTOL()) {
324     // Use the _ftol2 runtime function, which has a pseudo-instruction
325     // to handle its weird calling convention.
326     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
327   }
328
329   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330   if (!X86ScalarSSEf64) {
331     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
332     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
333     if (Subtarget->is64Bit()) {
334       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
335       // Without SSE, i64->f64 goes through memory.
336       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
337     }
338   }
339
340   // Scalar integer divide and remainder are lowered to use operations that
341   // produce two results, to match the available instructions. This exposes
342   // the two-result form to trivial CSE, which is able to combine x/y and x%y
343   // into a single instruction.
344   //
345   // Scalar integer multiply-high is also lowered to use two-result
346   // operations, to match the available instructions. However, plain multiply
347   // (low) operations are left as Legal, as there are single-result
348   // instructions for this in x86. Using the two-result multiply instructions
349   // when both high and low results are needed must be arranged by dagcombine.
350   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
351     MVT VT = IntVTs[i];
352     setOperationAction(ISD::MULHS, VT, Expand);
353     setOperationAction(ISD::MULHU, VT, Expand);
354     setOperationAction(ISD::SDIV, VT, Expand);
355     setOperationAction(ISD::UDIV, VT, Expand);
356     setOperationAction(ISD::SREM, VT, Expand);
357     setOperationAction(ISD::UREM, VT, Expand);
358
359     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360     setOperationAction(ISD::ADDC, VT, Custom);
361     setOperationAction(ISD::ADDE, VT, Custom);
362     setOperationAction(ISD::SUBC, VT, Custom);
363     setOperationAction(ISD::SUBE, VT, Custom);
364   }
365
366   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
367   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
368   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
369   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
370   if (Subtarget->is64Bit())
371     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
374   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
375   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
376   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
378   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
379   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
380
381   // Promote the i8 variants and force them on up to i32 which has a shorter
382   // encoding.
383   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
384   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
385   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
386   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
387   if (Subtarget->hasBMI()) {
388     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
389     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
390     if (Subtarget->is64Bit())
391       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
392   } else {
393     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
394     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
397   }
398
399   if (Subtarget->hasLZCNT()) {
400     // When promoting the i8 variants, force them to i32 for a shorter
401     // encoding.
402     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
403     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
404     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
405     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
406     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
407     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
408     if (Subtarget->is64Bit())
409       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
410   } else {
411     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
412     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
413     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
414     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
415     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
416     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
417     if (Subtarget->is64Bit()) {
418       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
419       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
420     }
421   }
422
423   if (Subtarget->hasPOPCNT()) {
424     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
425   } else {
426     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
427     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
428     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
429     if (Subtarget->is64Bit())
430       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
431   }
432
433   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
434   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
435
436   // These should be promoted to a larger select which is supported.
437   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
438   // X86 wants to expand cmov itself.
439   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
440   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
441   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
442   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
443   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
445   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
446   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
447   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
448   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
451   if (Subtarget->is64Bit()) {
452     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
453     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
454   }
455   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
456
457   // Darwin ABI issue.
458   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
459   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
460   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
461   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
462   if (Subtarget->is64Bit())
463     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
464   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
465   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
466   if (Subtarget->is64Bit()) {
467     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
468     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
469     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
470     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
471     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
472   }
473   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
474   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
475   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
476   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
477   if (Subtarget->is64Bit()) {
478     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
479     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
480     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
481   }
482
483   if (Subtarget->hasSSE1())
484     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
485
486   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
487   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
488
489   // On X86 and X86-64, atomic operations are lowered to locked instructions.
490   // Locked instructions, in turn, have implicit fence semantics (all memory
491   // operations are flushed before issuing the locked instruction, and they
492   // are not buffered), so we can fold away the common pattern of
493   // fence-atomic-fence.
494   setShouldFoldAtomicFences(true);
495
496   // Expand certain atomics
497   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
498     MVT VT = IntVTs[i];
499     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
500     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
501     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
502   }
503
504   if (!Subtarget->is64Bit()) {
505     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
513   }
514
515   if (Subtarget->hasCmpxchg16b()) {
516     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
517   }
518
519   // FIXME - use subtarget debug flags
520   if (!Subtarget->isTargetDarwin() &&
521       !Subtarget->isTargetELF() &&
522       !Subtarget->isTargetCygMing()) {
523     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
524   }
525
526   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
527   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
528   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
529   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
530   if (Subtarget->is64Bit()) {
531     setExceptionPointerRegister(X86::RAX);
532     setExceptionSelectorRegister(X86::RDX);
533   } else {
534     setExceptionPointerRegister(X86::EAX);
535     setExceptionSelectorRegister(X86::EDX);
536   }
537   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
538   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
539
540   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
541   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
542
543   setOperationAction(ISD::TRAP, MVT::Other, Legal);
544
545   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
546   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
547   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
548   if (Subtarget->is64Bit()) {
549     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
550     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
551   } else {
552     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
553     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
554   }
555
556   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
557   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
558
559   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
560     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
561                        MVT::i64 : MVT::i32, Custom);
562   else if (TM.Options.EnableSegmentedStacks)
563     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
564                        MVT::i64 : MVT::i32, Custom);
565   else
566     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
567                        MVT::i64 : MVT::i32, Expand);
568
569   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
570     // f32 and f64 use SSE.
571     // Set up the FP register classes.
572     addRegisterClass(MVT::f32, &X86::FR32RegClass);
573     addRegisterClass(MVT::f64, &X86::FR64RegClass);
574
575     // Use ANDPD to simulate FABS.
576     setOperationAction(ISD::FABS , MVT::f64, Custom);
577     setOperationAction(ISD::FABS , MVT::f32, Custom);
578
579     // Use XORP to simulate FNEG.
580     setOperationAction(ISD::FNEG , MVT::f64, Custom);
581     setOperationAction(ISD::FNEG , MVT::f32, Custom);
582
583     // Use ANDPD and ORPD to simulate FCOPYSIGN.
584     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
585     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
586
587     // Lower this to FGETSIGNx86 plus an AND.
588     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
589     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
590
591     // We don't support sin/cos/fmod
592     setOperationAction(ISD::FSIN , MVT::f64, Expand);
593     setOperationAction(ISD::FCOS , MVT::f64, Expand);
594     setOperationAction(ISD::FSIN , MVT::f32, Expand);
595     setOperationAction(ISD::FCOS , MVT::f32, Expand);
596
597     // Expand FP immediates into loads from the stack, except for the special
598     // cases we handle.
599     addLegalFPImmediate(APFloat(+0.0)); // xorpd
600     addLegalFPImmediate(APFloat(+0.0f)); // xorps
601   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
602     // Use SSE for f32, x87 for f64.
603     // Set up the FP register classes.
604     addRegisterClass(MVT::f32, &X86::FR32RegClass);
605     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
606
607     // Use ANDPS to simulate FABS.
608     setOperationAction(ISD::FABS , MVT::f32, Custom);
609
610     // Use XORP to simulate FNEG.
611     setOperationAction(ISD::FNEG , MVT::f32, Custom);
612
613     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
614
615     // Use ANDPS and ORPS to simulate FCOPYSIGN.
616     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
617     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
618
619     // We don't support sin/cos/fmod
620     setOperationAction(ISD::FSIN , MVT::f32, Expand);
621     setOperationAction(ISD::FCOS , MVT::f32, Expand);
622
623     // Special cases we handle for FP constants.
624     addLegalFPImmediate(APFloat(+0.0f)); // xorps
625     addLegalFPImmediate(APFloat(+0.0)); // FLD0
626     addLegalFPImmediate(APFloat(+1.0)); // FLD1
627     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
628     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
629
630     if (!TM.Options.UnsafeFPMath) {
631       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
632       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
633     }
634   } else if (!TM.Options.UseSoftFloat) {
635     // f32 and f64 in x87.
636     // Set up the FP register classes.
637     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
638     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
639
640     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
641     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
642     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
643     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
644
645     if (!TM.Options.UnsafeFPMath) {
646       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
647       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
648     }
649     addLegalFPImmediate(APFloat(+0.0)); // FLD0
650     addLegalFPImmediate(APFloat(+1.0)); // FLD1
651     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
652     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
653     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
654     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
655     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
656     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
657   }
658
659   // We don't support FMA.
660   setOperationAction(ISD::FMA, MVT::f64, Expand);
661   setOperationAction(ISD::FMA, MVT::f32, Expand);
662
663   // Long double always uses X87.
664   if (!TM.Options.UseSoftFloat) {
665     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
666     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
667     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
668     {
669       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
670       addLegalFPImmediate(TmpFlt);  // FLD0
671       TmpFlt.changeSign();
672       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
673
674       bool ignored;
675       APFloat TmpFlt2(+1.0);
676       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
677                       &ignored);
678       addLegalFPImmediate(TmpFlt2);  // FLD1
679       TmpFlt2.changeSign();
680       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
681     }
682
683     if (!TM.Options.UnsafeFPMath) {
684       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
685       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
686     }
687
688     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
689     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
690     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
691     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
692     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
693     setOperationAction(ISD::FMA, MVT::f80, Expand);
694   }
695
696   // Always use a library call for pow.
697   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
698   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
699   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
700
701   setOperationAction(ISD::FLOG, MVT::f80, Expand);
702   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
703   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
704   setOperationAction(ISD::FEXP, MVT::f80, Expand);
705   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
706
707   // First set operation action for all vector types to either promote
708   // (for widening) or expand (for scalarization). Then we will selectively
709   // turn on ones that can be effectively codegen'd.
710   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
711            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
712     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
727     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
729     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
730     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
765     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
770     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
771              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
772       setTruncStoreAction((MVT::SimpleValueType)VT,
773                           (MVT::SimpleValueType)InnerVT, Expand);
774     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
775     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
776     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
777   }
778
779   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
780   // with -msoft-float, disable use of MMX as well.
781   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
782     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
783     // No operations on x86mmx supported, everything uses intrinsics.
784   }
785
786   // MMX-sized vectors (other than x86mmx) are expected to be expanded
787   // into smaller operations.
788   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
789   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
790   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
791   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
792   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
793   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
794   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
795   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
796   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
797   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
798   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
799   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
800   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
801   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
802   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
803   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
804   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
805   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
806   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
807   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
808   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
809   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
810   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
811   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
812   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
813   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
814   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
815   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
816   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
817
818   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
819     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
820
821     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
822     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
823     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
824     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
825     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
826     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
827     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
828     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
829     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
830     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
831     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
832     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
833   }
834
835   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
836     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
837
838     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
839     // registers cannot be used even for integer operations.
840     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
841     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
842     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
843     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
844
845     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
846     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
847     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
848     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
849     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
850     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
851     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
852     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
853     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
854     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
855     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
856     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
857     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
858     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
859     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
860     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
861
862     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
863     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
864     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
865     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
866
867     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
868     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
869     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
870     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
871     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
872
873     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
874     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
875     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
876     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
877     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
878
879     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
880     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
881       MVT VT = (MVT::SimpleValueType)i;
882       // Do not attempt to custom lower non-power-of-2 vectors
883       if (!isPowerOf2_32(VT.getVectorNumElements()))
884         continue;
885       // Do not attempt to custom lower non-128-bit vectors
886       if (!VT.is128BitVector())
887         continue;
888       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
889       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
890       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
891     }
892
893     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
894     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
895     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
896     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
897     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
898     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
899
900     if (Subtarget->is64Bit()) {
901       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
902       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
903     }
904
905     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
906     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
907       MVT VT = (MVT::SimpleValueType)i;
908
909       // Do not attempt to promote non-128-bit vectors
910       if (!VT.is128BitVector())
911         continue;
912
913       setOperationAction(ISD::AND,    VT, Promote);
914       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
915       setOperationAction(ISD::OR,     VT, Promote);
916       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
917       setOperationAction(ISD::XOR,    VT, Promote);
918       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
919       setOperationAction(ISD::LOAD,   VT, Promote);
920       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
921       setOperationAction(ISD::SELECT, VT, Promote);
922       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
923     }
924
925     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
926
927     // Custom lower v2i64 and v2f64 selects.
928     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
929     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
930     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
931     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
932
933     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
934     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
935   }
936
937   if (Subtarget->hasSSE41()) {
938     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
939     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
940     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
941     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
942     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
943     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
944     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
945     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
946     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
947     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
948
949     // FIXME: Do we need to handle scalar-to-vector here?
950     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
951
952     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
953     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
954     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
955     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
956     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
957
958     // i8 and i16 vectors are custom , because the source register and source
959     // source memory operand types are not the same width.  f32 vectors are
960     // custom since the immediate controlling the insert encodes additional
961     // information.
962     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
963     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
966
967     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
968     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
969     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
970     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
971
972     // FIXME: these should be Legal but thats only for the case where
973     // the index is constant.  For now custom expand to deal with that.
974     if (Subtarget->is64Bit()) {
975       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
976       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
977     }
978   }
979
980   if (Subtarget->hasSSE2()) {
981     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
982     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
983
984     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
985     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
986
987     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
988     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
989
990     if (Subtarget->hasAVX2()) {
991       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
992       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
993
994       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
995       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
996
997       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
998     } else {
999       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1000       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1001
1002       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1003       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1004
1005       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1006     }
1007   }
1008
1009   if (Subtarget->hasSSE42())
1010     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
1011
1012   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1013     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1014     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1015     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1016     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1017     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1018     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1019
1020     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1021     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1022     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1023
1024     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1025     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1026     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1027     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1028     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1029     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1030
1031     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1032     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1033     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1034     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1035     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1036     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1037
1038     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1039     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1040     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1041
1042     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1043     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1044
1045     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1046     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1047
1048     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1049     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1050
1051     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1052     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1053     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1054     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1055
1056     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1057     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1058     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1059
1060     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1061     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1062     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1063     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1064
1065     if (Subtarget->hasFMA()) {
1066       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1067       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1068       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1069       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1070       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1071       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1072     }
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 VT = (MVT::SimpleValueType)i;
1128
1129       // Extract subvector is special because the value type
1130       // (result) is 128-bit but the source is 256-bit wide.
1131       if (VT.is128BitVector())
1132         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1133
1134       // Do not attempt to custom lower other non-256-bit vectors
1135       if (!VT.is256BitVector())
1136         continue;
1137
1138       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1139       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1140       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1141       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1142       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1143       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1144       setOperationAction(ISD::CONCAT_VECTORS,     VT, 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 VT = (MVT::SimpleValueType)i;
1150
1151       // Do not attempt to promote non-256-bit vectors
1152       if (!VT.is256BitVector())
1153         continue;
1154
1155       setOperationAction(ISD::AND,    VT, Promote);
1156       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1157       setOperationAction(ISD::OR,     VT, Promote);
1158       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1159       setOperationAction(ISD::XOR,    VT, Promote);
1160       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1161       setOperationAction(ISD::LOAD,   VT, Promote);
1162       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1163       setOperationAction(ISD::SELECT, VT, Promote);
1164       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1165     }
1166   }
1167
1168   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1169   // of this type with custom code.
1170   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1171            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1172     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1173                        Custom);
1174   }
1175
1176   // We want to custom lower some of our intrinsics.
1177   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1178   setOperationAction(ISD::INTRINSIC_W_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::FMA);
1223   setTargetDAGCombine(ISD::SUB);
1224   setTargetDAGCombine(ISD::LOAD);
1225   setTargetDAGCombine(ISD::STORE);
1226   setTargetDAGCombine(ISD::ZERO_EXTEND);
1227   setTargetDAGCombine(ISD::ANY_EXTEND);
1228   setTargetDAGCombine(ISD::SIGN_EXTEND);
1229   setTargetDAGCombine(ISD::TRUNCATE);
1230   setTargetDAGCombine(ISD::UINT_TO_FP);
1231   setTargetDAGCombine(ISD::SINT_TO_FP);
1232   setTargetDAGCombine(ISD::SETCC);
1233   setTargetDAGCombine(ISD::FP_TO_SINT);
1234   if (Subtarget->is64Bit())
1235     setTargetDAGCombine(ISD::MUL);
1236   setTargetDAGCombine(ISD::XOR);
1237
1238   computeRegisterProperties();
1239
1240   // On Darwin, -Os means optimize for size without hurting performance,
1241   // do not reduce the limit.
1242   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1243   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1244   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1245   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1246   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1247   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1248   setPrefLoopAlignment(4); // 2^4 bytes.
1249   benefitFromCodePlacementOpt = true;
1250
1251   // Predictable cmov don't hurt on atom because it's in-order.
1252   predictableSelectIsExpensive = !Subtarget->isAtom();
1253
1254   setPrefFunctionAlignment(4); // 2^4 bytes.
1255 }
1256
1257
1258 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1259   if (!VT.isVector()) return MVT::i8;
1260   return VT.changeVectorElementTypeToInteger();
1261 }
1262
1263
1264 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1265 /// the desired ByVal argument alignment.
1266 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1267   if (MaxAlign == 16)
1268     return;
1269   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1270     if (VTy->getBitWidth() == 128)
1271       MaxAlign = 16;
1272   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1273     unsigned EltAlign = 0;
1274     getMaxByValAlign(ATy->getElementType(), EltAlign);
1275     if (EltAlign > MaxAlign)
1276       MaxAlign = EltAlign;
1277   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1278     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1279       unsigned EltAlign = 0;
1280       getMaxByValAlign(STy->getElementType(i), EltAlign);
1281       if (EltAlign > MaxAlign)
1282         MaxAlign = EltAlign;
1283       if (MaxAlign == 16)
1284         break;
1285     }
1286   }
1287 }
1288
1289 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1290 /// function arguments in the caller parameter area. For X86, aggregates
1291 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1292 /// are at 4-byte boundaries.
1293 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1294   if (Subtarget->is64Bit()) {
1295     // Max of 8 and alignment of type.
1296     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1297     if (TyAlign > 8)
1298       return TyAlign;
1299     return 8;
1300   }
1301
1302   unsigned Align = 4;
1303   if (Subtarget->hasSSE1())
1304     getMaxByValAlign(Ty, Align);
1305   return Align;
1306 }
1307
1308 /// getOptimalMemOpType - Returns the target specific optimal type for load
1309 /// and store operations as a result of memset, memcpy, and memmove
1310 /// lowering. If DstAlign is zero that means it's safe to destination
1311 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1312 /// means there isn't a need to check it against alignment requirement,
1313 /// probably because the source does not need to be loaded. If
1314 /// 'IsZeroVal' is true, that means it's safe to return a
1315 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1316 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1317 /// constant so it does not need to be loaded.
1318 /// It returns EVT::Other if the type should be determined using generic
1319 /// target-independent logic.
1320 EVT
1321 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1322                                        unsigned DstAlign, unsigned SrcAlign,
1323                                        bool IsZeroVal,
1324                                        bool MemcpyStrSrc,
1325                                        MachineFunction &MF) const {
1326   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1327   // linux.  This is because the stack realignment code can't handle certain
1328   // cases like PR2962.  This should be removed when PR2962 is fixed.
1329   const Function *F = MF.getFunction();
1330   if (IsZeroVal &&
1331       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1332     if (Size >= 16 &&
1333         (Subtarget->isUnalignedMemAccessFast() ||
1334          ((DstAlign == 0 || DstAlign >= 16) &&
1335           (SrcAlign == 0 || SrcAlign >= 16))) &&
1336         Subtarget->getStackAlignment() >= 16) {
1337       if (Subtarget->getStackAlignment() >= 32) {
1338         if (Subtarget->hasAVX2())
1339           return MVT::v8i32;
1340         if (Subtarget->hasAVX())
1341           return MVT::v8f32;
1342       }
1343       if (Subtarget->hasSSE2())
1344         return MVT::v4i32;
1345       if (Subtarget->hasSSE1())
1346         return MVT::v4f32;
1347     } else if (!MemcpyStrSrc && Size >= 8 &&
1348                !Subtarget->is64Bit() &&
1349                Subtarget->getStackAlignment() >= 8 &&
1350                Subtarget->hasSSE2()) {
1351       // Do not use f64 to lower memcpy if source is string constant. It's
1352       // better to use i32 to avoid the loads.
1353       return MVT::f64;
1354     }
1355   }
1356   if (Subtarget->is64Bit() && Size >= 8)
1357     return MVT::i64;
1358   return MVT::i32;
1359 }
1360
1361 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1362 /// current function.  The returned value is a member of the
1363 /// MachineJumpTableInfo::JTEntryKind enum.
1364 unsigned X86TargetLowering::getJumpTableEncoding() const {
1365   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1366   // symbol.
1367   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1368       Subtarget->isPICStyleGOT())
1369     return MachineJumpTableInfo::EK_Custom32;
1370
1371   // Otherwise, use the normal jump table encoding heuristics.
1372   return TargetLowering::getJumpTableEncoding();
1373 }
1374
1375 const MCExpr *
1376 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1377                                              const MachineBasicBlock *MBB,
1378                                              unsigned uid,MCContext &Ctx) const{
1379   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1380          Subtarget->isPICStyleGOT());
1381   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1382   // entries.
1383   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1384                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1385 }
1386
1387 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1388 /// jumptable.
1389 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1390                                                     SelectionDAG &DAG) const {
1391   if (!Subtarget->is64Bit())
1392     // This doesn't have DebugLoc associated with it, but is not really the
1393     // same as a Register.
1394     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1395   return Table;
1396 }
1397
1398 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1399 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1400 /// MCExpr.
1401 const MCExpr *X86TargetLowering::
1402 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1403                              MCContext &Ctx) const {
1404   // X86-64 uses RIP relative addressing based on the jump table label.
1405   if (Subtarget->isPICStyleRIPRel())
1406     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1407
1408   // Otherwise, the reference is relative to the PIC base.
1409   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1410 }
1411
1412 // FIXME: Why this routine is here? Move to RegInfo!
1413 std::pair<const TargetRegisterClass*, uint8_t>
1414 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1415   const TargetRegisterClass *RRC = 0;
1416   uint8_t Cost = 1;
1417   switch (VT.getSimpleVT().SimpleTy) {
1418   default:
1419     return TargetLowering::findRepresentativeClass(VT);
1420   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1421     RRC = Subtarget->is64Bit() ?
1422       (const TargetRegisterClass*)&X86::GR64RegClass :
1423       (const TargetRegisterClass*)&X86::GR32RegClass;
1424     break;
1425   case MVT::x86mmx:
1426     RRC = &X86::VR64RegClass;
1427     break;
1428   case MVT::f32: case MVT::f64:
1429   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1430   case MVT::v4f32: case MVT::v2f64:
1431   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1432   case MVT::v4f64:
1433     RRC = &X86::VR128RegClass;
1434     break;
1435   }
1436   return std::make_pair(RRC, Cost);
1437 }
1438
1439 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1440                                                unsigned &Offset) const {
1441   if (!Subtarget->isTargetLinux())
1442     return false;
1443
1444   if (Subtarget->is64Bit()) {
1445     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1446     Offset = 0x28;
1447     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1448       AddressSpace = 256;
1449     else
1450       AddressSpace = 257;
1451   } else {
1452     // %gs:0x14 on i386
1453     Offset = 0x14;
1454     AddressSpace = 256;
1455   }
1456   return true;
1457 }
1458
1459
1460 //===----------------------------------------------------------------------===//
1461 //               Return Value Calling Convention Implementation
1462 //===----------------------------------------------------------------------===//
1463
1464 #include "X86GenCallingConv.inc"
1465
1466 bool
1467 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1468                                   MachineFunction &MF, bool isVarArg,
1469                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1470                         LLVMContext &Context) const {
1471   SmallVector<CCValAssign, 16> RVLocs;
1472   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1473                  RVLocs, Context);
1474   return CCInfo.CheckReturn(Outs, RetCC_X86);
1475 }
1476
1477 SDValue
1478 X86TargetLowering::LowerReturn(SDValue Chain,
1479                                CallingConv::ID CallConv, bool isVarArg,
1480                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1481                                const SmallVectorImpl<SDValue> &OutVals,
1482                                DebugLoc dl, SelectionDAG &DAG) const {
1483   MachineFunction &MF = DAG.getMachineFunction();
1484   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1485
1486   SmallVector<CCValAssign, 16> RVLocs;
1487   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1488                  RVLocs, *DAG.getContext());
1489   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1490
1491   // Add the regs to the liveout set for the function.
1492   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1493   for (unsigned i = 0; i != RVLocs.size(); ++i)
1494     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1495       MRI.addLiveOut(RVLocs[i].getLocReg());
1496
1497   SDValue Flag;
1498
1499   SmallVector<SDValue, 6> RetOps;
1500   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1501   // Operand #1 = Bytes To Pop
1502   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1503                    MVT::i16));
1504
1505   // Copy the result values into the output registers.
1506   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1507     CCValAssign &VA = RVLocs[i];
1508     assert(VA.isRegLoc() && "Can only return in registers!");
1509     SDValue ValToCopy = OutVals[i];
1510     EVT ValVT = ValToCopy.getValueType();
1511
1512     // Promote values to the appropriate types
1513     if (VA.getLocInfo() == CCValAssign::SExt)
1514       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1515     else if (VA.getLocInfo() == CCValAssign::ZExt)
1516       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1517     else if (VA.getLocInfo() == CCValAssign::AExt)
1518       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1519     else if (VA.getLocInfo() == CCValAssign::BCvt)
1520       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1521
1522     // If this is x86-64, and we disabled SSE, we can't return FP values,
1523     // or SSE or MMX vectors.
1524     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1525          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1526           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1527       report_fatal_error("SSE register return with SSE disabled");
1528     }
1529     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1530     // llvm-gcc has never done it right and no one has noticed, so this
1531     // should be OK for now.
1532     if (ValVT == MVT::f64 &&
1533         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1534       report_fatal_error("SSE2 register return with SSE2 disabled");
1535
1536     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1537     // the RET instruction and handled by the FP Stackifier.
1538     if (VA.getLocReg() == X86::ST0 ||
1539         VA.getLocReg() == X86::ST1) {
1540       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1541       // change the value to the FP stack register class.
1542       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1543         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1544       RetOps.push_back(ValToCopy);
1545       // Don't emit a copytoreg.
1546       continue;
1547     }
1548
1549     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1550     // which is returned in RAX / RDX.
1551     if (Subtarget->is64Bit()) {
1552       if (ValVT == MVT::x86mmx) {
1553         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1554           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1555           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1556                                   ValToCopy);
1557           // If we don't have SSE2 available, convert to v4f32 so the generated
1558           // register is legal.
1559           if (!Subtarget->hasSSE2())
1560             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1561         }
1562       }
1563     }
1564
1565     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1566     Flag = Chain.getValue(1);
1567   }
1568
1569   // The x86-64 ABI for returning structs by value requires that we copy
1570   // the sret argument into %rax for the return. We saved the argument into
1571   // a virtual register in the entry block, so now we copy the value out
1572   // and into %rax.
1573   if (Subtarget->is64Bit() &&
1574       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1575     MachineFunction &MF = DAG.getMachineFunction();
1576     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1577     unsigned Reg = FuncInfo->getSRetReturnReg();
1578     assert(Reg &&
1579            "SRetReturnReg should have been set in LowerFormalArguments().");
1580     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1581
1582     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1583     Flag = Chain.getValue(1);
1584
1585     // RAX now acts like a return value.
1586     MRI.addLiveOut(X86::RAX);
1587   }
1588
1589   RetOps[0] = Chain;  // Update chain.
1590
1591   // Add the flag if we have it.
1592   if (Flag.getNode())
1593     RetOps.push_back(Flag);
1594
1595   return DAG.getNode(X86ISD::RET_FLAG, dl,
1596                      MVT::Other, &RetOps[0], RetOps.size());
1597 }
1598
1599 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1600   if (N->getNumValues() != 1)
1601     return false;
1602   if (!N->hasNUsesOfValue(1, 0))
1603     return false;
1604
1605   SDValue TCChain = Chain;
1606   SDNode *Copy = *N->use_begin();
1607   if (Copy->getOpcode() == ISD::CopyToReg) {
1608     // If the copy has a glue operand, we conservatively assume it isn't safe to
1609     // perform a tail call.
1610     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1611       return false;
1612     TCChain = Copy->getOperand(0);
1613   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1614     return false;
1615
1616   bool HasRet = false;
1617   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1618        UI != UE; ++UI) {
1619     if (UI->getOpcode() != X86ISD::RET_FLAG)
1620       return false;
1621     HasRet = true;
1622   }
1623
1624   if (!HasRet)
1625     return false;
1626
1627   Chain = TCChain;
1628   return true;
1629 }
1630
1631 EVT
1632 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1633                                             ISD::NodeType ExtendKind) const {
1634   MVT ReturnMVT;
1635   // TODO: Is this also valid on 32-bit?
1636   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1637     ReturnMVT = MVT::i8;
1638   else
1639     ReturnMVT = MVT::i32;
1640
1641   EVT MinVT = getRegisterType(Context, ReturnMVT);
1642   return VT.bitsLT(MinVT) ? MinVT : VT;
1643 }
1644
1645 /// LowerCallResult - Lower the result values of a call into the
1646 /// appropriate copies out of appropriate physical registers.
1647 ///
1648 SDValue
1649 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1650                                    CallingConv::ID CallConv, bool isVarArg,
1651                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1652                                    DebugLoc dl, SelectionDAG &DAG,
1653                                    SmallVectorImpl<SDValue> &InVals) const {
1654
1655   // Assign locations to each value returned by this call.
1656   SmallVector<CCValAssign, 16> RVLocs;
1657   bool Is64Bit = Subtarget->is64Bit();
1658   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1659                  getTargetMachine(), RVLocs, *DAG.getContext());
1660   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1661
1662   // Copy all of the result registers out of their specified physreg.
1663   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1664     CCValAssign &VA = RVLocs[i];
1665     EVT CopyVT = VA.getValVT();
1666
1667     // If this is x86-64, and we disabled SSE, we can't return FP values
1668     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1669         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1670       report_fatal_error("SSE register return with SSE disabled");
1671     }
1672
1673     SDValue Val;
1674
1675     // If this is a call to a function that returns an fp value on the floating
1676     // point stack, we must guarantee the value is popped from the stack, so
1677     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1678     // if the return value is not used. We use the FpPOP_RETVAL instruction
1679     // instead.
1680     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1681       // If we prefer to use the value in xmm registers, copy it out as f80 and
1682       // use a truncate to move it from fp stack reg to xmm reg.
1683       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1684       SDValue Ops[] = { Chain, InFlag };
1685       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1686                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1687       Val = Chain.getValue(0);
1688
1689       // Round the f80 to the right size, which also moves it to the appropriate
1690       // xmm register.
1691       if (CopyVT != VA.getValVT())
1692         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1693                           // This truncation won't change the value.
1694                           DAG.getIntPtrConstant(1));
1695     } else {
1696       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1697                                  CopyVT, InFlag).getValue(1);
1698       Val = Chain.getValue(0);
1699     }
1700     InFlag = Chain.getValue(2);
1701     InVals.push_back(Val);
1702   }
1703
1704   return Chain;
1705 }
1706
1707
1708 //===----------------------------------------------------------------------===//
1709 //                C & StdCall & Fast Calling Convention implementation
1710 //===----------------------------------------------------------------------===//
1711 //  StdCall calling convention seems to be standard for many Windows' API
1712 //  routines and around. It differs from C calling convention just a little:
1713 //  callee should clean up the stack, not caller. Symbols should be also
1714 //  decorated in some fancy way :) It doesn't support any vector arguments.
1715 //  For info on fast calling convention see Fast Calling Convention (tail call)
1716 //  implementation LowerX86_32FastCCCallTo.
1717
1718 /// CallIsStructReturn - Determines whether a call uses struct return
1719 /// semantics.
1720 enum StructReturnType {
1721   NotStructReturn,
1722   RegStructReturn,
1723   StackStructReturn
1724 };
1725 static StructReturnType
1726 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1727   if (Outs.empty())
1728     return NotStructReturn;
1729
1730   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1731   if (!Flags.isSRet())
1732     return NotStructReturn;
1733   if (Flags.isInReg())
1734     return RegStructReturn;
1735   return StackStructReturn;
1736 }
1737
1738 /// ArgsAreStructReturn - Determines whether a function uses struct
1739 /// return semantics.
1740 static StructReturnType
1741 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1742   if (Ins.empty())
1743     return NotStructReturn;
1744
1745   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1746   if (!Flags.isSRet())
1747     return NotStructReturn;
1748   if (Flags.isInReg())
1749     return RegStructReturn;
1750   return StackStructReturn;
1751 }
1752
1753 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1754 /// by "Src" to address "Dst" with size and alignment information specified by
1755 /// the specific parameter attribute. The copy will be passed as a byval
1756 /// function parameter.
1757 static SDValue
1758 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1759                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1760                           DebugLoc dl) {
1761   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1762
1763   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1764                        /*isVolatile*/false, /*AlwaysInline=*/true,
1765                        MachinePointerInfo(), MachinePointerInfo());
1766 }
1767
1768 /// IsTailCallConvention - Return true if the calling convention is one that
1769 /// supports tail call optimization.
1770 static bool IsTailCallConvention(CallingConv::ID CC) {
1771   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1772 }
1773
1774 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1775   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1776     return false;
1777
1778   CallSite CS(CI);
1779   CallingConv::ID CalleeCC = CS.getCallingConv();
1780   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1781     return false;
1782
1783   return true;
1784 }
1785
1786 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1787 /// a tailcall target by changing its ABI.
1788 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1789                                    bool GuaranteedTailCallOpt) {
1790   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1791 }
1792
1793 SDValue
1794 X86TargetLowering::LowerMemArgument(SDValue Chain,
1795                                     CallingConv::ID CallConv,
1796                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1797                                     DebugLoc dl, SelectionDAG &DAG,
1798                                     const CCValAssign &VA,
1799                                     MachineFrameInfo *MFI,
1800                                     unsigned i) const {
1801   // Create the nodes corresponding to a load from this parameter slot.
1802   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1803   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1804                               getTargetMachine().Options.GuaranteedTailCallOpt);
1805   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1806   EVT ValVT;
1807
1808   // If value is passed by pointer we have address passed instead of the value
1809   // itself.
1810   if (VA.getLocInfo() == CCValAssign::Indirect)
1811     ValVT = VA.getLocVT();
1812   else
1813     ValVT = VA.getValVT();
1814
1815   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1816   // changed with more analysis.
1817   // In case of tail call optimization mark all arguments mutable. Since they
1818   // could be overwritten by lowering of arguments in case of a tail call.
1819   if (Flags.isByVal()) {
1820     unsigned Bytes = Flags.getByValSize();
1821     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1822     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1823     return DAG.getFrameIndex(FI, getPointerTy());
1824   } else {
1825     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1826                                     VA.getLocMemOffset(), isImmutable);
1827     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1828     return DAG.getLoad(ValVT, dl, Chain, FIN,
1829                        MachinePointerInfo::getFixedStack(FI),
1830                        false, false, false, 0);
1831   }
1832 }
1833
1834 SDValue
1835 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1836                                         CallingConv::ID CallConv,
1837                                         bool isVarArg,
1838                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1839                                         DebugLoc dl,
1840                                         SelectionDAG &DAG,
1841                                         SmallVectorImpl<SDValue> &InVals)
1842                                           const {
1843   MachineFunction &MF = DAG.getMachineFunction();
1844   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1845
1846   const Function* Fn = MF.getFunction();
1847   if (Fn->hasExternalLinkage() &&
1848       Subtarget->isTargetCygMing() &&
1849       Fn->getName() == "main")
1850     FuncInfo->setForceFramePointer(true);
1851
1852   MachineFrameInfo *MFI = MF.getFrameInfo();
1853   bool Is64Bit = Subtarget->is64Bit();
1854   bool IsWindows = Subtarget->isTargetWindows();
1855   bool IsWin64 = Subtarget->isTargetWin64();
1856
1857   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1858          "Var args not supported with calling convention fastcc or ghc");
1859
1860   // Assign locations to all of the incoming arguments.
1861   SmallVector<CCValAssign, 16> ArgLocs;
1862   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1863                  ArgLocs, *DAG.getContext());
1864
1865   // Allocate shadow area for Win64
1866   if (IsWin64) {
1867     CCInfo.AllocateStack(32, 8);
1868   }
1869
1870   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1871
1872   unsigned LastVal = ~0U;
1873   SDValue ArgValue;
1874   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1875     CCValAssign &VA = ArgLocs[i];
1876     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1877     // places.
1878     assert(VA.getValNo() != LastVal &&
1879            "Don't support value assigned to multiple locs yet");
1880     (void)LastVal;
1881     LastVal = VA.getValNo();
1882
1883     if (VA.isRegLoc()) {
1884       EVT RegVT = VA.getLocVT();
1885       const TargetRegisterClass *RC;
1886       if (RegVT == MVT::i32)
1887         RC = &X86::GR32RegClass;
1888       else if (Is64Bit && RegVT == MVT::i64)
1889         RC = &X86::GR64RegClass;
1890       else if (RegVT == MVT::f32)
1891         RC = &X86::FR32RegClass;
1892       else if (RegVT == MVT::f64)
1893         RC = &X86::FR64RegClass;
1894       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1895         RC = &X86::VR256RegClass;
1896       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1897         RC = &X86::VR128RegClass;
1898       else if (RegVT == MVT::x86mmx)
1899         RC = &X86::VR64RegClass;
1900       else
1901         llvm_unreachable("Unknown argument type!");
1902
1903       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1904       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1905
1906       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1907       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1908       // right size.
1909       if (VA.getLocInfo() == CCValAssign::SExt)
1910         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1911                                DAG.getValueType(VA.getValVT()));
1912       else if (VA.getLocInfo() == CCValAssign::ZExt)
1913         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1914                                DAG.getValueType(VA.getValVT()));
1915       else if (VA.getLocInfo() == CCValAssign::BCvt)
1916         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1917
1918       if (VA.isExtInLoc()) {
1919         // Handle MMX values passed in XMM regs.
1920         if (RegVT.isVector()) {
1921           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1922                                  ArgValue);
1923         } else
1924           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1925       }
1926     } else {
1927       assert(VA.isMemLoc());
1928       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1929     }
1930
1931     // If value is passed via pointer - do a load.
1932     if (VA.getLocInfo() == CCValAssign::Indirect)
1933       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1934                              MachinePointerInfo(), false, false, false, 0);
1935
1936     InVals.push_back(ArgValue);
1937   }
1938
1939   // The x86-64 ABI for returning structs by value requires that we copy
1940   // the sret argument into %rax for the return. Save the argument into
1941   // a virtual register so that we can access it from the return points.
1942   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1943     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1944     unsigned Reg = FuncInfo->getSRetReturnReg();
1945     if (!Reg) {
1946       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1947       FuncInfo->setSRetReturnReg(Reg);
1948     }
1949     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1950     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1951   }
1952
1953   unsigned StackSize = CCInfo.getNextStackOffset();
1954   // Align stack specially for tail calls.
1955   if (FuncIsMadeTailCallSafe(CallConv,
1956                              MF.getTarget().Options.GuaranteedTailCallOpt))
1957     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1958
1959   // If the function takes variable number of arguments, make a frame index for
1960   // the start of the first vararg value... for expansion of llvm.va_start.
1961   if (isVarArg) {
1962     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1963                     CallConv != CallingConv::X86_ThisCall)) {
1964       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1965     }
1966     if (Is64Bit) {
1967       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1968
1969       // FIXME: We should really autogenerate these arrays
1970       static const uint16_t GPR64ArgRegsWin64[] = {
1971         X86::RCX, X86::RDX, X86::R8,  X86::R9
1972       };
1973       static const uint16_t GPR64ArgRegs64Bit[] = {
1974         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1975       };
1976       static const uint16_t XMMArgRegs64Bit[] = {
1977         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1978         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1979       };
1980       const uint16_t *GPR64ArgRegs;
1981       unsigned NumXMMRegs = 0;
1982
1983       if (IsWin64) {
1984         // The XMM registers which might contain var arg parameters are shadowed
1985         // in their paired GPR.  So we only need to save the GPR to their home
1986         // slots.
1987         TotalNumIntRegs = 4;
1988         GPR64ArgRegs = GPR64ArgRegsWin64;
1989       } else {
1990         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1991         GPR64ArgRegs = GPR64ArgRegs64Bit;
1992
1993         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1994                                                 TotalNumXMMRegs);
1995       }
1996       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1997                                                        TotalNumIntRegs);
1998
1999       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
2000       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2001              "SSE register cannot be used when SSE is disabled!");
2002       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2003                NoImplicitFloatOps) &&
2004              "SSE register cannot be used when SSE is disabled!");
2005       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2006           !Subtarget->hasSSE1())
2007         // Kernel mode asks for SSE to be disabled, so don't push them
2008         // on the stack.
2009         TotalNumXMMRegs = 0;
2010
2011       if (IsWin64) {
2012         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2013         // Get to the caller-allocated home save location.  Add 8 to account
2014         // for the return address.
2015         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2016         FuncInfo->setRegSaveFrameIndex(
2017           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2018         // Fixup to set vararg frame on shadow area (4 x i64).
2019         if (NumIntRegs < 4)
2020           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2021       } else {
2022         // For X86-64, if there are vararg parameters that are passed via
2023         // registers, then we must store them to their spots on the stack so
2024         // they may be loaded by deferencing the result of va_next.
2025         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2026         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2027         FuncInfo->setRegSaveFrameIndex(
2028           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2029                                false));
2030       }
2031
2032       // Store the integer parameter registers.
2033       SmallVector<SDValue, 8> MemOps;
2034       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2035                                         getPointerTy());
2036       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2037       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2038         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2039                                   DAG.getIntPtrConstant(Offset));
2040         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2041                                      &X86::GR64RegClass);
2042         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2043         SDValue Store =
2044           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2045                        MachinePointerInfo::getFixedStack(
2046                          FuncInfo->getRegSaveFrameIndex(), Offset),
2047                        false, false, 0);
2048         MemOps.push_back(Store);
2049         Offset += 8;
2050       }
2051
2052       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2053         // Now store the XMM (fp + vector) parameter registers.
2054         SmallVector<SDValue, 11> SaveXMMOps;
2055         SaveXMMOps.push_back(Chain);
2056
2057         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2058         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2059         SaveXMMOps.push_back(ALVal);
2060
2061         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2062                                FuncInfo->getRegSaveFrameIndex()));
2063         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2064                                FuncInfo->getVarArgsFPOffset()));
2065
2066         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2067           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2068                                        &X86::VR128RegClass);
2069           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2070           SaveXMMOps.push_back(Val);
2071         }
2072         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2073                                      MVT::Other,
2074                                      &SaveXMMOps[0], SaveXMMOps.size()));
2075       }
2076
2077       if (!MemOps.empty())
2078         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2079                             &MemOps[0], MemOps.size());
2080     }
2081   }
2082
2083   // Some CCs need callee pop.
2084   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2085                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2086     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2087   } else {
2088     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2089     // If this is an sret function, the return should pop the hidden pointer.
2090     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2091         argsAreStructReturn(Ins) == StackStructReturn)
2092       FuncInfo->setBytesToPopOnReturn(4);
2093   }
2094
2095   if (!Is64Bit) {
2096     // RegSaveFrameIndex is X86-64 only.
2097     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2098     if (CallConv == CallingConv::X86_FastCall ||
2099         CallConv == CallingConv::X86_ThisCall)
2100       // fastcc functions can't have varargs.
2101       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2102   }
2103
2104   FuncInfo->setArgumentStackSize(StackSize);
2105
2106   return Chain;
2107 }
2108
2109 SDValue
2110 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2111                                     SDValue StackPtr, SDValue Arg,
2112                                     DebugLoc dl, SelectionDAG &DAG,
2113                                     const CCValAssign &VA,
2114                                     ISD::ArgFlagsTy Flags) const {
2115   unsigned LocMemOffset = VA.getLocMemOffset();
2116   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2117   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2118   if (Flags.isByVal())
2119     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2120
2121   return DAG.getStore(Chain, dl, Arg, PtrOff,
2122                       MachinePointerInfo::getStack(LocMemOffset),
2123                       false, false, 0);
2124 }
2125
2126 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2127 /// optimization is performed and it is required.
2128 SDValue
2129 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2130                                            SDValue &OutRetAddr, SDValue Chain,
2131                                            bool IsTailCall, bool Is64Bit,
2132                                            int FPDiff, DebugLoc dl) const {
2133   // Adjust the Return address stack slot.
2134   EVT VT = getPointerTy();
2135   OutRetAddr = getReturnAddressFrameIndex(DAG);
2136
2137   // Load the "old" Return address.
2138   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2139                            false, false, false, 0);
2140   return SDValue(OutRetAddr.getNode(), 1);
2141 }
2142
2143 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2144 /// optimization is performed and it is required (FPDiff!=0).
2145 static SDValue
2146 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2147                          SDValue Chain, SDValue RetAddrFrIdx,
2148                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2149   // Store the return address to the appropriate stack slot.
2150   if (!FPDiff) return Chain;
2151   // Calculate the new stack slot for the return address.
2152   int SlotSize = Is64Bit ? 8 : 4;
2153   int NewReturnAddrFI =
2154     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2155   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2156   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2157   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2158                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2159                        false, false, 0);
2160   return Chain;
2161 }
2162
2163 SDValue
2164 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2165                              SmallVectorImpl<SDValue> &InVals) const {
2166   SelectionDAG &DAG                     = CLI.DAG;
2167   DebugLoc &dl                          = CLI.DL;
2168   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2169   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2170   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2171   SDValue Chain                         = CLI.Chain;
2172   SDValue Callee                        = CLI.Callee;
2173   CallingConv::ID CallConv              = CLI.CallConv;
2174   bool &isTailCall                      = CLI.IsTailCall;
2175   bool isVarArg                         = CLI.IsVarArg;
2176
2177   MachineFunction &MF = DAG.getMachineFunction();
2178   bool Is64Bit        = Subtarget->is64Bit();
2179   bool IsWin64        = Subtarget->isTargetWin64();
2180   bool IsWindows      = Subtarget->isTargetWindows();
2181   StructReturnType SR = callIsStructReturn(Outs);
2182   bool IsSibcall      = false;
2183
2184   if (MF.getTarget().Options.DisableTailCalls)
2185     isTailCall = false;
2186
2187   if (isTailCall) {
2188     // Check if it's really possible to do a tail call.
2189     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2190                     isVarArg, SR != NotStructReturn,
2191                     MF.getFunction()->hasStructRetAttr(),
2192                     Outs, OutVals, Ins, DAG);
2193
2194     // Sibcalls are automatically detected tailcalls which do not require
2195     // ABI changes.
2196     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2197       IsSibcall = true;
2198
2199     if (isTailCall)
2200       ++NumTailCalls;
2201   }
2202
2203   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2204          "Var args not supported with calling convention fastcc or ghc");
2205
2206   // Analyze operands of the call, assigning locations to each operand.
2207   SmallVector<CCValAssign, 16> ArgLocs;
2208   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2209                  ArgLocs, *DAG.getContext());
2210
2211   // Allocate shadow area for Win64
2212   if (IsWin64) {
2213     CCInfo.AllocateStack(32, 8);
2214   }
2215
2216   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2217
2218   // Get a count of how many bytes are to be pushed on the stack.
2219   unsigned NumBytes = CCInfo.getNextStackOffset();
2220   if (IsSibcall)
2221     // This is a sibcall. The memory operands are available in caller's
2222     // own caller's stack.
2223     NumBytes = 0;
2224   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2225            IsTailCallConvention(CallConv))
2226     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2227
2228   int FPDiff = 0;
2229   if (isTailCall && !IsSibcall) {
2230     // Lower arguments at fp - stackoffset + fpdiff.
2231     unsigned NumBytesCallerPushed =
2232       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2233     FPDiff = NumBytesCallerPushed - NumBytes;
2234
2235     // Set the delta of movement of the returnaddr stackslot.
2236     // But only set if delta is greater than previous delta.
2237     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2238       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2239   }
2240
2241   if (!IsSibcall)
2242     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2243
2244   SDValue RetAddrFrIdx;
2245   // Load return address for tail calls.
2246   if (isTailCall && FPDiff)
2247     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2248                                     Is64Bit, FPDiff, dl);
2249
2250   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2251   SmallVector<SDValue, 8> MemOpChains;
2252   SDValue StackPtr;
2253
2254   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2255   // of tail call optimization arguments are handle later.
2256   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2257     CCValAssign &VA = ArgLocs[i];
2258     EVT RegVT = VA.getLocVT();
2259     SDValue Arg = OutVals[i];
2260     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2261     bool isByVal = Flags.isByVal();
2262
2263     // Promote the value if needed.
2264     switch (VA.getLocInfo()) {
2265     default: llvm_unreachable("Unknown loc info!");
2266     case CCValAssign::Full: break;
2267     case CCValAssign::SExt:
2268       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2269       break;
2270     case CCValAssign::ZExt:
2271       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2272       break;
2273     case CCValAssign::AExt:
2274       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2275         // Special case: passing MMX values in XMM registers.
2276         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2277         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2278         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2279       } else
2280         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2281       break;
2282     case CCValAssign::BCvt:
2283       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2284       break;
2285     case CCValAssign::Indirect: {
2286       // Store the argument.
2287       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2288       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2289       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2290                            MachinePointerInfo::getFixedStack(FI),
2291                            false, false, 0);
2292       Arg = SpillSlot;
2293       break;
2294     }
2295     }
2296
2297     if (VA.isRegLoc()) {
2298       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2299       if (isVarArg && IsWin64) {
2300         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2301         // shadow reg if callee is a varargs function.
2302         unsigned ShadowReg = 0;
2303         switch (VA.getLocReg()) {
2304         case X86::XMM0: ShadowReg = X86::RCX; break;
2305         case X86::XMM1: ShadowReg = X86::RDX; break;
2306         case X86::XMM2: ShadowReg = X86::R8; break;
2307         case X86::XMM3: ShadowReg = X86::R9; break;
2308         }
2309         if (ShadowReg)
2310           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2311       }
2312     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2313       assert(VA.isMemLoc());
2314       if (StackPtr.getNode() == 0)
2315         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2316       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2317                                              dl, DAG, VA, Flags));
2318     }
2319   }
2320
2321   if (!MemOpChains.empty())
2322     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2323                         &MemOpChains[0], MemOpChains.size());
2324
2325   if (Subtarget->isPICStyleGOT()) {
2326     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2327     // GOT pointer.
2328     if (!isTailCall) {
2329       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2330                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2331     } else {
2332       // If we are tail calling and generating PIC/GOT style code load the
2333       // address of the callee into ECX. The value in ecx is used as target of
2334       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2335       // for tail calls on PIC/GOT architectures. Normally we would just put the
2336       // address of GOT into ebx and then call target@PLT. But for tail calls
2337       // ebx would be restored (since ebx is callee saved) before jumping to the
2338       // target@PLT.
2339
2340       // Note: The actual moving to ECX is done further down.
2341       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2342       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2343           !G->getGlobal()->hasProtectedVisibility())
2344         Callee = LowerGlobalAddress(Callee, DAG);
2345       else if (isa<ExternalSymbolSDNode>(Callee))
2346         Callee = LowerExternalSymbol(Callee, DAG);
2347     }
2348   }
2349
2350   if (Is64Bit && isVarArg && !IsWin64) {
2351     // From AMD64 ABI document:
2352     // For calls that may call functions that use varargs or stdargs
2353     // (prototype-less calls or calls to functions containing ellipsis (...) in
2354     // the declaration) %al is used as hidden argument to specify the number
2355     // of SSE registers used. The contents of %al do not need to match exactly
2356     // the number of registers, but must be an ubound on the number of SSE
2357     // registers used and is in the range 0 - 8 inclusive.
2358
2359     // Count the number of XMM registers allocated.
2360     static const uint16_t XMMArgRegs[] = {
2361       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2362       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2363     };
2364     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2365     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2366            && "SSE registers cannot be used when SSE is disabled");
2367
2368     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2369                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2370   }
2371
2372   // For tail calls lower the arguments to the 'real' stack slot.
2373   if (isTailCall) {
2374     // Force all the incoming stack arguments to be loaded from the stack
2375     // before any new outgoing arguments are stored to the stack, because the
2376     // outgoing stack slots may alias the incoming argument stack slots, and
2377     // the alias isn't otherwise explicit. This is slightly more conservative
2378     // than necessary, because it means that each store effectively depends
2379     // on every argument instead of just those arguments it would clobber.
2380     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2381
2382     SmallVector<SDValue, 8> MemOpChains2;
2383     SDValue FIN;
2384     int FI = 0;
2385     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2386       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2387         CCValAssign &VA = ArgLocs[i];
2388         if (VA.isRegLoc())
2389           continue;
2390         assert(VA.isMemLoc());
2391         SDValue Arg = OutVals[i];
2392         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2393         // Create frame index.
2394         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2395         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2396         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2397         FIN = DAG.getFrameIndex(FI, getPointerTy());
2398
2399         if (Flags.isByVal()) {
2400           // Copy relative to framepointer.
2401           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2402           if (StackPtr.getNode() == 0)
2403             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2404                                           getPointerTy());
2405           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2406
2407           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2408                                                            ArgChain,
2409                                                            Flags, DAG, dl));
2410         } else {
2411           // Store relative to framepointer.
2412           MemOpChains2.push_back(
2413             DAG.getStore(ArgChain, dl, Arg, FIN,
2414                          MachinePointerInfo::getFixedStack(FI),
2415                          false, false, 0));
2416         }
2417       }
2418     }
2419
2420     if (!MemOpChains2.empty())
2421       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2422                           &MemOpChains2[0], MemOpChains2.size());
2423
2424     // Store the return address to the appropriate stack slot.
2425     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2426                                      FPDiff, dl);
2427   }
2428
2429   // Build a sequence of copy-to-reg nodes chained together with token chain
2430   // and flag operands which copy the outgoing args into registers.
2431   SDValue InFlag;
2432   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2433     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2434                              RegsToPass[i].second, InFlag);
2435     InFlag = Chain.getValue(1);
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 a register mask operand representing the call-preserved registers.
2540   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2541   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2542   assert(Mask && "Missing call preserved mask for calling convention");
2543   Ops.push_back(DAG.getRegisterMask(Mask));
2544
2545   if (InFlag.getNode())
2546     Ops.push_back(InFlag);
2547
2548   if (isTailCall) {
2549     // We used to do:
2550     //// If this is the first return lowered for this function, add the regs
2551     //// to the liveout set for the function.
2552     // This isn't right, although it's probably harmless on x86; liveouts
2553     // should be computed from returns not tail calls.  Consider a void
2554     // function making a tail call to a function returning int.
2555     return DAG.getNode(X86ISD::TC_RETURN, dl,
2556                        NodeTys, &Ops[0], Ops.size());
2557   }
2558
2559   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2560   InFlag = Chain.getValue(1);
2561
2562   // Create the CALLSEQ_END node.
2563   unsigned NumBytesForCalleeToPush;
2564   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2565                        getTargetMachine().Options.GuaranteedTailCallOpt))
2566     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2567   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2568            SR == StackStructReturn)
2569     // If this is a call to a struct-return function, the callee
2570     // pops the hidden struct pointer, so we have to push it back.
2571     // This is common for Darwin/X86, Linux & Mingw32 targets.
2572     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2573     NumBytesForCalleeToPush = 4;
2574   else
2575     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2576
2577   // Returns a flag for retval copy to use.
2578   if (!IsSibcall) {
2579     Chain = DAG.getCALLSEQ_END(Chain,
2580                                DAG.getIntPtrConstant(NumBytes, true),
2581                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2582                                                      true),
2583                                InFlag);
2584     InFlag = Chain.getValue(1);
2585   }
2586
2587   // Handle result values, copying them out of physregs into vregs that we
2588   // return.
2589   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2590                          Ins, dl, DAG, InVals);
2591 }
2592
2593
2594 //===----------------------------------------------------------------------===//
2595 //                Fast Calling Convention (tail call) implementation
2596 //===----------------------------------------------------------------------===//
2597
2598 //  Like std call, callee cleans arguments, convention except that ECX is
2599 //  reserved for storing the tail called function address. Only 2 registers are
2600 //  free for argument passing (inreg). Tail call optimization is performed
2601 //  provided:
2602 //                * tailcallopt is enabled
2603 //                * caller/callee are fastcc
2604 //  On X86_64 architecture with GOT-style position independent code only local
2605 //  (within module) calls are supported at the moment.
2606 //  To keep the stack aligned according to platform abi the function
2607 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2608 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2609 //  If a tail called function callee has more arguments than the caller the
2610 //  caller needs to make sure that there is room to move the RETADDR to. This is
2611 //  achieved by reserving an area the size of the argument delta right after the
2612 //  original REtADDR, but before the saved framepointer or the spilled registers
2613 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2614 //  stack layout:
2615 //    arg1
2616 //    arg2
2617 //    RETADDR
2618 //    [ new RETADDR
2619 //      move area ]
2620 //    (possible EBP)
2621 //    ESI
2622 //    EDI
2623 //    local1 ..
2624
2625 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2626 /// for a 16 byte align requirement.
2627 unsigned
2628 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2629                                                SelectionDAG& DAG) const {
2630   MachineFunction &MF = DAG.getMachineFunction();
2631   const TargetMachine &TM = MF.getTarget();
2632   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2633   unsigned StackAlignment = TFI.getStackAlignment();
2634   uint64_t AlignMask = StackAlignment - 1;
2635   int64_t Offset = StackSize;
2636   uint64_t SlotSize = TD->getPointerSize();
2637   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2638     // Number smaller than 12 so just add the difference.
2639     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2640   } else {
2641     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2642     Offset = ((~AlignMask) & Offset) + StackAlignment +
2643       (StackAlignment-SlotSize);
2644   }
2645   return Offset;
2646 }
2647
2648 /// MatchingStackOffset - Return true if the given stack call argument is
2649 /// already available in the same position (relatively) of the caller's
2650 /// incoming argument stack.
2651 static
2652 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2653                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2654                          const X86InstrInfo *TII) {
2655   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2656   int FI = INT_MAX;
2657   if (Arg.getOpcode() == ISD::CopyFromReg) {
2658     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2659     if (!TargetRegisterInfo::isVirtualRegister(VR))
2660       return false;
2661     MachineInstr *Def = MRI->getVRegDef(VR);
2662     if (!Def)
2663       return false;
2664     if (!Flags.isByVal()) {
2665       if (!TII->isLoadFromStackSlot(Def, FI))
2666         return false;
2667     } else {
2668       unsigned Opcode = Def->getOpcode();
2669       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2670           Def->getOperand(1).isFI()) {
2671         FI = Def->getOperand(1).getIndex();
2672         Bytes = Flags.getByValSize();
2673       } else
2674         return false;
2675     }
2676   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2677     if (Flags.isByVal())
2678       // ByVal argument is passed in as a pointer but it's now being
2679       // dereferenced. e.g.
2680       // define @foo(%struct.X* %A) {
2681       //   tail call @bar(%struct.X* byval %A)
2682       // }
2683       return false;
2684     SDValue Ptr = Ld->getBasePtr();
2685     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2686     if (!FINode)
2687       return false;
2688     FI = FINode->getIndex();
2689   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2690     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2691     FI = FINode->getIndex();
2692     Bytes = Flags.getByValSize();
2693   } else
2694     return false;
2695
2696   assert(FI != INT_MAX);
2697   if (!MFI->isFixedObjectIndex(FI))
2698     return false;
2699   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2700 }
2701
2702 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2703 /// for tail call optimization. Targets which want to do tail call
2704 /// optimization should implement this function.
2705 bool
2706 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2707                                                      CallingConv::ID CalleeCC,
2708                                                      bool isVarArg,
2709                                                      bool isCalleeStructRet,
2710                                                      bool isCallerStructRet,
2711                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2712                                     const SmallVectorImpl<SDValue> &OutVals,
2713                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2714                                                      SelectionDAG& DAG) const {
2715   if (!IsTailCallConvention(CalleeCC) &&
2716       CalleeCC != CallingConv::C)
2717     return false;
2718
2719   // If -tailcallopt is specified, make fastcc functions tail-callable.
2720   const MachineFunction &MF = DAG.getMachineFunction();
2721   const Function *CallerF = DAG.getMachineFunction().getFunction();
2722   CallingConv::ID CallerCC = CallerF->getCallingConv();
2723   bool CCMatch = CallerCC == CalleeCC;
2724
2725   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2726     if (IsTailCallConvention(CalleeCC) && CCMatch)
2727       return true;
2728     return false;
2729   }
2730
2731   // Look for obvious safe cases to perform tail call optimization that do not
2732   // require ABI changes. This is what gcc calls sibcall.
2733
2734   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2735   // emit a special epilogue.
2736   if (RegInfo->needsStackRealignment(MF))
2737     return false;
2738
2739   // Also avoid sibcall optimization if either caller or callee uses struct
2740   // return semantics.
2741   if (isCalleeStructRet || isCallerStructRet)
2742     return false;
2743
2744   // An stdcall caller is expected to clean up its arguments; the callee
2745   // isn't going to do that.
2746   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2747     return false;
2748
2749   // Do not sibcall optimize vararg calls unless all arguments are passed via
2750   // registers.
2751   if (isVarArg && !Outs.empty()) {
2752
2753     // Optimizing for varargs on Win64 is unlikely to be safe without
2754     // additional testing.
2755     if (Subtarget->isTargetWin64())
2756       return false;
2757
2758     SmallVector<CCValAssign, 16> ArgLocs;
2759     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2760                    getTargetMachine(), ArgLocs, *DAG.getContext());
2761
2762     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2763     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2764       if (!ArgLocs[i].isRegLoc())
2765         return false;
2766   }
2767
2768   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2769   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2770   // this into a sibcall.
2771   bool Unused = false;
2772   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2773     if (!Ins[i].Used) {
2774       Unused = true;
2775       break;
2776     }
2777   }
2778   if (Unused) {
2779     SmallVector<CCValAssign, 16> RVLocs;
2780     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2781                    getTargetMachine(), RVLocs, *DAG.getContext());
2782     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2783     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2784       CCValAssign &VA = RVLocs[i];
2785       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2786         return false;
2787     }
2788   }
2789
2790   // If the calling conventions do not match, then we'd better make sure the
2791   // results are returned in the same way as what the caller expects.
2792   if (!CCMatch) {
2793     SmallVector<CCValAssign, 16> RVLocs1;
2794     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2795                     getTargetMachine(), RVLocs1, *DAG.getContext());
2796     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2797
2798     SmallVector<CCValAssign, 16> RVLocs2;
2799     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2800                     getTargetMachine(), RVLocs2, *DAG.getContext());
2801     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2802
2803     if (RVLocs1.size() != RVLocs2.size())
2804       return false;
2805     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2806       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2807         return false;
2808       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2809         return false;
2810       if (RVLocs1[i].isRegLoc()) {
2811         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2812           return false;
2813       } else {
2814         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2815           return false;
2816       }
2817     }
2818   }
2819
2820   // If the callee takes no arguments then go on to check the results of the
2821   // call.
2822   if (!Outs.empty()) {
2823     // Check if stack adjustment is needed. For now, do not do this if any
2824     // argument is passed on the stack.
2825     SmallVector<CCValAssign, 16> ArgLocs;
2826     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2827                    getTargetMachine(), ArgLocs, *DAG.getContext());
2828
2829     // Allocate shadow area for Win64
2830     if (Subtarget->isTargetWin64()) {
2831       CCInfo.AllocateStack(32, 8);
2832     }
2833
2834     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2835     if (CCInfo.getNextStackOffset()) {
2836       MachineFunction &MF = DAG.getMachineFunction();
2837       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2838         return false;
2839
2840       // Check if the arguments are already laid out in the right way as
2841       // the caller's fixed stack objects.
2842       MachineFrameInfo *MFI = MF.getFrameInfo();
2843       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2844       const X86InstrInfo *TII =
2845         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2846       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2847         CCValAssign &VA = ArgLocs[i];
2848         SDValue Arg = OutVals[i];
2849         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2850         if (VA.getLocInfo() == CCValAssign::Indirect)
2851           return false;
2852         if (!VA.isRegLoc()) {
2853           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2854                                    MFI, MRI, TII))
2855             return false;
2856         }
2857       }
2858     }
2859
2860     // If the tailcall address may be in a register, then make sure it's
2861     // possible to register allocate for it. In 32-bit, the call address can
2862     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2863     // callee-saved registers are restored. These happen to be the same
2864     // registers used to pass 'inreg' arguments so watch out for those.
2865     if (!Subtarget->is64Bit() &&
2866         !isa<GlobalAddressSDNode>(Callee) &&
2867         !isa<ExternalSymbolSDNode>(Callee)) {
2868       unsigned NumInRegs = 0;
2869       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2870         CCValAssign &VA = ArgLocs[i];
2871         if (!VA.isRegLoc())
2872           continue;
2873         unsigned Reg = VA.getLocReg();
2874         switch (Reg) {
2875         default: break;
2876         case X86::EAX: case X86::EDX: case X86::ECX:
2877           if (++NumInRegs == 3)
2878             return false;
2879           break;
2880         }
2881       }
2882     }
2883   }
2884
2885   return true;
2886 }
2887
2888 FastISel *
2889 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2890                                   const TargetLibraryInfo *libInfo) const {
2891   return X86::createFastISel(funcInfo, libInfo);
2892 }
2893
2894
2895 //===----------------------------------------------------------------------===//
2896 //                           Other Lowering Hooks
2897 //===----------------------------------------------------------------------===//
2898
2899 static bool MayFoldLoad(SDValue Op) {
2900   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2901 }
2902
2903 static bool MayFoldIntoStore(SDValue Op) {
2904   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2905 }
2906
2907 static bool isTargetShuffle(unsigned Opcode) {
2908   switch(Opcode) {
2909   default: return false;
2910   case X86ISD::PSHUFD:
2911   case X86ISD::PSHUFHW:
2912   case X86ISD::PSHUFLW:
2913   case X86ISD::SHUFP:
2914   case X86ISD::PALIGN:
2915   case X86ISD::MOVLHPS:
2916   case X86ISD::MOVLHPD:
2917   case X86ISD::MOVHLPS:
2918   case X86ISD::MOVLPS:
2919   case X86ISD::MOVLPD:
2920   case X86ISD::MOVSHDUP:
2921   case X86ISD::MOVSLDUP:
2922   case X86ISD::MOVDDUP:
2923   case X86ISD::MOVSS:
2924   case X86ISD::MOVSD:
2925   case X86ISD::UNPCKL:
2926   case X86ISD::UNPCKH:
2927   case X86ISD::VPERMILP:
2928   case X86ISD::VPERM2X128:
2929   case X86ISD::VPERMI:
2930     return true;
2931   }
2932 }
2933
2934 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2935                                     SDValue V1, SelectionDAG &DAG) {
2936   switch(Opc) {
2937   default: llvm_unreachable("Unknown x86 shuffle node");
2938   case X86ISD::MOVSHDUP:
2939   case X86ISD::MOVSLDUP:
2940   case X86ISD::MOVDDUP:
2941     return DAG.getNode(Opc, dl, VT, V1);
2942   }
2943 }
2944
2945 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2946                                     SDValue V1, unsigned TargetMask,
2947                                     SelectionDAG &DAG) {
2948   switch(Opc) {
2949   default: llvm_unreachable("Unknown x86 shuffle node");
2950   case X86ISD::PSHUFD:
2951   case X86ISD::PSHUFHW:
2952   case X86ISD::PSHUFLW:
2953   case X86ISD::VPERMILP:
2954   case X86ISD::VPERMI:
2955     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2956   }
2957 }
2958
2959 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2960                                     SDValue V1, SDValue V2, unsigned TargetMask,
2961                                     SelectionDAG &DAG) {
2962   switch(Opc) {
2963   default: llvm_unreachable("Unknown x86 shuffle node");
2964   case X86ISD::PALIGN:
2965   case X86ISD::SHUFP:
2966   case X86ISD::VPERM2X128:
2967     return DAG.getNode(Opc, dl, VT, V1, V2,
2968                        DAG.getConstant(TargetMask, MVT::i8));
2969   }
2970 }
2971
2972 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2973                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2974   switch(Opc) {
2975   default: llvm_unreachable("Unknown x86 shuffle node");
2976   case X86ISD::MOVLHPS:
2977   case X86ISD::MOVLHPD:
2978   case X86ISD::MOVHLPS:
2979   case X86ISD::MOVLPS:
2980   case X86ISD::MOVLPD:
2981   case X86ISD::MOVSS:
2982   case X86ISD::MOVSD:
2983   case X86ISD::UNPCKL:
2984   case X86ISD::UNPCKH:
2985     return DAG.getNode(Opc, dl, VT, V1, V2);
2986   }
2987 }
2988
2989 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2990   MachineFunction &MF = DAG.getMachineFunction();
2991   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2992   int ReturnAddrIndex = FuncInfo->getRAIndex();
2993
2994   if (ReturnAddrIndex == 0) {
2995     // Set up a frame object for the return address.
2996     uint64_t SlotSize = TD->getPointerSize();
2997     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2998                                                            false);
2999     FuncInfo->setRAIndex(ReturnAddrIndex);
3000   }
3001
3002   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3003 }
3004
3005
3006 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3007                                        bool hasSymbolicDisplacement) {
3008   // Offset should fit into 32 bit immediate field.
3009   if (!isInt<32>(Offset))
3010     return false;
3011
3012   // If we don't have a symbolic displacement - we don't have any extra
3013   // restrictions.
3014   if (!hasSymbolicDisplacement)
3015     return true;
3016
3017   // FIXME: Some tweaks might be needed for medium code model.
3018   if (M != CodeModel::Small && M != CodeModel::Kernel)
3019     return false;
3020
3021   // For small code model we assume that latest object is 16MB before end of 31
3022   // bits boundary. We may also accept pretty large negative constants knowing
3023   // that all objects are in the positive half of address space.
3024   if (M == CodeModel::Small && Offset < 16*1024*1024)
3025     return true;
3026
3027   // For kernel code model we know that all object resist in the negative half
3028   // of 32bits address space. We may not accept negative offsets, since they may
3029   // be just off and we may accept pretty large positive ones.
3030   if (M == CodeModel::Kernel && Offset > 0)
3031     return true;
3032
3033   return false;
3034 }
3035
3036 /// isCalleePop - Determines whether the callee is required to pop its
3037 /// own arguments. Callee pop is necessary to support tail calls.
3038 bool X86::isCalleePop(CallingConv::ID CallingConv,
3039                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3040   if (IsVarArg)
3041     return false;
3042
3043   switch (CallingConv) {
3044   default:
3045     return false;
3046   case CallingConv::X86_StdCall:
3047     return !is64Bit;
3048   case CallingConv::X86_FastCall:
3049     return !is64Bit;
3050   case CallingConv::X86_ThisCall:
3051     return !is64Bit;
3052   case CallingConv::Fast:
3053     return TailCallOpt;
3054   case CallingConv::GHC:
3055     return TailCallOpt;
3056   }
3057 }
3058
3059 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3060 /// specific condition code, returning the condition code and the LHS/RHS of the
3061 /// comparison to make.
3062 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3063                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3064   if (!isFP) {
3065     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3066       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3067         // X > -1   -> X == 0, jump !sign.
3068         RHS = DAG.getConstant(0, RHS.getValueType());
3069         return X86::COND_NS;
3070       }
3071       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3072         // X < 0   -> X == 0, jump on sign.
3073         return X86::COND_S;
3074       }
3075       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3076         // X < 1   -> X <= 0
3077         RHS = DAG.getConstant(0, RHS.getValueType());
3078         return X86::COND_LE;
3079       }
3080     }
3081
3082     switch (SetCCOpcode) {
3083     default: llvm_unreachable("Invalid integer condition!");
3084     case ISD::SETEQ:  return X86::COND_E;
3085     case ISD::SETGT:  return X86::COND_G;
3086     case ISD::SETGE:  return X86::COND_GE;
3087     case ISD::SETLT:  return X86::COND_L;
3088     case ISD::SETLE:  return X86::COND_LE;
3089     case ISD::SETNE:  return X86::COND_NE;
3090     case ISD::SETULT: return X86::COND_B;
3091     case ISD::SETUGT: return X86::COND_A;
3092     case ISD::SETULE: return X86::COND_BE;
3093     case ISD::SETUGE: return X86::COND_AE;
3094     }
3095   }
3096
3097   // First determine if it is required or is profitable to flip the operands.
3098
3099   // If LHS is a foldable load, but RHS is not, flip the condition.
3100   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3101       !ISD::isNON_EXTLoad(RHS.getNode())) {
3102     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3103     std::swap(LHS, RHS);
3104   }
3105
3106   switch (SetCCOpcode) {
3107   default: break;
3108   case ISD::SETOLT:
3109   case ISD::SETOLE:
3110   case ISD::SETUGT:
3111   case ISD::SETUGE:
3112     std::swap(LHS, RHS);
3113     break;
3114   }
3115
3116   // On a floating point condition, the flags are set as follows:
3117   // ZF  PF  CF   op
3118   //  0 | 0 | 0 | X > Y
3119   //  0 | 0 | 1 | X < Y
3120   //  1 | 0 | 0 | X == Y
3121   //  1 | 1 | 1 | unordered
3122   switch (SetCCOpcode) {
3123   default: llvm_unreachable("Condcode should be pre-legalized away");
3124   case ISD::SETUEQ:
3125   case ISD::SETEQ:   return X86::COND_E;
3126   case ISD::SETOLT:              // flipped
3127   case ISD::SETOGT:
3128   case ISD::SETGT:   return X86::COND_A;
3129   case ISD::SETOLE:              // flipped
3130   case ISD::SETOGE:
3131   case ISD::SETGE:   return X86::COND_AE;
3132   case ISD::SETUGT:              // flipped
3133   case ISD::SETULT:
3134   case ISD::SETLT:   return X86::COND_B;
3135   case ISD::SETUGE:              // flipped
3136   case ISD::SETULE:
3137   case ISD::SETLE:   return X86::COND_BE;
3138   case ISD::SETONE:
3139   case ISD::SETNE:   return X86::COND_NE;
3140   case ISD::SETUO:   return X86::COND_P;
3141   case ISD::SETO:    return X86::COND_NP;
3142   case ISD::SETOEQ:
3143   case ISD::SETUNE:  return X86::COND_INVALID;
3144   }
3145 }
3146
3147 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3148 /// code. Current x86 isa includes the following FP cmov instructions:
3149 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3150 static bool hasFPCMov(unsigned X86CC) {
3151   switch (X86CC) {
3152   default:
3153     return false;
3154   case X86::COND_B:
3155   case X86::COND_BE:
3156   case X86::COND_E:
3157   case X86::COND_P:
3158   case X86::COND_A:
3159   case X86::COND_AE:
3160   case X86::COND_NE:
3161   case X86::COND_NP:
3162     return true;
3163   }
3164 }
3165
3166 /// isFPImmLegal - Returns true if the target can instruction select the
3167 /// specified FP immediate natively. If false, the legalizer will
3168 /// materialize the FP immediate as a load from a constant pool.
3169 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3170   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3171     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3172       return true;
3173   }
3174   return false;
3175 }
3176
3177 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3178 /// the specified range (L, H].
3179 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3180   return (Val < 0) || (Val >= Low && Val < Hi);
3181 }
3182
3183 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3184 /// specified value.
3185 static bool isUndefOrEqual(int Val, int CmpVal) {
3186   if (Val < 0 || Val == CmpVal)
3187     return true;
3188   return false;
3189 }
3190
3191 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3192 /// from position Pos and ending in Pos+Size, falls within the specified
3193 /// sequential range (L, L+Pos]. or is undef.
3194 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3195                                        unsigned Pos, unsigned Size, int Low) {
3196   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3197     if (!isUndefOrEqual(Mask[i], Low))
3198       return false;
3199   return true;
3200 }
3201
3202 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3203 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3204 /// the second operand.
3205 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3206   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3207     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3208   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3209     return (Mask[0] < 2 && Mask[1] < 2);
3210   return false;
3211 }
3212
3213 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3214 /// is suitable for input to PSHUFHW.
3215 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3216   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3217     return false;
3218
3219   // Lower quadword copied in order or undef.
3220   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3221     return false;
3222
3223   // Upper quadword shuffled.
3224   for (unsigned i = 4; i != 8; ++i)
3225     if (!isUndefOrInRange(Mask[i], 4, 8))
3226       return false;
3227
3228   if (VT == MVT::v16i16) {
3229     // Lower quadword copied in order or undef.
3230     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3231       return false;
3232
3233     // Upper quadword shuffled.
3234     for (unsigned i = 12; i != 16; ++i)
3235       if (!isUndefOrInRange(Mask[i], 12, 16))
3236         return false;
3237   }
3238
3239   return true;
3240 }
3241
3242 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3243 /// is suitable for input to PSHUFLW.
3244 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3245   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3246     return false;
3247
3248   // Upper quadword copied in order.
3249   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3250     return false;
3251
3252   // Lower quadword shuffled.
3253   for (unsigned i = 0; i != 4; ++i)
3254     if (!isUndefOrInRange(Mask[i], 0, 4))
3255       return false;
3256
3257   if (VT == MVT::v16i16) {
3258     // Upper quadword copied in order.
3259     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3260       return false;
3261
3262     // Lower quadword shuffled.
3263     for (unsigned i = 8; i != 12; ++i)
3264       if (!isUndefOrInRange(Mask[i], 8, 12))
3265         return false;
3266   }
3267
3268   return true;
3269 }
3270
3271 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3272 /// is suitable for input to PALIGNR.
3273 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3274                           const X86Subtarget *Subtarget) {
3275   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3276       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3277     return false;
3278
3279   unsigned NumElts = VT.getVectorNumElements();
3280   unsigned NumLanes = VT.getSizeInBits()/128;
3281   unsigned NumLaneElts = NumElts/NumLanes;
3282
3283   // Do not handle 64-bit element shuffles with palignr.
3284   if (NumLaneElts == 2)
3285     return false;
3286
3287   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3288     unsigned i;
3289     for (i = 0; i != NumLaneElts; ++i) {
3290       if (Mask[i+l] >= 0)
3291         break;
3292     }
3293
3294     // Lane is all undef, go to next lane
3295     if (i == NumLaneElts)
3296       continue;
3297
3298     int Start = Mask[i+l];
3299
3300     // Make sure its in this lane in one of the sources
3301     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3302         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3303       return false;
3304
3305     // If not lane 0, then we must match lane 0
3306     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3307       return false;
3308
3309     // Correct second source to be contiguous with first source
3310     if (Start >= (int)NumElts)
3311       Start -= NumElts - NumLaneElts;
3312
3313     // Make sure we're shifting in the right direction.
3314     if (Start <= (int)(i+l))
3315       return false;
3316
3317     Start -= i;
3318
3319     // Check the rest of the elements to see if they are consecutive.
3320     for (++i; i != NumLaneElts; ++i) {
3321       int Idx = Mask[i+l];
3322
3323       // Make sure its in this lane
3324       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3325           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3326         return false;
3327
3328       // If not lane 0, then we must match lane 0
3329       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3330         return false;
3331
3332       if (Idx >= (int)NumElts)
3333         Idx -= NumElts - NumLaneElts;
3334
3335       if (!isUndefOrEqual(Idx, Start+i))
3336         return false;
3337
3338     }
3339   }
3340
3341   return true;
3342 }
3343
3344 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3345 /// the two vector operands have swapped position.
3346 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3347                                      unsigned NumElems) {
3348   for (unsigned i = 0; i != NumElems; ++i) {
3349     int idx = Mask[i];
3350     if (idx < 0)
3351       continue;
3352     else if (idx < (int)NumElems)
3353       Mask[i] = idx + NumElems;
3354     else
3355       Mask[i] = idx - NumElems;
3356   }
3357 }
3358
3359 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3360 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3361 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3362 /// reverse of what x86 shuffles want.
3363 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3364                         bool Commuted = false) {
3365   if (!HasAVX && VT.getSizeInBits() == 256)
3366     return false;
3367
3368   unsigned NumElems = VT.getVectorNumElements();
3369   unsigned NumLanes = VT.getSizeInBits()/128;
3370   unsigned NumLaneElems = NumElems/NumLanes;
3371
3372   if (NumLaneElems != 2 && NumLaneElems != 4)
3373     return false;
3374
3375   // VSHUFPSY divides the resulting vector into 4 chunks.
3376   // The sources are also splitted into 4 chunks, and each destination
3377   // chunk must come from a different source chunk.
3378   //
3379   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3380   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3381   //
3382   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3383   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3384   //
3385   // VSHUFPDY divides the resulting vector into 4 chunks.
3386   // The sources are also splitted into 4 chunks, and each destination
3387   // chunk must come from a different source chunk.
3388   //
3389   //  SRC1 =>      X3       X2       X1       X0
3390   //  SRC2 =>      Y3       Y2       Y1       Y0
3391   //
3392   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3393   //
3394   unsigned HalfLaneElems = NumLaneElems/2;
3395   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3396     for (unsigned i = 0; i != NumLaneElems; ++i) {
3397       int Idx = Mask[i+l];
3398       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3399       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3400         return false;
3401       // For VSHUFPSY, the mask of the second half must be the same as the
3402       // first but with the appropriate offsets. This works in the same way as
3403       // VPERMILPS works with masks.
3404       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3405         continue;
3406       if (!isUndefOrEqual(Idx, Mask[i]+l))
3407         return false;
3408     }
3409   }
3410
3411   return true;
3412 }
3413
3414 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3415 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3416 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3417   unsigned NumElems = VT.getVectorNumElements();
3418
3419   if (VT.getSizeInBits() != 128)
3420     return false;
3421
3422   if (NumElems != 4)
3423     return false;
3424
3425   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3426   return isUndefOrEqual(Mask[0], 6) &&
3427          isUndefOrEqual(Mask[1], 7) &&
3428          isUndefOrEqual(Mask[2], 2) &&
3429          isUndefOrEqual(Mask[3], 3);
3430 }
3431
3432 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3433 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3434 /// <2, 3, 2, 3>
3435 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3436   unsigned NumElems = VT.getVectorNumElements();
3437
3438   if (VT.getSizeInBits() != 128)
3439     return false;
3440
3441   if (NumElems != 4)
3442     return false;
3443
3444   return isUndefOrEqual(Mask[0], 2) &&
3445          isUndefOrEqual(Mask[1], 3) &&
3446          isUndefOrEqual(Mask[2], 2) &&
3447          isUndefOrEqual(Mask[3], 3);
3448 }
3449
3450 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3451 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3452 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3453   if (VT.getSizeInBits() != 128)
3454     return false;
3455
3456   unsigned NumElems = VT.getVectorNumElements();
3457
3458   if (NumElems != 2 && NumElems != 4)
3459     return false;
3460
3461   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3462     if (!isUndefOrEqual(Mask[i], i + NumElems))
3463       return false;
3464
3465   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3466     if (!isUndefOrEqual(Mask[i], i))
3467       return false;
3468
3469   return true;
3470 }
3471
3472 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3473 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3474 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3475   unsigned NumElems = VT.getVectorNumElements();
3476
3477   if ((NumElems != 2 && NumElems != 4)
3478       || VT.getSizeInBits() > 128)
3479     return false;
3480
3481   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3482     if (!isUndefOrEqual(Mask[i], i))
3483       return false;
3484
3485   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3486     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3487       return false;
3488
3489   return true;
3490 }
3491
3492 //
3493 // Some special combinations that can be optimized.
3494 //
3495 static
3496 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3497                                SelectionDAG &DAG) {
3498   EVT VT = SVOp->getValueType(0);
3499   DebugLoc dl = SVOp->getDebugLoc();
3500
3501   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3502     return SDValue();
3503
3504   ArrayRef<int> Mask = SVOp->getMask();
3505
3506   // These are the special masks that may be optimized.
3507   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3508   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3509   bool MatchEvenMask = true;
3510   bool MatchOddMask  = true;
3511   for (int i=0; i<8; ++i) {
3512     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3513       MatchEvenMask = false;
3514     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3515       MatchOddMask = false;
3516   }
3517   static const int CompactionMaskEven[] = {0, 2, -1, -1, 4, 6, -1, -1};
3518   static const int CompactionMaskOdd [] = {1, 3, -1, -1, 5, 7, -1, -1};
3519
3520   const int *CompactionMask;
3521   if (MatchEvenMask)
3522     CompactionMask = CompactionMaskEven;
3523   else if (MatchOddMask)
3524     CompactionMask = CompactionMaskOdd;
3525   else
3526     return SDValue();
3527
3528   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3529
3530   SDValue Op0 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(0),
3531                                      UndefNode, CompactionMask);
3532   SDValue Op1 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(1),
3533                                      UndefNode, CompactionMask);
3534   static const int UnpackMask[] = {0, 8, 1, 9, 4, 12, 5, 13};
3535   return DAG.getVectorShuffle(VT, dl, Op0, Op1, UnpackMask);
3536 }
3537
3538 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3539 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3540 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3541                          bool HasAVX2, bool V2IsSplat = false) {
3542   unsigned NumElts = VT.getVectorNumElements();
3543
3544   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3545          "Unsupported vector type for unpckh");
3546
3547   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3548       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3549     return false;
3550
3551   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3552   // independently on 128-bit lanes.
3553   unsigned NumLanes = VT.getSizeInBits()/128;
3554   unsigned NumLaneElts = NumElts/NumLanes;
3555
3556   for (unsigned l = 0; l != NumLanes; ++l) {
3557     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3558          i != (l+1)*NumLaneElts;
3559          i += 2, ++j) {
3560       int BitI  = Mask[i];
3561       int BitI1 = Mask[i+1];
3562       if (!isUndefOrEqual(BitI, j))
3563         return false;
3564       if (V2IsSplat) {
3565         if (!isUndefOrEqual(BitI1, NumElts))
3566           return false;
3567       } else {
3568         if (!isUndefOrEqual(BitI1, j + NumElts))
3569           return false;
3570       }
3571     }
3572   }
3573
3574   return true;
3575 }
3576
3577 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3578 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3579 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3580                          bool HasAVX2, bool V2IsSplat = false) {
3581   unsigned NumElts = VT.getVectorNumElements();
3582
3583   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3584          "Unsupported vector type for unpckh");
3585
3586   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3587       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3588     return false;
3589
3590   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3591   // independently on 128-bit lanes.
3592   unsigned NumLanes = VT.getSizeInBits()/128;
3593   unsigned NumLaneElts = NumElts/NumLanes;
3594
3595   for (unsigned l = 0; l != NumLanes; ++l) {
3596     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3597          i != (l+1)*NumLaneElts; i += 2, ++j) {
3598       int BitI  = Mask[i];
3599       int BitI1 = Mask[i+1];
3600       if (!isUndefOrEqual(BitI, j))
3601         return false;
3602       if (V2IsSplat) {
3603         if (isUndefOrEqual(BitI1, NumElts))
3604           return false;
3605       } else {
3606         if (!isUndefOrEqual(BitI1, j+NumElts))
3607           return false;
3608       }
3609     }
3610   }
3611   return true;
3612 }
3613
3614 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3615 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3616 /// <0, 0, 1, 1>
3617 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3618                                   bool HasAVX2) {
3619   unsigned NumElts = VT.getVectorNumElements();
3620
3621   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3622          "Unsupported vector type for unpckh");
3623
3624   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3625       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3626     return false;
3627
3628   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3629   // FIXME: Need a better way to get rid of this, there's no latency difference
3630   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3631   // the former later. We should also remove the "_undef" special mask.
3632   if (NumElts == 4 && VT.getSizeInBits() == 256)
3633     return false;
3634
3635   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3636   // independently on 128-bit lanes.
3637   unsigned NumLanes = VT.getSizeInBits()/128;
3638   unsigned NumLaneElts = NumElts/NumLanes;
3639
3640   for (unsigned l = 0; l != NumLanes; ++l) {
3641     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3642          i != (l+1)*NumLaneElts;
3643          i += 2, ++j) {
3644       int BitI  = Mask[i];
3645       int BitI1 = Mask[i+1];
3646
3647       if (!isUndefOrEqual(BitI, j))
3648         return false;
3649       if (!isUndefOrEqual(BitI1, j))
3650         return false;
3651     }
3652   }
3653
3654   return true;
3655 }
3656
3657 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3658 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3659 /// <2, 2, 3, 3>
3660 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3661   unsigned NumElts = VT.getVectorNumElements();
3662
3663   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3664          "Unsupported vector type for unpckh");
3665
3666   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3667       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3668     return false;
3669
3670   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3671   // independently on 128-bit lanes.
3672   unsigned NumLanes = VT.getSizeInBits()/128;
3673   unsigned NumLaneElts = NumElts/NumLanes;
3674
3675   for (unsigned l = 0; l != NumLanes; ++l) {
3676     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3677          i != (l+1)*NumLaneElts; i += 2, ++j) {
3678       int BitI  = Mask[i];
3679       int BitI1 = Mask[i+1];
3680       if (!isUndefOrEqual(BitI, j))
3681         return false;
3682       if (!isUndefOrEqual(BitI1, j))
3683         return false;
3684     }
3685   }
3686   return true;
3687 }
3688
3689 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3690 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3691 /// MOVSD, and MOVD, i.e. setting the lowest element.
3692 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3693   if (VT.getVectorElementType().getSizeInBits() < 32)
3694     return false;
3695   if (VT.getSizeInBits() == 256)
3696     return false;
3697
3698   unsigned NumElts = VT.getVectorNumElements();
3699
3700   if (!isUndefOrEqual(Mask[0], NumElts))
3701     return false;
3702
3703   for (unsigned i = 1; i != NumElts; ++i)
3704     if (!isUndefOrEqual(Mask[i], i))
3705       return false;
3706
3707   return true;
3708 }
3709
3710 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3711 /// as permutations between 128-bit chunks or halves. As an example: this
3712 /// shuffle bellow:
3713 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3714 /// The first half comes from the second half of V1 and the second half from the
3715 /// the second half of V2.
3716 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3717   if (!HasAVX || VT.getSizeInBits() != 256)
3718     return false;
3719
3720   // The shuffle result is divided into half A and half B. In total the two
3721   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3722   // B must come from C, D, E or F.
3723   unsigned HalfSize = VT.getVectorNumElements()/2;
3724   bool MatchA = false, MatchB = false;
3725
3726   // Check if A comes from one of C, D, E, F.
3727   for (unsigned Half = 0; Half != 4; ++Half) {
3728     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3729       MatchA = true;
3730       break;
3731     }
3732   }
3733
3734   // Check if B comes from one of C, D, E, F.
3735   for (unsigned Half = 0; Half != 4; ++Half) {
3736     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3737       MatchB = true;
3738       break;
3739     }
3740   }
3741
3742   return MatchA && MatchB;
3743 }
3744
3745 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3746 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3747 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3748   EVT VT = SVOp->getValueType(0);
3749
3750   unsigned HalfSize = VT.getVectorNumElements()/2;
3751
3752   unsigned FstHalf = 0, SndHalf = 0;
3753   for (unsigned i = 0; i < HalfSize; ++i) {
3754     if (SVOp->getMaskElt(i) > 0) {
3755       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3756       break;
3757     }
3758   }
3759   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3760     if (SVOp->getMaskElt(i) > 0) {
3761       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3762       break;
3763     }
3764   }
3765
3766   return (FstHalf | (SndHalf << 4));
3767 }
3768
3769 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3770 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3771 /// Note that VPERMIL mask matching is different depending whether theunderlying
3772 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3773 /// to the same elements of the low, but to the higher half of the source.
3774 /// In VPERMILPD the two lanes could be shuffled independently of each other
3775 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3776 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3777   if (!HasAVX)
3778     return false;
3779
3780   unsigned NumElts = VT.getVectorNumElements();
3781   // Only match 256-bit with 32/64-bit types
3782   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3783     return false;
3784
3785   unsigned NumLanes = VT.getSizeInBits()/128;
3786   unsigned LaneSize = NumElts/NumLanes;
3787   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3788     for (unsigned i = 0; i != LaneSize; ++i) {
3789       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3790         return false;
3791       if (NumElts != 8 || l == 0)
3792         continue;
3793       // VPERMILPS handling
3794       if (Mask[i] < 0)
3795         continue;
3796       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3797         return false;
3798     }
3799   }
3800
3801   return true;
3802 }
3803
3804 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3805 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3806 /// element of vector 2 and the other elements to come from vector 1 in order.
3807 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3808                                bool V2IsSplat = false, bool V2IsUndef = false) {
3809   unsigned NumOps = VT.getVectorNumElements();
3810   if (VT.getSizeInBits() == 256)
3811     return false;
3812   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3813     return false;
3814
3815   if (!isUndefOrEqual(Mask[0], 0))
3816     return false;
3817
3818   for (unsigned i = 1; i != NumOps; ++i)
3819     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3820           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3821           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3822       return false;
3823
3824   return true;
3825 }
3826
3827 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3828 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3829 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3830 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3831                            const X86Subtarget *Subtarget) {
3832   if (!Subtarget->hasSSE3())
3833     return false;
3834
3835   unsigned NumElems = VT.getVectorNumElements();
3836
3837   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3838       (VT.getSizeInBits() == 256 && NumElems != 8))
3839     return false;
3840
3841   // "i+1" is the value the indexed mask element must have
3842   for (unsigned i = 0; i != NumElems; i += 2)
3843     if (!isUndefOrEqual(Mask[i], i+1) ||
3844         !isUndefOrEqual(Mask[i+1], i+1))
3845       return false;
3846
3847   return true;
3848 }
3849
3850 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3851 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3852 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3853 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3854                            const X86Subtarget *Subtarget) {
3855   if (!Subtarget->hasSSE3())
3856     return false;
3857
3858   unsigned NumElems = VT.getVectorNumElements();
3859
3860   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3861       (VT.getSizeInBits() == 256 && NumElems != 8))
3862     return false;
3863
3864   // "i" is the value the indexed mask element must have
3865   for (unsigned i = 0; i != NumElems; i += 2)
3866     if (!isUndefOrEqual(Mask[i], i) ||
3867         !isUndefOrEqual(Mask[i+1], i))
3868       return false;
3869
3870   return true;
3871 }
3872
3873 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3874 /// specifies a shuffle of elements that is suitable for input to 256-bit
3875 /// version of MOVDDUP.
3876 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3877   unsigned NumElts = VT.getVectorNumElements();
3878
3879   if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3880     return false;
3881
3882   for (unsigned i = 0; i != NumElts/2; ++i)
3883     if (!isUndefOrEqual(Mask[i], 0))
3884       return false;
3885   for (unsigned i = NumElts/2; i != NumElts; ++i)
3886     if (!isUndefOrEqual(Mask[i], NumElts/2))
3887       return false;
3888   return true;
3889 }
3890
3891 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3892 /// specifies a shuffle of elements that is suitable for input to 128-bit
3893 /// version of MOVDDUP.
3894 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3895   if (VT.getSizeInBits() != 128)
3896     return false;
3897
3898   unsigned e = VT.getVectorNumElements() / 2;
3899   for (unsigned i = 0; i != e; ++i)
3900     if (!isUndefOrEqual(Mask[i], i))
3901       return false;
3902   for (unsigned i = 0; i != e; ++i)
3903     if (!isUndefOrEqual(Mask[e+i], i))
3904       return false;
3905   return true;
3906 }
3907
3908 /// isVEXTRACTF128Index - Return true if the specified
3909 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3910 /// suitable for input to VEXTRACTF128.
3911 bool X86::isVEXTRACTF128Index(SDNode *N) {
3912   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3913     return false;
3914
3915   // The index should be aligned on a 128-bit boundary.
3916   uint64_t Index =
3917     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3918
3919   unsigned VL = N->getValueType(0).getVectorNumElements();
3920   unsigned VBits = N->getValueType(0).getSizeInBits();
3921   unsigned ElSize = VBits / VL;
3922   bool Result = (Index * ElSize) % 128 == 0;
3923
3924   return Result;
3925 }
3926
3927 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3928 /// operand specifies a subvector insert that is suitable for input to
3929 /// VINSERTF128.
3930 bool X86::isVINSERTF128Index(SDNode *N) {
3931   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3932     return false;
3933
3934   // The index should be aligned on a 128-bit boundary.
3935   uint64_t Index =
3936     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3937
3938   unsigned VL = N->getValueType(0).getVectorNumElements();
3939   unsigned VBits = N->getValueType(0).getSizeInBits();
3940   unsigned ElSize = VBits / VL;
3941   bool Result = (Index * ElSize) % 128 == 0;
3942
3943   return Result;
3944 }
3945
3946 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3947 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3948 /// Handles 128-bit and 256-bit.
3949 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3950   EVT VT = N->getValueType(0);
3951
3952   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3953          "Unsupported vector type for PSHUF/SHUFP");
3954
3955   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3956   // independently on 128-bit lanes.
3957   unsigned NumElts = VT.getVectorNumElements();
3958   unsigned NumLanes = VT.getSizeInBits()/128;
3959   unsigned NumLaneElts = NumElts/NumLanes;
3960
3961   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3962          "Only supports 2 or 4 elements per lane");
3963
3964   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3965   unsigned Mask = 0;
3966   for (unsigned i = 0; i != NumElts; ++i) {
3967     int Elt = N->getMaskElt(i);
3968     if (Elt < 0) continue;
3969     Elt &= NumLaneElts - 1;
3970     unsigned ShAmt = (i << Shift) % 8;
3971     Mask |= Elt << ShAmt;
3972   }
3973
3974   return Mask;
3975 }
3976
3977 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3978 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3979 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3980   EVT VT = N->getValueType(0);
3981
3982   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3983          "Unsupported vector type for PSHUFHW");
3984
3985   unsigned NumElts = VT.getVectorNumElements();
3986
3987   unsigned Mask = 0;
3988   for (unsigned l = 0; l != NumElts; l += 8) {
3989     // 8 nodes per lane, but we only care about the last 4.
3990     for (unsigned i = 0; i < 4; ++i) {
3991       int Elt = N->getMaskElt(l+i+4);
3992       if (Elt < 0) continue;
3993       Elt &= 0x3; // only 2-bits.
3994       Mask |= Elt << (i * 2);
3995     }
3996   }
3997
3998   return Mask;
3999 }
4000
4001 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4002 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4003 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4004   EVT VT = N->getValueType(0);
4005
4006   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4007          "Unsupported vector type for PSHUFHW");
4008
4009   unsigned NumElts = VT.getVectorNumElements();
4010
4011   unsigned Mask = 0;
4012   for (unsigned l = 0; l != NumElts; l += 8) {
4013     // 8 nodes per lane, but we only care about the first 4.
4014     for (unsigned i = 0; i < 4; ++i) {
4015       int Elt = N->getMaskElt(l+i);
4016       if (Elt < 0) continue;
4017       Elt &= 0x3; // only 2-bits
4018       Mask |= Elt << (i * 2);
4019     }
4020   }
4021
4022   return Mask;
4023 }
4024
4025 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4026 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4027 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4028   EVT VT = SVOp->getValueType(0);
4029   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4030
4031   unsigned NumElts = VT.getVectorNumElements();
4032   unsigned NumLanes = VT.getSizeInBits()/128;
4033   unsigned NumLaneElts = NumElts/NumLanes;
4034
4035   int Val = 0;
4036   unsigned i;
4037   for (i = 0; i != NumElts; ++i) {
4038     Val = SVOp->getMaskElt(i);
4039     if (Val >= 0)
4040       break;
4041   }
4042   if (Val >= (int)NumElts)
4043     Val -= NumElts - NumLaneElts;
4044
4045   assert(Val - i > 0 && "PALIGNR imm should be positive");
4046   return (Val - i) * EltSize;
4047 }
4048
4049 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4050 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4051 /// instructions.
4052 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4053   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4054     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4055
4056   uint64_t Index =
4057     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4058
4059   EVT VecVT = N->getOperand(0).getValueType();
4060   EVT ElVT = VecVT.getVectorElementType();
4061
4062   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4063   return Index / NumElemsPerChunk;
4064 }
4065
4066 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4067 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4068 /// instructions.
4069 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4070   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4071     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4072
4073   uint64_t Index =
4074     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4075
4076   EVT VecVT = N->getValueType(0);
4077   EVT ElVT = VecVT.getVectorElementType();
4078
4079   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4080   return Index / NumElemsPerChunk;
4081 }
4082
4083 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4084 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4085 /// Handles 256-bit.
4086 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4087   EVT VT = N->getValueType(0);
4088
4089   unsigned NumElts = VT.getVectorNumElements();
4090
4091   assert((VT.is256BitVector() && NumElts == 4) &&
4092          "Unsupported vector type for VPERMQ/VPERMPD");
4093
4094   unsigned Mask = 0;
4095   for (unsigned i = 0; i != NumElts; ++i) {
4096     int Elt = N->getMaskElt(i);
4097     if (Elt < 0)
4098       continue;
4099     Mask |= Elt << (i*2);
4100   }
4101
4102   return Mask;
4103 }
4104 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4105 /// constant +0.0.
4106 bool X86::isZeroNode(SDValue Elt) {
4107   return ((isa<ConstantSDNode>(Elt) &&
4108            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4109           (isa<ConstantFPSDNode>(Elt) &&
4110            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4111 }
4112
4113 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4114 /// their permute mask.
4115 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4116                                     SelectionDAG &DAG) {
4117   EVT VT = SVOp->getValueType(0);
4118   unsigned NumElems = VT.getVectorNumElements();
4119   SmallVector<int, 8> MaskVec;
4120
4121   for (unsigned i = 0; i != NumElems; ++i) {
4122     int Idx = SVOp->getMaskElt(i);
4123     if (Idx >= 0) {
4124       if (Idx < (int)NumElems)
4125         Idx += NumElems;
4126       else
4127         Idx -= NumElems;
4128     }
4129     MaskVec.push_back(Idx);
4130   }
4131   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4132                               SVOp->getOperand(0), &MaskVec[0]);
4133 }
4134
4135 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4136 /// match movhlps. The lower half elements should come from upper half of
4137 /// V1 (and in order), and the upper half elements should come from the upper
4138 /// half of V2 (and in order).
4139 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4140   if (VT.getSizeInBits() != 128)
4141     return false;
4142   if (VT.getVectorNumElements() != 4)
4143     return false;
4144   for (unsigned i = 0, e = 2; i != e; ++i)
4145     if (!isUndefOrEqual(Mask[i], i+2))
4146       return false;
4147   for (unsigned i = 2; i != 4; ++i)
4148     if (!isUndefOrEqual(Mask[i], i+4))
4149       return false;
4150   return true;
4151 }
4152
4153 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4154 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4155 /// required.
4156 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4157   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4158     return false;
4159   N = N->getOperand(0).getNode();
4160   if (!ISD::isNON_EXTLoad(N))
4161     return false;
4162   if (LD)
4163     *LD = cast<LoadSDNode>(N);
4164   return true;
4165 }
4166
4167 // Test whether the given value is a vector value which will be legalized
4168 // into a load.
4169 static bool WillBeConstantPoolLoad(SDNode *N) {
4170   if (N->getOpcode() != ISD::BUILD_VECTOR)
4171     return false;
4172
4173   // Check for any non-constant elements.
4174   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4175     switch (N->getOperand(i).getNode()->getOpcode()) {
4176     case ISD::UNDEF:
4177     case ISD::ConstantFP:
4178     case ISD::Constant:
4179       break;
4180     default:
4181       return false;
4182     }
4183
4184   // Vectors of all-zeros and all-ones are materialized with special
4185   // instructions rather than being loaded.
4186   return !ISD::isBuildVectorAllZeros(N) &&
4187          !ISD::isBuildVectorAllOnes(N);
4188 }
4189
4190 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4191 /// match movlp{s|d}. The lower half elements should come from lower half of
4192 /// V1 (and in order), and the upper half elements should come from the upper
4193 /// half of V2 (and in order). And since V1 will become the source of the
4194 /// MOVLP, it must be either a vector load or a scalar load to vector.
4195 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4196                                ArrayRef<int> Mask, EVT VT) {
4197   if (VT.getSizeInBits() != 128)
4198     return false;
4199
4200   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4201     return false;
4202   // Is V2 is a vector load, don't do this transformation. We will try to use
4203   // load folding shufps op.
4204   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4205     return false;
4206
4207   unsigned NumElems = VT.getVectorNumElements();
4208
4209   if (NumElems != 2 && NumElems != 4)
4210     return false;
4211   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4212     if (!isUndefOrEqual(Mask[i], i))
4213       return false;
4214   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4215     if (!isUndefOrEqual(Mask[i], i+NumElems))
4216       return false;
4217   return true;
4218 }
4219
4220 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4221 /// all the same.
4222 static bool isSplatVector(SDNode *N) {
4223   if (N->getOpcode() != ISD::BUILD_VECTOR)
4224     return false;
4225
4226   SDValue SplatValue = N->getOperand(0);
4227   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4228     if (N->getOperand(i) != SplatValue)
4229       return false;
4230   return true;
4231 }
4232
4233 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4234 /// to an zero vector.
4235 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4236 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4237   SDValue V1 = N->getOperand(0);
4238   SDValue V2 = N->getOperand(1);
4239   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4240   for (unsigned i = 0; i != NumElems; ++i) {
4241     int Idx = N->getMaskElt(i);
4242     if (Idx >= (int)NumElems) {
4243       unsigned Opc = V2.getOpcode();
4244       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4245         continue;
4246       if (Opc != ISD::BUILD_VECTOR ||
4247           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4248         return false;
4249     } else if (Idx >= 0) {
4250       unsigned Opc = V1.getOpcode();
4251       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4252         continue;
4253       if (Opc != ISD::BUILD_VECTOR ||
4254           !X86::isZeroNode(V1.getOperand(Idx)))
4255         return false;
4256     }
4257   }
4258   return true;
4259 }
4260
4261 /// getZeroVector - Returns a vector of specified type with all zero elements.
4262 ///
4263 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4264                              SelectionDAG &DAG, DebugLoc dl) {
4265   assert(VT.isVector() && "Expected a vector type");
4266   unsigned Size = VT.getSizeInBits();
4267
4268   // Always build SSE zero vectors as <4 x i32> bitcasted
4269   // to their dest type. This ensures they get CSE'd.
4270   SDValue Vec;
4271   if (Size == 128) {  // SSE
4272     if (Subtarget->hasSSE2()) {  // SSE2
4273       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4274       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4275     } else { // SSE1
4276       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4277       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4278     }
4279   } else if (Size == 256) { // AVX
4280     if (Subtarget->hasAVX2()) { // AVX2
4281       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4282       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4283       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4284     } else {
4285       // 256-bit logic and arithmetic instructions in AVX are all
4286       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4287       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4288       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4289       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4290     }
4291   } else
4292     llvm_unreachable("Unexpected vector type");
4293
4294   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4295 }
4296
4297 /// getOnesVector - Returns a vector of specified type with all bits set.
4298 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4299 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4300 /// Then bitcast to their original type, ensuring they get CSE'd.
4301 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4302                              DebugLoc dl) {
4303   assert(VT.isVector() && "Expected a vector type");
4304   unsigned Size = VT.getSizeInBits();
4305
4306   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4307   SDValue Vec;
4308   if (Size == 256) {
4309     if (HasAVX2) { // AVX2
4310       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4311       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4312     } else { // AVX
4313       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4314       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4315     }
4316   } else if (Size == 128) {
4317     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4318   } else
4319     llvm_unreachable("Unexpected vector type");
4320
4321   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4322 }
4323
4324 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4325 /// that point to V2 points to its first element.
4326 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4327   for (unsigned i = 0; i != NumElems; ++i) {
4328     if (Mask[i] > (int)NumElems) {
4329       Mask[i] = NumElems;
4330     }
4331   }
4332 }
4333
4334 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4335 /// operation of specified width.
4336 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4337                        SDValue V2) {
4338   unsigned NumElems = VT.getVectorNumElements();
4339   SmallVector<int, 8> Mask;
4340   Mask.push_back(NumElems);
4341   for (unsigned i = 1; i != NumElems; ++i)
4342     Mask.push_back(i);
4343   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4344 }
4345
4346 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4347 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4348                           SDValue V2) {
4349   unsigned NumElems = VT.getVectorNumElements();
4350   SmallVector<int, 8> Mask;
4351   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4352     Mask.push_back(i);
4353     Mask.push_back(i + NumElems);
4354   }
4355   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4356 }
4357
4358 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4359 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4360                           SDValue V2) {
4361   unsigned NumElems = VT.getVectorNumElements();
4362   SmallVector<int, 8> Mask;
4363   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4364     Mask.push_back(i + Half);
4365     Mask.push_back(i + NumElems + Half);
4366   }
4367   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4368 }
4369
4370 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4371 // a generic shuffle instruction because the target has no such instructions.
4372 // Generate shuffles which repeat i16 and i8 several times until they can be
4373 // represented by v4f32 and then be manipulated by target suported shuffles.
4374 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4375   EVT VT = V.getValueType();
4376   int NumElems = VT.getVectorNumElements();
4377   DebugLoc dl = V.getDebugLoc();
4378
4379   while (NumElems > 4) {
4380     if (EltNo < NumElems/2) {
4381       V = getUnpackl(DAG, dl, VT, V, V);
4382     } else {
4383       V = getUnpackh(DAG, dl, VT, V, V);
4384       EltNo -= NumElems/2;
4385     }
4386     NumElems >>= 1;
4387   }
4388   return V;
4389 }
4390
4391 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4392 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4393   EVT VT = V.getValueType();
4394   DebugLoc dl = V.getDebugLoc();
4395   unsigned Size = VT.getSizeInBits();
4396
4397   if (Size == 128) {
4398     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4399     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4400     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4401                              &SplatMask[0]);
4402   } else if (Size == 256) {
4403     // To use VPERMILPS to splat scalars, the second half of indicies must
4404     // refer to the higher part, which is a duplication of the lower one,
4405     // because VPERMILPS can only handle in-lane permutations.
4406     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4407                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4408
4409     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4410     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4411                              &SplatMask[0]);
4412   } else
4413     llvm_unreachable("Vector size not supported");
4414
4415   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4416 }
4417
4418 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4419 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4420   EVT SrcVT = SV->getValueType(0);
4421   SDValue V1 = SV->getOperand(0);
4422   DebugLoc dl = SV->getDebugLoc();
4423
4424   int EltNo = SV->getSplatIndex();
4425   int NumElems = SrcVT.getVectorNumElements();
4426   unsigned Size = SrcVT.getSizeInBits();
4427
4428   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4429           "Unknown how to promote splat for type");
4430
4431   // Extract the 128-bit part containing the splat element and update
4432   // the splat element index when it refers to the higher register.
4433   if (Size == 256) {
4434     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4435     if (EltNo >= NumElems/2)
4436       EltNo -= NumElems/2;
4437   }
4438
4439   // All i16 and i8 vector types can't be used directly by a generic shuffle
4440   // instruction because the target has no such instruction. Generate shuffles
4441   // which repeat i16 and i8 several times until they fit in i32, and then can
4442   // be manipulated by target suported shuffles.
4443   EVT EltVT = SrcVT.getVectorElementType();
4444   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4445     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4446
4447   // Recreate the 256-bit vector and place the same 128-bit vector
4448   // into the low and high part. This is necessary because we want
4449   // to use VPERM* to shuffle the vectors
4450   if (Size == 256) {
4451     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4452   }
4453
4454   return getLegalSplat(DAG, V1, EltNo);
4455 }
4456
4457 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4458 /// vector of zero or undef vector.  This produces a shuffle where the low
4459 /// element of V2 is swizzled into the zero/undef vector, landing at element
4460 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4461 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4462                                            bool IsZero,
4463                                            const X86Subtarget *Subtarget,
4464                                            SelectionDAG &DAG) {
4465   EVT VT = V2.getValueType();
4466   SDValue V1 = IsZero
4467     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4468   unsigned NumElems = VT.getVectorNumElements();
4469   SmallVector<int, 16> MaskVec;
4470   for (unsigned i = 0; i != NumElems; ++i)
4471     // If this is the insertion idx, put the low elt of V2 here.
4472     MaskVec.push_back(i == Idx ? NumElems : i);
4473   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4474 }
4475
4476 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4477 /// target specific opcode. Returns true if the Mask could be calculated.
4478 /// Sets IsUnary to true if only uses one source.
4479 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4480                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4481   unsigned NumElems = VT.getVectorNumElements();
4482   SDValue ImmN;
4483
4484   IsUnary = false;
4485   switch(N->getOpcode()) {
4486   case X86ISD::SHUFP:
4487     ImmN = N->getOperand(N->getNumOperands()-1);
4488     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4489     break;
4490   case X86ISD::UNPCKH:
4491     DecodeUNPCKHMask(VT, Mask);
4492     break;
4493   case X86ISD::UNPCKL:
4494     DecodeUNPCKLMask(VT, Mask);
4495     break;
4496   case X86ISD::MOVHLPS:
4497     DecodeMOVHLPSMask(NumElems, Mask);
4498     break;
4499   case X86ISD::MOVLHPS:
4500     DecodeMOVLHPSMask(NumElems, Mask);
4501     break;
4502   case X86ISD::PSHUFD:
4503   case X86ISD::VPERMILP:
4504     ImmN = N->getOperand(N->getNumOperands()-1);
4505     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4506     IsUnary = true;
4507     break;
4508   case X86ISD::PSHUFHW:
4509     ImmN = N->getOperand(N->getNumOperands()-1);
4510     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4511     IsUnary = true;
4512     break;
4513   case X86ISD::PSHUFLW:
4514     ImmN = N->getOperand(N->getNumOperands()-1);
4515     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4516     IsUnary = true;
4517     break;
4518   case X86ISD::VPERMI:
4519     ImmN = N->getOperand(N->getNumOperands()-1);
4520     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4521     IsUnary = true;
4522     break;
4523   case X86ISD::MOVSS:
4524   case X86ISD::MOVSD: {
4525     // The index 0 always comes from the first element of the second source,
4526     // this is why MOVSS and MOVSD are used in the first place. The other
4527     // elements come from the other positions of the first source vector
4528     Mask.push_back(NumElems);
4529     for (unsigned i = 1; i != NumElems; ++i) {
4530       Mask.push_back(i);
4531     }
4532     break;
4533   }
4534   case X86ISD::VPERM2X128:
4535     ImmN = N->getOperand(N->getNumOperands()-1);
4536     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4537     if (Mask.empty()) return false;
4538     break;
4539   case X86ISD::MOVDDUP:
4540   case X86ISD::MOVLHPD:
4541   case X86ISD::MOVLPD:
4542   case X86ISD::MOVLPS:
4543   case X86ISD::MOVSHDUP:
4544   case X86ISD::MOVSLDUP:
4545   case X86ISD::PALIGN:
4546     // Not yet implemented
4547     return false;
4548   default: llvm_unreachable("unknown target shuffle node");
4549   }
4550
4551   return true;
4552 }
4553
4554 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4555 /// element of the result of the vector shuffle.
4556 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4557                                    unsigned Depth) {
4558   if (Depth == 6)
4559     return SDValue();  // Limit search depth.
4560
4561   SDValue V = SDValue(N, 0);
4562   EVT VT = V.getValueType();
4563   unsigned Opcode = V.getOpcode();
4564
4565   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4566   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4567     int Elt = SV->getMaskElt(Index);
4568
4569     if (Elt < 0)
4570       return DAG.getUNDEF(VT.getVectorElementType());
4571
4572     unsigned NumElems = VT.getVectorNumElements();
4573     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4574                                          : SV->getOperand(1);
4575     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4576   }
4577
4578   // Recurse into target specific vector shuffles to find scalars.
4579   if (isTargetShuffle(Opcode)) {
4580     MVT ShufVT = V.getValueType().getSimpleVT();
4581     unsigned NumElems = ShufVT.getVectorNumElements();
4582     SmallVector<int, 16> ShuffleMask;
4583     SDValue ImmN;
4584     bool IsUnary;
4585
4586     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4587       return SDValue();
4588
4589     int Elt = ShuffleMask[Index];
4590     if (Elt < 0)
4591       return DAG.getUNDEF(ShufVT.getVectorElementType());
4592
4593     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4594                                          : N->getOperand(1);
4595     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4596                                Depth+1);
4597   }
4598
4599   // Actual nodes that may contain scalar elements
4600   if (Opcode == ISD::BITCAST) {
4601     V = V.getOperand(0);
4602     EVT SrcVT = V.getValueType();
4603     unsigned NumElems = VT.getVectorNumElements();
4604
4605     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4606       return SDValue();
4607   }
4608
4609   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4610     return (Index == 0) ? V.getOperand(0)
4611                         : DAG.getUNDEF(VT.getVectorElementType());
4612
4613   if (V.getOpcode() == ISD::BUILD_VECTOR)
4614     return V.getOperand(Index);
4615
4616   return SDValue();
4617 }
4618
4619 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4620 /// shuffle operation which come from a consecutively from a zero. The
4621 /// search can start in two different directions, from left or right.
4622 static
4623 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4624                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4625   unsigned i;
4626   for (i = 0; i != NumElems; ++i) {
4627     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4628     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4629     if (!(Elt.getNode() &&
4630          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4631       break;
4632   }
4633
4634   return i;
4635 }
4636
4637 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4638 /// correspond consecutively to elements from one of the vector operands,
4639 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4640 static
4641 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4642                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4643                               unsigned NumElems, unsigned &OpNum) {
4644   bool SeenV1 = false;
4645   bool SeenV2 = false;
4646
4647   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4648     int Idx = SVOp->getMaskElt(i);
4649     // Ignore undef indicies
4650     if (Idx < 0)
4651       continue;
4652
4653     if (Idx < (int)NumElems)
4654       SeenV1 = true;
4655     else
4656       SeenV2 = true;
4657
4658     // Only accept consecutive elements from the same vector
4659     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4660       return false;
4661   }
4662
4663   OpNum = SeenV1 ? 0 : 1;
4664   return true;
4665 }
4666
4667 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4668 /// logical left shift of a vector.
4669 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4670                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4671   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4672   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4673               false /* check zeros from right */, DAG);
4674   unsigned OpSrc;
4675
4676   if (!NumZeros)
4677     return false;
4678
4679   // Considering the elements in the mask that are not consecutive zeros,
4680   // check if they consecutively come from only one of the source vectors.
4681   //
4682   //               V1 = {X, A, B, C}     0
4683   //                         \  \  \    /
4684   //   vector_shuffle V1, V2 <1, 2, 3, X>
4685   //
4686   if (!isShuffleMaskConsecutive(SVOp,
4687             0,                   // Mask Start Index
4688             NumElems-NumZeros,   // Mask End Index(exclusive)
4689             NumZeros,            // Where to start looking in the src vector
4690             NumElems,            // Number of elements in vector
4691             OpSrc))              // Which source operand ?
4692     return false;
4693
4694   isLeft = false;
4695   ShAmt = NumZeros;
4696   ShVal = SVOp->getOperand(OpSrc);
4697   return true;
4698 }
4699
4700 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4701 /// logical left shift of a vector.
4702 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4703                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4704   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4705   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4706               true /* check zeros from left */, DAG);
4707   unsigned OpSrc;
4708
4709   if (!NumZeros)
4710     return false;
4711
4712   // Considering the elements in the mask that are not consecutive zeros,
4713   // check if they consecutively come from only one of the source vectors.
4714   //
4715   //                           0    { A, B, X, X } = V2
4716   //                          / \    /  /
4717   //   vector_shuffle V1, V2 <X, X, 4, 5>
4718   //
4719   if (!isShuffleMaskConsecutive(SVOp,
4720             NumZeros,     // Mask Start Index
4721             NumElems,     // Mask End Index(exclusive)
4722             0,            // Where to start looking in the src vector
4723             NumElems,     // Number of elements in vector
4724             OpSrc))       // Which source operand ?
4725     return false;
4726
4727   isLeft = true;
4728   ShAmt = NumZeros;
4729   ShVal = SVOp->getOperand(OpSrc);
4730   return true;
4731 }
4732
4733 /// isVectorShift - Returns true if the shuffle can be implemented as a
4734 /// logical left or right shift of a vector.
4735 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4736                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4737   // Although the logic below support any bitwidth size, there are no
4738   // shift instructions which handle more than 128-bit vectors.
4739   if (SVOp->getValueType(0).getSizeInBits() > 128)
4740     return false;
4741
4742   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4743       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4744     return true;
4745
4746   return false;
4747 }
4748
4749 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4750 ///
4751 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4752                                        unsigned NumNonZero, unsigned NumZero,
4753                                        SelectionDAG &DAG,
4754                                        const X86Subtarget* Subtarget,
4755                                        const TargetLowering &TLI) {
4756   if (NumNonZero > 8)
4757     return SDValue();
4758
4759   DebugLoc dl = Op.getDebugLoc();
4760   SDValue V(0, 0);
4761   bool First = true;
4762   for (unsigned i = 0; i < 16; ++i) {
4763     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4764     if (ThisIsNonZero && First) {
4765       if (NumZero)
4766         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4767       else
4768         V = DAG.getUNDEF(MVT::v8i16);
4769       First = false;
4770     }
4771
4772     if ((i & 1) != 0) {
4773       SDValue ThisElt(0, 0), LastElt(0, 0);
4774       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4775       if (LastIsNonZero) {
4776         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4777                               MVT::i16, Op.getOperand(i-1));
4778       }
4779       if (ThisIsNonZero) {
4780         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4781         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4782                               ThisElt, DAG.getConstant(8, MVT::i8));
4783         if (LastIsNonZero)
4784           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4785       } else
4786         ThisElt = LastElt;
4787
4788       if (ThisElt.getNode())
4789         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4790                         DAG.getIntPtrConstant(i/2));
4791     }
4792   }
4793
4794   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4795 }
4796
4797 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4798 ///
4799 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4800                                      unsigned NumNonZero, unsigned NumZero,
4801                                      SelectionDAG &DAG,
4802                                      const X86Subtarget* Subtarget,
4803                                      const TargetLowering &TLI) {
4804   if (NumNonZero > 4)
4805     return SDValue();
4806
4807   DebugLoc dl = Op.getDebugLoc();
4808   SDValue V(0, 0);
4809   bool First = true;
4810   for (unsigned i = 0; i < 8; ++i) {
4811     bool isNonZero = (NonZeros & (1 << i)) != 0;
4812     if (isNonZero) {
4813       if (First) {
4814         if (NumZero)
4815           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4816         else
4817           V = DAG.getUNDEF(MVT::v8i16);
4818         First = false;
4819       }
4820       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4821                       MVT::v8i16, V, Op.getOperand(i),
4822                       DAG.getIntPtrConstant(i));
4823     }
4824   }
4825
4826   return V;
4827 }
4828
4829 /// getVShift - Return a vector logical shift node.
4830 ///
4831 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4832                          unsigned NumBits, SelectionDAG &DAG,
4833                          const TargetLowering &TLI, DebugLoc dl) {
4834   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4835   EVT ShVT = MVT::v2i64;
4836   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4837   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4838   return DAG.getNode(ISD::BITCAST, dl, VT,
4839                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4840                              DAG.getConstant(NumBits,
4841                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4842 }
4843
4844 SDValue
4845 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4846                                           SelectionDAG &DAG) const {
4847
4848   // Check if the scalar load can be widened into a vector load. And if
4849   // the address is "base + cst" see if the cst can be "absorbed" into
4850   // the shuffle mask.
4851   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4852     SDValue Ptr = LD->getBasePtr();
4853     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4854       return SDValue();
4855     EVT PVT = LD->getValueType(0);
4856     if (PVT != MVT::i32 && PVT != MVT::f32)
4857       return SDValue();
4858
4859     int FI = -1;
4860     int64_t Offset = 0;
4861     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4862       FI = FINode->getIndex();
4863       Offset = 0;
4864     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4865                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4866       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4867       Offset = Ptr.getConstantOperandVal(1);
4868       Ptr = Ptr.getOperand(0);
4869     } else {
4870       return SDValue();
4871     }
4872
4873     // FIXME: 256-bit vector instructions don't require a strict alignment,
4874     // improve this code to support it better.
4875     unsigned RequiredAlign = VT.getSizeInBits()/8;
4876     SDValue Chain = LD->getChain();
4877     // Make sure the stack object alignment is at least 16 or 32.
4878     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4879     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4880       if (MFI->isFixedObjectIndex(FI)) {
4881         // Can't change the alignment. FIXME: It's possible to compute
4882         // the exact stack offset and reference FI + adjust offset instead.
4883         // If someone *really* cares about this. That's the way to implement it.
4884         return SDValue();
4885       } else {
4886         MFI->setObjectAlignment(FI, RequiredAlign);
4887       }
4888     }
4889
4890     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4891     // Ptr + (Offset & ~15).
4892     if (Offset < 0)
4893       return SDValue();
4894     if ((Offset % RequiredAlign) & 3)
4895       return SDValue();
4896     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4897     if (StartOffset)
4898       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4899                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4900
4901     int EltNo = (Offset - StartOffset) >> 2;
4902     unsigned NumElems = VT.getVectorNumElements();
4903
4904     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4905     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4906                              LD->getPointerInfo().getWithOffset(StartOffset),
4907                              false, false, false, 0);
4908
4909     SmallVector<int, 8> Mask;
4910     for (unsigned i = 0; i != NumElems; ++i)
4911       Mask.push_back(EltNo);
4912
4913     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4914   }
4915
4916   return SDValue();
4917 }
4918
4919 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4920 /// vector of type 'VT', see if the elements can be replaced by a single large
4921 /// load which has the same value as a build_vector whose operands are 'elts'.
4922 ///
4923 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4924 ///
4925 /// FIXME: we'd also like to handle the case where the last elements are zero
4926 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4927 /// There's even a handy isZeroNode for that purpose.
4928 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4929                                         DebugLoc &DL, SelectionDAG &DAG) {
4930   EVT EltVT = VT.getVectorElementType();
4931   unsigned NumElems = Elts.size();
4932
4933   LoadSDNode *LDBase = NULL;
4934   unsigned LastLoadedElt = -1U;
4935
4936   // For each element in the initializer, see if we've found a load or an undef.
4937   // If we don't find an initial load element, or later load elements are
4938   // non-consecutive, bail out.
4939   for (unsigned i = 0; i < NumElems; ++i) {
4940     SDValue Elt = Elts[i];
4941
4942     if (!Elt.getNode() ||
4943         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4944       return SDValue();
4945     if (!LDBase) {
4946       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4947         return SDValue();
4948       LDBase = cast<LoadSDNode>(Elt.getNode());
4949       LastLoadedElt = i;
4950       continue;
4951     }
4952     if (Elt.getOpcode() == ISD::UNDEF)
4953       continue;
4954
4955     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4956     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4957       return SDValue();
4958     LastLoadedElt = i;
4959   }
4960
4961   // If we have found an entire vector of loads and undefs, then return a large
4962   // load of the entire vector width starting at the base pointer.  If we found
4963   // consecutive loads for the low half, generate a vzext_load node.
4964   if (LastLoadedElt == NumElems - 1) {
4965     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4966       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4967                          LDBase->getPointerInfo(),
4968                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4969                          LDBase->isInvariant(), 0);
4970     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4971                        LDBase->getPointerInfo(),
4972                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4973                        LDBase->isInvariant(), LDBase->getAlignment());
4974   }
4975   if (NumElems == 4 && LastLoadedElt == 1 &&
4976       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4977     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4978     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4979     SDValue ResNode =
4980         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4981                                 LDBase->getPointerInfo(),
4982                                 LDBase->getAlignment(),
4983                                 false/*isVolatile*/, true/*ReadMem*/,
4984                                 false/*WriteMem*/);
4985     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4986   }
4987   return SDValue();
4988 }
4989
4990 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4991 /// to generate a splat value for the following cases:
4992 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4993 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4994 /// a scalar load, or a constant.
4995 /// The VBROADCAST node is returned when a pattern is found,
4996 /// or SDValue() otherwise.
4997 SDValue
4998 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
4999   if (!Subtarget->hasAVX())
5000     return SDValue();
5001
5002   EVT VT = Op.getValueType();
5003   DebugLoc dl = Op.getDebugLoc();
5004
5005   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5006          "Unsupported vector type for broadcast.");
5007
5008   SDValue Ld;
5009   bool ConstSplatVal;
5010
5011   switch (Op.getOpcode()) {
5012     default:
5013       // Unknown pattern found.
5014       return SDValue();
5015
5016     case ISD::BUILD_VECTOR: {
5017       // The BUILD_VECTOR node must be a splat.
5018       if (!isSplatVector(Op.getNode()))
5019         return SDValue();
5020
5021       Ld = Op.getOperand(0);
5022       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5023                      Ld.getOpcode() == ISD::ConstantFP);
5024
5025       // The suspected load node has several users. Make sure that all
5026       // of its users are from the BUILD_VECTOR node.
5027       // Constants may have multiple users.
5028       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5029         return SDValue();
5030       break;
5031     }
5032
5033     case ISD::VECTOR_SHUFFLE: {
5034       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5035
5036       // Shuffles must have a splat mask where the first element is
5037       // broadcasted.
5038       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5039         return SDValue();
5040
5041       SDValue Sc = Op.getOperand(0);
5042       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5043           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5044
5045         if (!Subtarget->hasAVX2())
5046           return SDValue();
5047
5048         // Use the register form of the broadcast instruction available on AVX2.
5049         if (VT.is256BitVector())
5050           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5051         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5052       }
5053
5054       Ld = Sc.getOperand(0);
5055       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5056                        Ld.getOpcode() == ISD::ConstantFP);
5057
5058       // The scalar_to_vector node and the suspected
5059       // load node must have exactly one user.
5060       // Constants may have multiple users.
5061       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5062         return SDValue();
5063       break;
5064     }
5065   }
5066
5067   bool Is256 = VT.getSizeInBits() == 256;
5068
5069   // Handle the broadcasting a single constant scalar from the constant pool
5070   // into a vector. On Sandybridge it is still better to load a constant vector
5071   // from the constant pool and not to broadcast it from a scalar.
5072   if (ConstSplatVal && Subtarget->hasAVX2()) {
5073     EVT CVT = Ld.getValueType();
5074     assert(!CVT.isVector() && "Must not broadcast a vector type");
5075     unsigned ScalarSize = CVT.getSizeInBits();
5076
5077     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5078       const Constant *C = 0;
5079       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5080         C = CI->getConstantIntValue();
5081       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5082         C = CF->getConstantFPValue();
5083
5084       assert(C && "Invalid constant type");
5085
5086       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5087       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5088       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5089                        MachinePointerInfo::getConstantPool(),
5090                        false, false, false, Alignment);
5091
5092       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5093     }
5094   }
5095
5096   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5097   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5098
5099   // Handle AVX2 in-register broadcasts.
5100   if (!IsLoad && Subtarget->hasAVX2() &&
5101       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5102     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5103
5104   // The scalar source must be a normal load.
5105   if (!IsLoad)
5106     return SDValue();
5107
5108   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5109     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5110
5111   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5112   // double since there is no vbroadcastsd xmm
5113   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5114     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5115       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5116   }
5117
5118   // Unsupported broadcast.
5119   return SDValue();
5120 }
5121
5122 SDValue
5123 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5124   DebugLoc dl = Op.getDebugLoc();
5125
5126   EVT VT = Op.getValueType();
5127   EVT ExtVT = VT.getVectorElementType();
5128   unsigned NumElems = Op.getNumOperands();
5129
5130   // Vectors containing all zeros can be matched by pxor and xorps later
5131   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5132     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5133     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5134     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5135       return Op;
5136
5137     return getZeroVector(VT, Subtarget, DAG, dl);
5138   }
5139
5140   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5141   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5142   // vpcmpeqd on 256-bit vectors.
5143   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5144     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5145       return Op;
5146
5147     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5148   }
5149
5150   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5151   if (Broadcast.getNode())
5152     return Broadcast;
5153
5154   unsigned EVTBits = ExtVT.getSizeInBits();
5155
5156   unsigned NumZero  = 0;
5157   unsigned NumNonZero = 0;
5158   unsigned NonZeros = 0;
5159   bool IsAllConstants = true;
5160   SmallSet<SDValue, 8> Values;
5161   for (unsigned i = 0; i < NumElems; ++i) {
5162     SDValue Elt = Op.getOperand(i);
5163     if (Elt.getOpcode() == ISD::UNDEF)
5164       continue;
5165     Values.insert(Elt);
5166     if (Elt.getOpcode() != ISD::Constant &&
5167         Elt.getOpcode() != ISD::ConstantFP)
5168       IsAllConstants = false;
5169     if (X86::isZeroNode(Elt))
5170       NumZero++;
5171     else {
5172       NonZeros |= (1 << i);
5173       NumNonZero++;
5174     }
5175   }
5176
5177   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5178   if (NumNonZero == 0)
5179     return DAG.getUNDEF(VT);
5180
5181   // Special case for single non-zero, non-undef, element.
5182   if (NumNonZero == 1) {
5183     unsigned Idx = CountTrailingZeros_32(NonZeros);
5184     SDValue Item = Op.getOperand(Idx);
5185
5186     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5187     // the value are obviously zero, truncate the value to i32 and do the
5188     // insertion that way.  Only do this if the value is non-constant or if the
5189     // value is a constant being inserted into element 0.  It is cheaper to do
5190     // a constant pool load than it is to do a movd + shuffle.
5191     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5192         (!IsAllConstants || Idx == 0)) {
5193       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5194         // Handle SSE only.
5195         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5196         EVT VecVT = MVT::v4i32;
5197         unsigned VecElts = 4;
5198
5199         // Truncate the value (which may itself be a constant) to i32, and
5200         // convert it to a vector with movd (S2V+shuffle to zero extend).
5201         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5202         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5203         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5204
5205         // Now we have our 32-bit value zero extended in the low element of
5206         // a vector.  If Idx != 0, swizzle it into place.
5207         if (Idx != 0) {
5208           SmallVector<int, 4> Mask;
5209           Mask.push_back(Idx);
5210           for (unsigned i = 1; i != VecElts; ++i)
5211             Mask.push_back(i);
5212           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5213                                       &Mask[0]);
5214         }
5215         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5216       }
5217     }
5218
5219     // If we have a constant or non-constant insertion into the low element of
5220     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5221     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5222     // depending on what the source datatype is.
5223     if (Idx == 0) {
5224       if (NumZero == 0)
5225         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5226
5227       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5228           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5229         if (VT.getSizeInBits() == 256) {
5230           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5231           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5232                              Item, DAG.getIntPtrConstant(0));
5233         }
5234         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5235         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5236         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5237         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5238       }
5239
5240       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5241         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5242         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5243         if (VT.getSizeInBits() == 256) {
5244           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5245           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5246         } else {
5247           assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5248           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5249         }
5250         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5251       }
5252     }
5253
5254     // Is it a vector logical left shift?
5255     if (NumElems == 2 && Idx == 1 &&
5256         X86::isZeroNode(Op.getOperand(0)) &&
5257         !X86::isZeroNode(Op.getOperand(1))) {
5258       unsigned NumBits = VT.getSizeInBits();
5259       return getVShift(true, VT,
5260                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5261                                    VT, Op.getOperand(1)),
5262                        NumBits/2, DAG, *this, dl);
5263     }
5264
5265     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5266       return SDValue();
5267
5268     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5269     // is a non-constant being inserted into an element other than the low one,
5270     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5271     // movd/movss) to move this into the low element, then shuffle it into
5272     // place.
5273     if (EVTBits == 32) {
5274       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5275
5276       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5277       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5278       SmallVector<int, 8> MaskVec;
5279       for (unsigned i = 0; i != NumElems; ++i)
5280         MaskVec.push_back(i == Idx ? 0 : 1);
5281       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5282     }
5283   }
5284
5285   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5286   if (Values.size() == 1) {
5287     if (EVTBits == 32) {
5288       // Instead of a shuffle like this:
5289       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5290       // Check if it's possible to issue this instead.
5291       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5292       unsigned Idx = CountTrailingZeros_32(NonZeros);
5293       SDValue Item = Op.getOperand(Idx);
5294       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5295         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5296     }
5297     return SDValue();
5298   }
5299
5300   // A vector full of immediates; various special cases are already
5301   // handled, so this is best done with a single constant-pool load.
5302   if (IsAllConstants)
5303     return SDValue();
5304
5305   // For AVX-length vectors, build the individual 128-bit pieces and use
5306   // shuffles to put them in place.
5307   if (VT.getSizeInBits() == 256) {
5308     SmallVector<SDValue, 32> V;
5309     for (unsigned i = 0; i != NumElems; ++i)
5310       V.push_back(Op.getOperand(i));
5311
5312     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5313
5314     // Build both the lower and upper subvector.
5315     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5316     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5317                                 NumElems/2);
5318
5319     // Recreate the wider vector with the lower and upper part.
5320     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5321   }
5322
5323   // Let legalizer expand 2-wide build_vectors.
5324   if (EVTBits == 64) {
5325     if (NumNonZero == 1) {
5326       // One half is zero or undef.
5327       unsigned Idx = CountTrailingZeros_32(NonZeros);
5328       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5329                                  Op.getOperand(Idx));
5330       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5331     }
5332     return SDValue();
5333   }
5334
5335   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5336   if (EVTBits == 8 && NumElems == 16) {
5337     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5338                                         Subtarget, *this);
5339     if (V.getNode()) return V;
5340   }
5341
5342   if (EVTBits == 16 && NumElems == 8) {
5343     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5344                                       Subtarget, *this);
5345     if (V.getNode()) return V;
5346   }
5347
5348   // If element VT is == 32 bits, turn it into a number of shuffles.
5349   SmallVector<SDValue, 8> V(NumElems);
5350   if (NumElems == 4 && NumZero > 0) {
5351     for (unsigned i = 0; i < 4; ++i) {
5352       bool isZero = !(NonZeros & (1 << i));
5353       if (isZero)
5354         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5355       else
5356         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5357     }
5358
5359     for (unsigned i = 0; i < 2; ++i) {
5360       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5361         default: break;
5362         case 0:
5363           V[i] = V[i*2];  // Must be a zero vector.
5364           break;
5365         case 1:
5366           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5367           break;
5368         case 2:
5369           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5370           break;
5371         case 3:
5372           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5373           break;
5374       }
5375     }
5376
5377     bool Reverse1 = (NonZeros & 0x3) == 2;
5378     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5379     int MaskVec[] = {
5380       Reverse1 ? 1 : 0,
5381       Reverse1 ? 0 : 1,
5382       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5383       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5384     };
5385     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5386   }
5387
5388   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5389     // Check for a build vector of consecutive loads.
5390     for (unsigned i = 0; i < NumElems; ++i)
5391       V[i] = Op.getOperand(i);
5392
5393     // Check for elements which are consecutive loads.
5394     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5395     if (LD.getNode())
5396       return LD;
5397
5398     // For SSE 4.1, use insertps to put the high elements into the low element.
5399     if (getSubtarget()->hasSSE41()) {
5400       SDValue Result;
5401       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5402         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5403       else
5404         Result = DAG.getUNDEF(VT);
5405
5406       for (unsigned i = 1; i < NumElems; ++i) {
5407         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5408         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5409                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5410       }
5411       return Result;
5412     }
5413
5414     // Otherwise, expand into a number of unpckl*, start by extending each of
5415     // our (non-undef) elements to the full vector width with the element in the
5416     // bottom slot of the vector (which generates no code for SSE).
5417     for (unsigned i = 0; i < NumElems; ++i) {
5418       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5419         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5420       else
5421         V[i] = DAG.getUNDEF(VT);
5422     }
5423
5424     // Next, we iteratively mix elements, e.g. for v4f32:
5425     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5426     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5427     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5428     unsigned EltStride = NumElems >> 1;
5429     while (EltStride != 0) {
5430       for (unsigned i = 0; i < EltStride; ++i) {
5431         // If V[i+EltStride] is undef and this is the first round of mixing,
5432         // then it is safe to just drop this shuffle: V[i] is already in the
5433         // right place, the one element (since it's the first round) being
5434         // inserted as undef can be dropped.  This isn't safe for successive
5435         // rounds because they will permute elements within both vectors.
5436         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5437             EltStride == NumElems/2)
5438           continue;
5439
5440         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5441       }
5442       EltStride >>= 1;
5443     }
5444     return V[0];
5445   }
5446   return SDValue();
5447 }
5448
5449 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5450 // them in a MMX register.  This is better than doing a stack convert.
5451 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5452   DebugLoc dl = Op.getDebugLoc();
5453   EVT ResVT = Op.getValueType();
5454
5455   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5456          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5457   int Mask[2];
5458   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5459   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5460   InVec = Op.getOperand(1);
5461   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5462     unsigned NumElts = ResVT.getVectorNumElements();
5463     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5464     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5465                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5466   } else {
5467     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5468     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5469     Mask[0] = 0; Mask[1] = 2;
5470     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5471   }
5472   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5473 }
5474
5475 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5476 // to create 256-bit vectors from two other 128-bit ones.
5477 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5478   DebugLoc dl = Op.getDebugLoc();
5479   EVT ResVT = Op.getValueType();
5480
5481   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5482
5483   SDValue V1 = Op.getOperand(0);
5484   SDValue V2 = Op.getOperand(1);
5485   unsigned NumElems = ResVT.getVectorNumElements();
5486
5487   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5488 }
5489
5490 SDValue
5491 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5492   EVT ResVT = Op.getValueType();
5493
5494   assert(Op.getNumOperands() == 2);
5495   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5496          "Unsupported CONCAT_VECTORS for value type");
5497
5498   // We support concatenate two MMX registers and place them in a MMX register.
5499   // This is better than doing a stack convert.
5500   if (ResVT.is128BitVector())
5501     return LowerMMXCONCAT_VECTORS(Op, DAG);
5502
5503   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5504   // from two other 128-bit ones.
5505   return LowerAVXCONCAT_VECTORS(Op, DAG);
5506 }
5507
5508 // Try to lower a shuffle node into a simple blend instruction.
5509 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5510                                           const X86Subtarget *Subtarget,
5511                                           SelectionDAG &DAG) {
5512   SDValue V1 = SVOp->getOperand(0);
5513   SDValue V2 = SVOp->getOperand(1);
5514   DebugLoc dl = SVOp->getDebugLoc();
5515   MVT VT = SVOp->getValueType(0).getSimpleVT();
5516   unsigned NumElems = VT.getVectorNumElements();
5517
5518   if (!Subtarget->hasSSE41())
5519     return SDValue();
5520
5521   unsigned ISDNo = 0;
5522   MVT OpTy;
5523
5524   switch (VT.SimpleTy) {
5525   default: return SDValue();
5526   case MVT::v8i16:
5527     ISDNo = X86ISD::BLENDPW;
5528     OpTy = MVT::v8i16;
5529     break;
5530   case MVT::v4i32:
5531   case MVT::v4f32:
5532     ISDNo = X86ISD::BLENDPS;
5533     OpTy = MVT::v4f32;
5534     break;
5535   case MVT::v2i64:
5536   case MVT::v2f64:
5537     ISDNo = X86ISD::BLENDPD;
5538     OpTy = MVT::v2f64;
5539     break;
5540   case MVT::v8i32:
5541   case MVT::v8f32:
5542     if (!Subtarget->hasAVX())
5543       return SDValue();
5544     ISDNo = X86ISD::BLENDPS;
5545     OpTy = MVT::v8f32;
5546     break;
5547   case MVT::v4i64:
5548   case MVT::v4f64:
5549     if (!Subtarget->hasAVX())
5550       return SDValue();
5551     ISDNo = X86ISD::BLENDPD;
5552     OpTy = MVT::v4f64;
5553     break;
5554   }
5555   assert(ISDNo && "Invalid Op Number");
5556
5557   unsigned MaskVals = 0;
5558
5559   for (unsigned i = 0; i != NumElems; ++i) {
5560     int EltIdx = SVOp->getMaskElt(i);
5561     if (EltIdx == (int)i || EltIdx < 0)
5562       MaskVals |= (1<<i);
5563     else if (EltIdx == (int)(i + NumElems))
5564       continue; // Bit is set to zero;
5565     else
5566       return SDValue();
5567   }
5568
5569   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5570   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5571   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5572                              DAG.getConstant(MaskVals, MVT::i32));
5573   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5574 }
5575
5576 // v8i16 shuffles - Prefer shuffles in the following order:
5577 // 1. [all]   pshuflw, pshufhw, optional move
5578 // 2. [ssse3] 1 x pshufb
5579 // 3. [ssse3] 2 x pshufb + 1 x por
5580 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5581 SDValue
5582 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5583                                             SelectionDAG &DAG) const {
5584   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5585   SDValue V1 = SVOp->getOperand(0);
5586   SDValue V2 = SVOp->getOperand(1);
5587   DebugLoc dl = SVOp->getDebugLoc();
5588   SmallVector<int, 8> MaskVals;
5589
5590   // Determine if more than 1 of the words in each of the low and high quadwords
5591   // of the result come from the same quadword of one of the two inputs.  Undef
5592   // mask values count as coming from any quadword, for better codegen.
5593   unsigned LoQuad[] = { 0, 0, 0, 0 };
5594   unsigned HiQuad[] = { 0, 0, 0, 0 };
5595   std::bitset<4> InputQuads;
5596   for (unsigned i = 0; i < 8; ++i) {
5597     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5598     int EltIdx = SVOp->getMaskElt(i);
5599     MaskVals.push_back(EltIdx);
5600     if (EltIdx < 0) {
5601       ++Quad[0];
5602       ++Quad[1];
5603       ++Quad[2];
5604       ++Quad[3];
5605       continue;
5606     }
5607     ++Quad[EltIdx / 4];
5608     InputQuads.set(EltIdx / 4);
5609   }
5610
5611   int BestLoQuad = -1;
5612   unsigned MaxQuad = 1;
5613   for (unsigned i = 0; i < 4; ++i) {
5614     if (LoQuad[i] > MaxQuad) {
5615       BestLoQuad = i;
5616       MaxQuad = LoQuad[i];
5617     }
5618   }
5619
5620   int BestHiQuad = -1;
5621   MaxQuad = 1;
5622   for (unsigned i = 0; i < 4; ++i) {
5623     if (HiQuad[i] > MaxQuad) {
5624       BestHiQuad = i;
5625       MaxQuad = HiQuad[i];
5626     }
5627   }
5628
5629   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5630   // of the two input vectors, shuffle them into one input vector so only a
5631   // single pshufb instruction is necessary. If There are more than 2 input
5632   // quads, disable the next transformation since it does not help SSSE3.
5633   bool V1Used = InputQuads[0] || InputQuads[1];
5634   bool V2Used = InputQuads[2] || InputQuads[3];
5635   if (Subtarget->hasSSSE3()) {
5636     if (InputQuads.count() == 2 && V1Used && V2Used) {
5637       BestLoQuad = InputQuads[0] ? 0 : 1;
5638       BestHiQuad = InputQuads[2] ? 2 : 3;
5639     }
5640     if (InputQuads.count() > 2) {
5641       BestLoQuad = -1;
5642       BestHiQuad = -1;
5643     }
5644   }
5645
5646   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5647   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5648   // words from all 4 input quadwords.
5649   SDValue NewV;
5650   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5651     int MaskV[] = {
5652       BestLoQuad < 0 ? 0 : BestLoQuad,
5653       BestHiQuad < 0 ? 1 : BestHiQuad
5654     };
5655     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5656                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5657                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5658     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5659
5660     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5661     // source words for the shuffle, to aid later transformations.
5662     bool AllWordsInNewV = true;
5663     bool InOrder[2] = { true, true };
5664     for (unsigned i = 0; i != 8; ++i) {
5665       int idx = MaskVals[i];
5666       if (idx != (int)i)
5667         InOrder[i/4] = false;
5668       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5669         continue;
5670       AllWordsInNewV = false;
5671       break;
5672     }
5673
5674     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5675     if (AllWordsInNewV) {
5676       for (int i = 0; i != 8; ++i) {
5677         int idx = MaskVals[i];
5678         if (idx < 0)
5679           continue;
5680         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5681         if ((idx != i) && idx < 4)
5682           pshufhw = false;
5683         if ((idx != i) && idx > 3)
5684           pshuflw = false;
5685       }
5686       V1 = NewV;
5687       V2Used = false;
5688       BestLoQuad = 0;
5689       BestHiQuad = 1;
5690     }
5691
5692     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5693     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5694     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5695       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5696       unsigned TargetMask = 0;
5697       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5698                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5699       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5700       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5701                              getShufflePSHUFLWImmediate(SVOp);
5702       V1 = NewV.getOperand(0);
5703       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5704     }
5705   }
5706
5707   // If we have SSSE3, and all words of the result are from 1 input vector,
5708   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5709   // is present, fall back to case 4.
5710   if (Subtarget->hasSSSE3()) {
5711     SmallVector<SDValue,16> pshufbMask;
5712
5713     // If we have elements from both input vectors, set the high bit of the
5714     // shuffle mask element to zero out elements that come from V2 in the V1
5715     // mask, and elements that come from V1 in the V2 mask, so that the two
5716     // results can be OR'd together.
5717     bool TwoInputs = V1Used && V2Used;
5718     for (unsigned i = 0; i != 8; ++i) {
5719       int EltIdx = MaskVals[i] * 2;
5720       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5721       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5722       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5723       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5724     }
5725     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5726     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5727                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5728                                  MVT::v16i8, &pshufbMask[0], 16));
5729     if (!TwoInputs)
5730       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5731
5732     // Calculate the shuffle mask for the second input, shuffle it, and
5733     // OR it with the first shuffled input.
5734     pshufbMask.clear();
5735     for (unsigned i = 0; i != 8; ++i) {
5736       int EltIdx = MaskVals[i] * 2;
5737       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5738       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5739       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5740       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5741     }
5742     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5743     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5744                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5745                                  MVT::v16i8, &pshufbMask[0], 16));
5746     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5747     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5748   }
5749
5750   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5751   // and update MaskVals with new element order.
5752   std::bitset<8> InOrder;
5753   if (BestLoQuad >= 0) {
5754     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5755     for (int i = 0; i != 4; ++i) {
5756       int idx = MaskVals[i];
5757       if (idx < 0) {
5758         InOrder.set(i);
5759       } else if ((idx / 4) == BestLoQuad) {
5760         MaskV[i] = idx & 3;
5761         InOrder.set(i);
5762       }
5763     }
5764     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5765                                 &MaskV[0]);
5766
5767     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5768       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5769       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5770                                   NewV.getOperand(0),
5771                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5772     }
5773   }
5774
5775   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5776   // and update MaskVals with the new element order.
5777   if (BestHiQuad >= 0) {
5778     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5779     for (unsigned i = 4; i != 8; ++i) {
5780       int idx = MaskVals[i];
5781       if (idx < 0) {
5782         InOrder.set(i);
5783       } else if ((idx / 4) == BestHiQuad) {
5784         MaskV[i] = (idx & 3) + 4;
5785         InOrder.set(i);
5786       }
5787     }
5788     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5789                                 &MaskV[0]);
5790
5791     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5792       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5793       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5794                                   NewV.getOperand(0),
5795                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5796     }
5797   }
5798
5799   // In case BestHi & BestLo were both -1, which means each quadword has a word
5800   // from each of the four input quadwords, calculate the InOrder bitvector now
5801   // before falling through to the insert/extract cleanup.
5802   if (BestLoQuad == -1 && BestHiQuad == -1) {
5803     NewV = V1;
5804     for (int i = 0; i != 8; ++i)
5805       if (MaskVals[i] < 0 || MaskVals[i] == i)
5806         InOrder.set(i);
5807   }
5808
5809   // The other elements are put in the right place using pextrw and pinsrw.
5810   for (unsigned i = 0; i != 8; ++i) {
5811     if (InOrder[i])
5812       continue;
5813     int EltIdx = MaskVals[i];
5814     if (EltIdx < 0)
5815       continue;
5816     SDValue ExtOp = (EltIdx < 8) ?
5817       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5818                   DAG.getIntPtrConstant(EltIdx)) :
5819       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5820                   DAG.getIntPtrConstant(EltIdx - 8));
5821     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5822                        DAG.getIntPtrConstant(i));
5823   }
5824   return NewV;
5825 }
5826
5827 // v16i8 shuffles - Prefer shuffles in the following order:
5828 // 1. [ssse3] 1 x pshufb
5829 // 2. [ssse3] 2 x pshufb + 1 x por
5830 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5831 static
5832 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5833                                  SelectionDAG &DAG,
5834                                  const X86TargetLowering &TLI) {
5835   SDValue V1 = SVOp->getOperand(0);
5836   SDValue V2 = SVOp->getOperand(1);
5837   DebugLoc dl = SVOp->getDebugLoc();
5838   ArrayRef<int> MaskVals = SVOp->getMask();
5839
5840   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5841
5842   // If we have SSSE3, case 1 is generated when all result bytes come from
5843   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5844   // present, fall back to case 3.
5845
5846   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5847   if (TLI.getSubtarget()->hasSSSE3()) {
5848     SmallVector<SDValue,16> pshufbMask;
5849
5850     // If all result elements are from one input vector, then only translate
5851     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5852     //
5853     // Otherwise, we have elements from both input vectors, and must zero out
5854     // elements that come from V2 in the first mask, and V1 in the second mask
5855     // so that we can OR them together.
5856     for (unsigned i = 0; i != 16; ++i) {
5857       int EltIdx = MaskVals[i];
5858       if (EltIdx < 0 || EltIdx >= 16)
5859         EltIdx = 0x80;
5860       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5861     }
5862     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5863                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5864                                  MVT::v16i8, &pshufbMask[0], 16));
5865     if (V2IsUndef)
5866       return V1;
5867
5868     // Calculate the shuffle mask for the second input, shuffle it, and
5869     // OR it with the first shuffled input.
5870     pshufbMask.clear();
5871     for (unsigned i = 0; i != 16; ++i) {
5872       int EltIdx = MaskVals[i];
5873       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5874       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5875     }
5876     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5877                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5878                                  MVT::v16i8, &pshufbMask[0], 16));
5879     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5880   }
5881
5882   // No SSSE3 - Calculate in place words and then fix all out of place words
5883   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5884   // the 16 different words that comprise the two doublequadword input vectors.
5885   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5886   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5887   SDValue NewV = V1;
5888   for (int i = 0; i != 8; ++i) {
5889     int Elt0 = MaskVals[i*2];
5890     int Elt1 = MaskVals[i*2+1];
5891
5892     // This word of the result is all undef, skip it.
5893     if (Elt0 < 0 && Elt1 < 0)
5894       continue;
5895
5896     // This word of the result is already in the correct place, skip it.
5897     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5898       continue;
5899
5900     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5901     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5902     SDValue InsElt;
5903
5904     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5905     // using a single extract together, load it and store it.
5906     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5907       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5908                            DAG.getIntPtrConstant(Elt1 / 2));
5909       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5910                         DAG.getIntPtrConstant(i));
5911       continue;
5912     }
5913
5914     // If Elt1 is defined, extract it from the appropriate source.  If the
5915     // source byte is not also odd, shift the extracted word left 8 bits
5916     // otherwise clear the bottom 8 bits if we need to do an or.
5917     if (Elt1 >= 0) {
5918       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5919                            DAG.getIntPtrConstant(Elt1 / 2));
5920       if ((Elt1 & 1) == 0)
5921         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5922                              DAG.getConstant(8,
5923                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5924       else if (Elt0 >= 0)
5925         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5926                              DAG.getConstant(0xFF00, MVT::i16));
5927     }
5928     // If Elt0 is defined, extract it from the appropriate source.  If the
5929     // source byte is not also even, shift the extracted word right 8 bits. If
5930     // Elt1 was also defined, OR the extracted values together before
5931     // inserting them in the result.
5932     if (Elt0 >= 0) {
5933       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5934                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5935       if ((Elt0 & 1) != 0)
5936         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5937                               DAG.getConstant(8,
5938                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5939       else if (Elt1 >= 0)
5940         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5941                              DAG.getConstant(0x00FF, MVT::i16));
5942       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5943                          : InsElt0;
5944     }
5945     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5946                        DAG.getIntPtrConstant(i));
5947   }
5948   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5949 }
5950
5951 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5952 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5953 /// done when every pair / quad of shuffle mask elements point to elements in
5954 /// the right sequence. e.g.
5955 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5956 static
5957 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5958                                  SelectionDAG &DAG, DebugLoc dl) {
5959   MVT VT = SVOp->getValueType(0).getSimpleVT();
5960   unsigned NumElems = VT.getVectorNumElements();
5961   MVT NewVT;
5962   unsigned Scale;
5963   switch (VT.SimpleTy) {
5964   default: llvm_unreachable("Unexpected!");
5965   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
5966   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
5967   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
5968   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
5969   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
5970   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
5971   }
5972
5973   SmallVector<int, 8> MaskVec;
5974   for (unsigned i = 0; i != NumElems; i += Scale) {
5975     int StartIdx = -1;
5976     for (unsigned j = 0; j != Scale; ++j) {
5977       int EltIdx = SVOp->getMaskElt(i+j);
5978       if (EltIdx < 0)
5979         continue;
5980       if (StartIdx < 0)
5981         StartIdx = (EltIdx / Scale);
5982       if (EltIdx != (int)(StartIdx*Scale + j))
5983         return SDValue();
5984     }
5985     MaskVec.push_back(StartIdx);
5986   }
5987
5988   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
5989   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
5990   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5991 }
5992
5993 /// getVZextMovL - Return a zero-extending vector move low node.
5994 ///
5995 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5996                             SDValue SrcOp, SelectionDAG &DAG,
5997                             const X86Subtarget *Subtarget, DebugLoc dl) {
5998   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5999     LoadSDNode *LD = NULL;
6000     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6001       LD = dyn_cast<LoadSDNode>(SrcOp);
6002     if (!LD) {
6003       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6004       // instead.
6005       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6006       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6007           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6008           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6009           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6010         // PR2108
6011         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6012         return DAG.getNode(ISD::BITCAST, dl, VT,
6013                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6014                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6015                                                    OpVT,
6016                                                    SrcOp.getOperand(0)
6017                                                           .getOperand(0))));
6018       }
6019     }
6020   }
6021
6022   return DAG.getNode(ISD::BITCAST, dl, VT,
6023                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6024                                  DAG.getNode(ISD::BITCAST, dl,
6025                                              OpVT, SrcOp)));
6026 }
6027
6028 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6029 /// which could not be matched by any known target speficic shuffle
6030 static SDValue
6031 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6032
6033   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6034   if (NewOp.getNode())
6035     return NewOp;
6036
6037   EVT VT = SVOp->getValueType(0);
6038
6039   unsigned NumElems = VT.getVectorNumElements();
6040   unsigned NumLaneElems = NumElems / 2;
6041
6042   DebugLoc dl = SVOp->getDebugLoc();
6043   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6044   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6045   SDValue Output[2];
6046
6047   SmallVector<int, 16> Mask;
6048   for (unsigned l = 0; l < 2; ++l) {
6049     // Build a shuffle mask for the output, discovering on the fly which
6050     // input vectors to use as shuffle operands (recorded in InputUsed).
6051     // If building a suitable shuffle vector proves too hard, then bail
6052     // out with UseBuildVector set.
6053     bool UseBuildVector = false;
6054     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6055     unsigned LaneStart = l * NumLaneElems;
6056     for (unsigned i = 0; i != NumLaneElems; ++i) {
6057       // The mask element.  This indexes into the input.
6058       int Idx = SVOp->getMaskElt(i+LaneStart);
6059       if (Idx < 0) {
6060         // the mask element does not index into any input vector.
6061         Mask.push_back(-1);
6062         continue;
6063       }
6064
6065       // The input vector this mask element indexes into.
6066       int Input = Idx / NumLaneElems;
6067
6068       // Turn the index into an offset from the start of the input vector.
6069       Idx -= Input * NumLaneElems;
6070
6071       // Find or create a shuffle vector operand to hold this input.
6072       unsigned OpNo;
6073       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6074         if (InputUsed[OpNo] == Input)
6075           // This input vector is already an operand.
6076           break;
6077         if (InputUsed[OpNo] < 0) {
6078           // Create a new operand for this input vector.
6079           InputUsed[OpNo] = Input;
6080           break;
6081         }
6082       }
6083
6084       if (OpNo >= array_lengthof(InputUsed)) {
6085         // More than two input vectors used!  Give up on trying to create a
6086         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6087         UseBuildVector = true;
6088         break;
6089       }
6090
6091       // Add the mask index for the new shuffle vector.
6092       Mask.push_back(Idx + OpNo * NumLaneElems);
6093     }
6094
6095     if (UseBuildVector) {
6096       SmallVector<SDValue, 16> SVOps;
6097       for (unsigned i = 0; i != NumLaneElems; ++i) {
6098         // The mask element.  This indexes into the input.
6099         int Idx = SVOp->getMaskElt(i+LaneStart);
6100         if (Idx < 0) {
6101           SVOps.push_back(DAG.getUNDEF(EltVT));
6102           continue;
6103         }
6104
6105         // The input vector this mask element indexes into.
6106         int Input = Idx / NumElems;
6107
6108         // Turn the index into an offset from the start of the input vector.
6109         Idx -= Input * NumElems;
6110
6111         // Extract the vector element by hand.
6112         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6113                                     SVOp->getOperand(Input),
6114                                     DAG.getIntPtrConstant(Idx)));
6115       }
6116
6117       // Construct the output using a BUILD_VECTOR.
6118       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6119                               SVOps.size());
6120     } else if (InputUsed[0] < 0) {
6121       // No input vectors were used! The result is undefined.
6122       Output[l] = DAG.getUNDEF(NVT);
6123     } else {
6124       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6125                                         (InputUsed[0] % 2) * NumLaneElems,
6126                                         DAG, dl);
6127       // If only one input was used, use an undefined vector for the other.
6128       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6129         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6130                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6131       // At least one input vector was used. Create a new shuffle vector.
6132       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6133     }
6134
6135     Mask.clear();
6136   }
6137
6138   // Concatenate the result back
6139   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6140 }
6141
6142 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6143 /// 4 elements, and match them with several different shuffle types.
6144 static SDValue
6145 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6146   SDValue V1 = SVOp->getOperand(0);
6147   SDValue V2 = SVOp->getOperand(1);
6148   DebugLoc dl = SVOp->getDebugLoc();
6149   EVT VT = SVOp->getValueType(0);
6150
6151   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6152
6153   std::pair<int, int> Locs[4];
6154   int Mask1[] = { -1, -1, -1, -1 };
6155   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6156
6157   unsigned NumHi = 0;
6158   unsigned NumLo = 0;
6159   for (unsigned i = 0; i != 4; ++i) {
6160     int Idx = PermMask[i];
6161     if (Idx < 0) {
6162       Locs[i] = std::make_pair(-1, -1);
6163     } else {
6164       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6165       if (Idx < 4) {
6166         Locs[i] = std::make_pair(0, NumLo);
6167         Mask1[NumLo] = Idx;
6168         NumLo++;
6169       } else {
6170         Locs[i] = std::make_pair(1, NumHi);
6171         if (2+NumHi < 4)
6172           Mask1[2+NumHi] = Idx;
6173         NumHi++;
6174       }
6175     }
6176   }
6177
6178   if (NumLo <= 2 && NumHi <= 2) {
6179     // If no more than two elements come from either vector. This can be
6180     // implemented with two shuffles. First shuffle gather the elements.
6181     // The second shuffle, which takes the first shuffle as both of its
6182     // vector operands, put the elements into the right order.
6183     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6184
6185     int Mask2[] = { -1, -1, -1, -1 };
6186
6187     for (unsigned i = 0; i != 4; ++i)
6188       if (Locs[i].first != -1) {
6189         unsigned Idx = (i < 2) ? 0 : 4;
6190         Idx += Locs[i].first * 2 + Locs[i].second;
6191         Mask2[i] = Idx;
6192       }
6193
6194     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6195   }
6196
6197   if (NumLo == 3 || NumHi == 3) {
6198     // Otherwise, we must have three elements from one vector, call it X, and
6199     // one element from the other, call it Y.  First, use a shufps to build an
6200     // intermediate vector with the one element from Y and the element from X
6201     // that will be in the same half in the final destination (the indexes don't
6202     // matter). Then, use a shufps to build the final vector, taking the half
6203     // containing the element from Y from the intermediate, and the other half
6204     // from X.
6205     if (NumHi == 3) {
6206       // Normalize it so the 3 elements come from V1.
6207       CommuteVectorShuffleMask(PermMask, 4);
6208       std::swap(V1, V2);
6209     }
6210
6211     // Find the element from V2.
6212     unsigned HiIndex;
6213     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6214       int Val = PermMask[HiIndex];
6215       if (Val < 0)
6216         continue;
6217       if (Val >= 4)
6218         break;
6219     }
6220
6221     Mask1[0] = PermMask[HiIndex];
6222     Mask1[1] = -1;
6223     Mask1[2] = PermMask[HiIndex^1];
6224     Mask1[3] = -1;
6225     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6226
6227     if (HiIndex >= 2) {
6228       Mask1[0] = PermMask[0];
6229       Mask1[1] = PermMask[1];
6230       Mask1[2] = HiIndex & 1 ? 6 : 4;
6231       Mask1[3] = HiIndex & 1 ? 4 : 6;
6232       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6233     }
6234
6235     Mask1[0] = HiIndex & 1 ? 2 : 0;
6236     Mask1[1] = HiIndex & 1 ? 0 : 2;
6237     Mask1[2] = PermMask[2];
6238     Mask1[3] = PermMask[3];
6239     if (Mask1[2] >= 0)
6240       Mask1[2] += 4;
6241     if (Mask1[3] >= 0)
6242       Mask1[3] += 4;
6243     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6244   }
6245
6246   // Break it into (shuffle shuffle_hi, shuffle_lo).
6247   int LoMask[] = { -1, -1, -1, -1 };
6248   int HiMask[] = { -1, -1, -1, -1 };
6249
6250   int *MaskPtr = LoMask;
6251   unsigned MaskIdx = 0;
6252   unsigned LoIdx = 0;
6253   unsigned HiIdx = 2;
6254   for (unsigned i = 0; i != 4; ++i) {
6255     if (i == 2) {
6256       MaskPtr = HiMask;
6257       MaskIdx = 1;
6258       LoIdx = 0;
6259       HiIdx = 2;
6260     }
6261     int Idx = PermMask[i];
6262     if (Idx < 0) {
6263       Locs[i] = std::make_pair(-1, -1);
6264     } else if (Idx < 4) {
6265       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6266       MaskPtr[LoIdx] = Idx;
6267       LoIdx++;
6268     } else {
6269       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6270       MaskPtr[HiIdx] = Idx;
6271       HiIdx++;
6272     }
6273   }
6274
6275   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6276   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6277   int MaskOps[] = { -1, -1, -1, -1 };
6278   for (unsigned i = 0; i != 4; ++i)
6279     if (Locs[i].first != -1)
6280       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6281   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6282 }
6283
6284 static bool MayFoldVectorLoad(SDValue V) {
6285   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6286     V = V.getOperand(0);
6287   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6288     V = V.getOperand(0);
6289   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6290       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6291     // BUILD_VECTOR (load), undef
6292     V = V.getOperand(0);
6293   if (MayFoldLoad(V))
6294     return true;
6295   return false;
6296 }
6297
6298 // FIXME: the version above should always be used. Since there's
6299 // a bug where several vector shuffles can't be folded because the
6300 // DAG is not updated during lowering and a node claims to have two
6301 // uses while it only has one, use this version, and let isel match
6302 // another instruction if the load really happens to have more than
6303 // one use. Remove this version after this bug get fixed.
6304 // rdar://8434668, PR8156
6305 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6306   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6307     V = V.getOperand(0);
6308   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6309     V = V.getOperand(0);
6310   if (ISD::isNormalLoad(V.getNode()))
6311     return true;
6312   return false;
6313 }
6314
6315 static
6316 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6317   EVT VT = Op.getValueType();
6318
6319   // Canonizalize to v2f64.
6320   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6321   return DAG.getNode(ISD::BITCAST, dl, VT,
6322                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6323                                           V1, DAG));
6324 }
6325
6326 static
6327 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6328                         bool HasSSE2) {
6329   SDValue V1 = Op.getOperand(0);
6330   SDValue V2 = Op.getOperand(1);
6331   EVT VT = Op.getValueType();
6332
6333   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6334
6335   if (HasSSE2 && VT == MVT::v2f64)
6336     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6337
6338   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6339   return DAG.getNode(ISD::BITCAST, dl, VT,
6340                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6341                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6342                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6343 }
6344
6345 static
6346 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6347   SDValue V1 = Op.getOperand(0);
6348   SDValue V2 = Op.getOperand(1);
6349   EVT VT = Op.getValueType();
6350
6351   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6352          "unsupported shuffle type");
6353
6354   if (V2.getOpcode() == ISD::UNDEF)
6355     V2 = V1;
6356
6357   // v4i32 or v4f32
6358   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6359 }
6360
6361 static
6362 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6363   SDValue V1 = Op.getOperand(0);
6364   SDValue V2 = Op.getOperand(1);
6365   EVT VT = Op.getValueType();
6366   unsigned NumElems = VT.getVectorNumElements();
6367
6368   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6369   // operand of these instructions is only memory, so check if there's a
6370   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6371   // same masks.
6372   bool CanFoldLoad = false;
6373
6374   // Trivial case, when V2 comes from a load.
6375   if (MayFoldVectorLoad(V2))
6376     CanFoldLoad = true;
6377
6378   // When V1 is a load, it can be folded later into a store in isel, example:
6379   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6380   //    turns into:
6381   //  (MOVLPSmr addr:$src1, VR128:$src2)
6382   // So, recognize this potential and also use MOVLPS or MOVLPD
6383   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6384     CanFoldLoad = true;
6385
6386   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6387   if (CanFoldLoad) {
6388     if (HasSSE2 && NumElems == 2)
6389       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6390
6391     if (NumElems == 4)
6392       // If we don't care about the second element, proceed to use movss.
6393       if (SVOp->getMaskElt(1) != -1)
6394         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6395   }
6396
6397   // movl and movlp will both match v2i64, but v2i64 is never matched by
6398   // movl earlier because we make it strict to avoid messing with the movlp load
6399   // folding logic (see the code above getMOVLP call). Match it here then,
6400   // this is horrible, but will stay like this until we move all shuffle
6401   // matching to x86 specific nodes. Note that for the 1st condition all
6402   // types are matched with movsd.
6403   if (HasSSE2) {
6404     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6405     // as to remove this logic from here, as much as possible
6406     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6407       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6408     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6409   }
6410
6411   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6412
6413   // Invert the operand order and use SHUFPS to match it.
6414   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6415                               getShuffleSHUFImmediate(SVOp), DAG);
6416 }
6417
6418 SDValue
6419 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6420   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6421   EVT VT = Op.getValueType();
6422   DebugLoc dl = Op.getDebugLoc();
6423   SDValue V1 = Op.getOperand(0);
6424   SDValue V2 = Op.getOperand(1);
6425
6426   if (isZeroShuffle(SVOp))
6427     return getZeroVector(VT, Subtarget, DAG, dl);
6428
6429   // Handle splat operations
6430   if (SVOp->isSplat()) {
6431     unsigned NumElem = VT.getVectorNumElements();
6432     int Size = VT.getSizeInBits();
6433
6434     // Use vbroadcast whenever the splat comes from a foldable load
6435     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6436     if (Broadcast.getNode())
6437       return Broadcast;
6438
6439     // Handle splats by matching through known shuffle masks
6440     if ((Size == 128 && NumElem <= 4) ||
6441         (Size == 256 && NumElem < 8))
6442       return SDValue();
6443
6444     // All remaning splats are promoted to target supported vector shuffles.
6445     return PromoteSplat(SVOp, DAG);
6446   }
6447
6448   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6449   // do it!
6450   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6451       VT == MVT::v16i16 || VT == MVT::v32i8) {
6452     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6453     if (NewOp.getNode())
6454       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6455   } else if ((VT == MVT::v4i32 ||
6456              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6457     // FIXME: Figure out a cleaner way to do this.
6458     // Try to make use of movq to zero out the top part.
6459     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6460       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6461       if (NewOp.getNode()) {
6462         EVT NewVT = NewOp.getValueType();
6463         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6464                                NewVT, true, false))
6465           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6466                               DAG, Subtarget, dl);
6467       }
6468     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6469       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6470       if (NewOp.getNode()) {
6471         EVT NewVT = NewOp.getValueType();
6472         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6473           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6474                               DAG, Subtarget, dl);
6475       }
6476     }
6477   }
6478   return SDValue();
6479 }
6480
6481 SDValue
6482 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6483   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6484   SDValue V1 = Op.getOperand(0);
6485   SDValue V2 = Op.getOperand(1);
6486   EVT VT = Op.getValueType();
6487   DebugLoc dl = Op.getDebugLoc();
6488   unsigned NumElems = VT.getVectorNumElements();
6489   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6490   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6491   bool V1IsSplat = false;
6492   bool V2IsSplat = false;
6493   bool HasSSE2 = Subtarget->hasSSE2();
6494   bool HasAVX    = Subtarget->hasAVX();
6495   bool HasAVX2   = Subtarget->hasAVX2();
6496   MachineFunction &MF = DAG.getMachineFunction();
6497   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6498
6499   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6500
6501   if (V1IsUndef && V2IsUndef)
6502     return DAG.getUNDEF(VT);
6503
6504   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6505
6506   // Vector shuffle lowering takes 3 steps:
6507   //
6508   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6509   //    narrowing and commutation of operands should be handled.
6510   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6511   //    shuffle nodes.
6512   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6513   //    so the shuffle can be broken into other shuffles and the legalizer can
6514   //    try the lowering again.
6515   //
6516   // The general idea is that no vector_shuffle operation should be left to
6517   // be matched during isel, all of them must be converted to a target specific
6518   // node here.
6519
6520   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6521   // narrowing and commutation of operands should be handled. The actual code
6522   // doesn't include all of those, work in progress...
6523   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6524   if (NewOp.getNode())
6525     return NewOp;
6526
6527   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6528
6529   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6530   // unpckh_undef). Only use pshufd if speed is more important than size.
6531   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6532     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6533   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6534     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6535
6536   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6537       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6538     return getMOVDDup(Op, dl, V1, DAG);
6539
6540   if (isMOVHLPS_v_undef_Mask(M, VT))
6541     return getMOVHighToLow(Op, dl, DAG);
6542
6543   // Use to match splats
6544   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6545       (VT == MVT::v2f64 || VT == MVT::v2i64))
6546     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6547
6548   if (isPSHUFDMask(M, VT)) {
6549     // The actual implementation will match the mask in the if above and then
6550     // during isel it can match several different instructions, not only pshufd
6551     // as its name says, sad but true, emulate the behavior for now...
6552     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6553       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6554
6555     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6556
6557     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6558       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6559
6560     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6561       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6562
6563     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6564                                 TargetMask, DAG);
6565   }
6566
6567   // Check if this can be converted into a logical shift.
6568   bool isLeft = false;
6569   unsigned ShAmt = 0;
6570   SDValue ShVal;
6571   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6572   if (isShift && ShVal.hasOneUse()) {
6573     // If the shifted value has multiple uses, it may be cheaper to use
6574     // v_set0 + movlhps or movhlps, etc.
6575     EVT EltVT = VT.getVectorElementType();
6576     ShAmt *= EltVT.getSizeInBits();
6577     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6578   }
6579
6580   if (isMOVLMask(M, VT)) {
6581     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6582       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6583     if (!isMOVLPMask(M, VT)) {
6584       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6585         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6586
6587       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6588         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6589     }
6590   }
6591
6592   // FIXME: fold these into legal mask.
6593   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6594     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6595
6596   if (isMOVHLPSMask(M, VT))
6597     return getMOVHighToLow(Op, dl, DAG);
6598
6599   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6600     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6601
6602   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6603     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6604
6605   if (isMOVLPMask(M, VT))
6606     return getMOVLP(Op, dl, DAG, HasSSE2);
6607
6608   if (ShouldXformToMOVHLPS(M, VT) ||
6609       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6610     return CommuteVectorShuffle(SVOp, DAG);
6611
6612   if (isShift) {
6613     // No better options. Use a vshldq / vsrldq.
6614     EVT EltVT = VT.getVectorElementType();
6615     ShAmt *= EltVT.getSizeInBits();
6616     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6617   }
6618
6619   bool Commuted = false;
6620   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6621   // 1,1,1,1 -> v8i16 though.
6622   V1IsSplat = isSplatVector(V1.getNode());
6623   V2IsSplat = isSplatVector(V2.getNode());
6624
6625   // Canonicalize the splat or undef, if present, to be on the RHS.
6626   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6627     CommuteVectorShuffleMask(M, NumElems);
6628     std::swap(V1, V2);
6629     std::swap(V1IsSplat, V2IsSplat);
6630     Commuted = true;
6631   }
6632
6633   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6634     // Shuffling low element of v1 into undef, just return v1.
6635     if (V2IsUndef)
6636       return V1;
6637     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6638     // the instruction selector will not match, so get a canonical MOVL with
6639     // swapped operands to undo the commute.
6640     return getMOVL(DAG, dl, VT, V2, V1);
6641   }
6642
6643   if (isUNPCKLMask(M, VT, HasAVX2))
6644     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6645
6646   if (isUNPCKHMask(M, VT, HasAVX2))
6647     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6648
6649   if (V2IsSplat) {
6650     // Normalize mask so all entries that point to V2 points to its first
6651     // element then try to match unpck{h|l} again. If match, return a
6652     // new vector_shuffle with the corrected mask.p
6653     SmallVector<int, 8> NewMask(M.begin(), M.end());
6654     NormalizeMask(NewMask, NumElems);
6655     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6656       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6657     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6658       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6659   }
6660
6661   if (Commuted) {
6662     // Commute is back and try unpck* again.
6663     // FIXME: this seems wrong.
6664     CommuteVectorShuffleMask(M, NumElems);
6665     std::swap(V1, V2);
6666     std::swap(V1IsSplat, V2IsSplat);
6667     Commuted = false;
6668
6669     if (isUNPCKLMask(M, VT, HasAVX2))
6670       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6671
6672     if (isUNPCKHMask(M, VT, HasAVX2))
6673       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6674   }
6675
6676   // Normalize the node to match x86 shuffle ops if needed
6677   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6678     return CommuteVectorShuffle(SVOp, DAG);
6679
6680   // The checks below are all present in isShuffleMaskLegal, but they are
6681   // inlined here right now to enable us to directly emit target specific
6682   // nodes, and remove one by one until they don't return Op anymore.
6683
6684   if (isPALIGNRMask(M, VT, Subtarget))
6685     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6686                                 getShufflePALIGNRImmediate(SVOp),
6687                                 DAG);
6688
6689   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6690       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6691     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6692       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6693   }
6694
6695   if (isPSHUFHWMask(M, VT, HasAVX2))
6696     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6697                                 getShufflePSHUFHWImmediate(SVOp),
6698                                 DAG);
6699
6700   if (isPSHUFLWMask(M, VT, HasAVX2))
6701     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6702                                 getShufflePSHUFLWImmediate(SVOp),
6703                                 DAG);
6704
6705   if (isSHUFPMask(M, VT, HasAVX))
6706     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6707                                 getShuffleSHUFImmediate(SVOp), DAG);
6708
6709   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6710     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6711   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6712     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6713
6714   //===--------------------------------------------------------------------===//
6715   // Generate target specific nodes for 128 or 256-bit shuffles only
6716   // supported in the AVX instruction set.
6717   //
6718
6719   // Handle VMOVDDUPY permutations
6720   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6721     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6722
6723   // Handle VPERMILPS/D* permutations
6724   if (isVPERMILPMask(M, VT, HasAVX)) {
6725     if (HasAVX2 && VT == MVT::v8i32)
6726       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6727                                   getShuffleSHUFImmediate(SVOp), DAG);
6728     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6729                                 getShuffleSHUFImmediate(SVOp), DAG);
6730   }
6731
6732   // Handle VPERM2F128/VPERM2I128 permutations
6733   if (isVPERM2X128Mask(M, VT, HasAVX))
6734     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6735                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6736
6737   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6738   if (BlendOp.getNode())
6739     return BlendOp;
6740
6741   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6742     SmallVector<SDValue, 8> permclMask;
6743     for (unsigned i = 0; i != 8; ++i) {
6744       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6745     }
6746     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6747                                &permclMask[0], 8);
6748     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6749     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6750                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6751   }
6752
6753   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6754     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6755                                 getShuffleCLImmediate(SVOp), DAG);
6756
6757
6758   //===--------------------------------------------------------------------===//
6759   // Since no target specific shuffle was selected for this generic one,
6760   // lower it into other known shuffles. FIXME: this isn't true yet, but
6761   // this is the plan.
6762   //
6763
6764   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6765   if (VT == MVT::v8i16) {
6766     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6767     if (NewOp.getNode())
6768       return NewOp;
6769   }
6770
6771   if (VT == MVT::v16i8) {
6772     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6773     if (NewOp.getNode())
6774       return NewOp;
6775   }
6776
6777   // Handle all 128-bit wide vectors with 4 elements, and match them with
6778   // several different shuffle types.
6779   if (NumElems == 4 && VT.getSizeInBits() == 128)
6780     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6781
6782   // Handle general 256-bit shuffles
6783   if (VT.is256BitVector())
6784     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6785
6786   return SDValue();
6787 }
6788
6789 SDValue
6790 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6791                                                 SelectionDAG &DAG) const {
6792   EVT VT = Op.getValueType();
6793   DebugLoc dl = Op.getDebugLoc();
6794
6795   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6796     return SDValue();
6797
6798   if (VT.getSizeInBits() == 8) {
6799     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6800                                     Op.getOperand(0), Op.getOperand(1));
6801     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6802                                     DAG.getValueType(VT));
6803     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6804   }
6805
6806   if (VT.getSizeInBits() == 16) {
6807     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6808     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6809     if (Idx == 0)
6810       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6811                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6812                                      DAG.getNode(ISD::BITCAST, dl,
6813                                                  MVT::v4i32,
6814                                                  Op.getOperand(0)),
6815                                      Op.getOperand(1)));
6816     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6817                                     Op.getOperand(0), Op.getOperand(1));
6818     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6819                                     DAG.getValueType(VT));
6820     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6821   }
6822
6823   if (VT == MVT::f32) {
6824     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6825     // the result back to FR32 register. It's only worth matching if the
6826     // result has a single use which is a store or a bitcast to i32.  And in
6827     // the case of a store, it's not worth it if the index is a constant 0,
6828     // because a MOVSSmr can be used instead, which is smaller and faster.
6829     if (!Op.hasOneUse())
6830       return SDValue();
6831     SDNode *User = *Op.getNode()->use_begin();
6832     if ((User->getOpcode() != ISD::STORE ||
6833          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6834           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6835         (User->getOpcode() != ISD::BITCAST ||
6836          User->getValueType(0) != MVT::i32))
6837       return SDValue();
6838     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6839                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6840                                               Op.getOperand(0)),
6841                                               Op.getOperand(1));
6842     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6843   }
6844
6845   if (VT == MVT::i32 || VT == MVT::i64) {
6846     // ExtractPS/pextrq works with constant index.
6847     if (isa<ConstantSDNode>(Op.getOperand(1)))
6848       return Op;
6849   }
6850   return SDValue();
6851 }
6852
6853
6854 SDValue
6855 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6856                                            SelectionDAG &DAG) const {
6857   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6858     return SDValue();
6859
6860   SDValue Vec = Op.getOperand(0);
6861   EVT VecVT = Vec.getValueType();
6862
6863   // If this is a 256-bit vector result, first extract the 128-bit vector and
6864   // then extract the element from the 128-bit vector.
6865   if (VecVT.getSizeInBits() == 256) {
6866     DebugLoc dl = Op.getNode()->getDebugLoc();
6867     unsigned NumElems = VecVT.getVectorNumElements();
6868     SDValue Idx = Op.getOperand(1);
6869     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6870
6871     // Get the 128-bit vector.
6872     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6873
6874     if (IdxVal >= NumElems/2)
6875       IdxVal -= NumElems/2;
6876     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6877                        DAG.getConstant(IdxVal, MVT::i32));
6878   }
6879
6880   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6881
6882   if (Subtarget->hasSSE41()) {
6883     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6884     if (Res.getNode())
6885       return Res;
6886   }
6887
6888   EVT VT = Op.getValueType();
6889   DebugLoc dl = Op.getDebugLoc();
6890   // TODO: handle v16i8.
6891   if (VT.getSizeInBits() == 16) {
6892     SDValue Vec = Op.getOperand(0);
6893     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6894     if (Idx == 0)
6895       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6896                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6897                                      DAG.getNode(ISD::BITCAST, dl,
6898                                                  MVT::v4i32, Vec),
6899                                      Op.getOperand(1)));
6900     // Transform it so it match pextrw which produces a 32-bit result.
6901     EVT EltVT = MVT::i32;
6902     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6903                                     Op.getOperand(0), Op.getOperand(1));
6904     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6905                                     DAG.getValueType(VT));
6906     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6907   }
6908
6909   if (VT.getSizeInBits() == 32) {
6910     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6911     if (Idx == 0)
6912       return Op;
6913
6914     // SHUFPS the element to the lowest double word, then movss.
6915     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6916     EVT VVT = Op.getOperand(0).getValueType();
6917     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6918                                        DAG.getUNDEF(VVT), Mask);
6919     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6920                        DAG.getIntPtrConstant(0));
6921   }
6922
6923   if (VT.getSizeInBits() == 64) {
6924     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6925     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6926     //        to match extract_elt for f64.
6927     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6928     if (Idx == 0)
6929       return Op;
6930
6931     // UNPCKHPD the element to the lowest double word, then movsd.
6932     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6933     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6934     int Mask[2] = { 1, -1 };
6935     EVT VVT = Op.getOperand(0).getValueType();
6936     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6937                                        DAG.getUNDEF(VVT), Mask);
6938     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6939                        DAG.getIntPtrConstant(0));
6940   }
6941
6942   return SDValue();
6943 }
6944
6945 SDValue
6946 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6947                                                SelectionDAG &DAG) const {
6948   EVT VT = Op.getValueType();
6949   EVT EltVT = VT.getVectorElementType();
6950   DebugLoc dl = Op.getDebugLoc();
6951
6952   SDValue N0 = Op.getOperand(0);
6953   SDValue N1 = Op.getOperand(1);
6954   SDValue N2 = Op.getOperand(2);
6955
6956   if (VT.getSizeInBits() == 256)
6957     return SDValue();
6958
6959   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6960       isa<ConstantSDNode>(N2)) {
6961     unsigned Opc;
6962     if (VT == MVT::v8i16)
6963       Opc = X86ISD::PINSRW;
6964     else if (VT == MVT::v16i8)
6965       Opc = X86ISD::PINSRB;
6966     else
6967       Opc = X86ISD::PINSRB;
6968
6969     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6970     // argument.
6971     if (N1.getValueType() != MVT::i32)
6972       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6973     if (N2.getValueType() != MVT::i32)
6974       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6975     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6976   }
6977
6978   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6979     // Bits [7:6] of the constant are the source select.  This will always be
6980     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6981     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6982     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6983     // Bits [5:4] of the constant are the destination select.  This is the
6984     //  value of the incoming immediate.
6985     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6986     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6987     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6988     // Create this as a scalar to vector..
6989     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6990     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6991   }
6992
6993   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
6994     // PINSR* works with constant index.
6995     return Op;
6996   }
6997   return SDValue();
6998 }
6999
7000 SDValue
7001 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7002   EVT VT = Op.getValueType();
7003   EVT EltVT = VT.getVectorElementType();
7004
7005   DebugLoc dl = Op.getDebugLoc();
7006   SDValue N0 = Op.getOperand(0);
7007   SDValue N1 = Op.getOperand(1);
7008   SDValue N2 = Op.getOperand(2);
7009
7010   // If this is a 256-bit vector result, first extract the 128-bit vector,
7011   // insert the element into the extracted half and then place it back.
7012   if (VT.getSizeInBits() == 256) {
7013     if (!isa<ConstantSDNode>(N2))
7014       return SDValue();
7015
7016     // Get the desired 128-bit vector half.
7017     unsigned NumElems = VT.getVectorNumElements();
7018     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7019     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7020
7021     // Insert the element into the desired half.
7022     bool Upper = IdxVal >= NumElems/2;
7023     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7024                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7025
7026     // Insert the changed part back to the 256-bit vector
7027     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7028   }
7029
7030   if (Subtarget->hasSSE41())
7031     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7032
7033   if (EltVT == MVT::i8)
7034     return SDValue();
7035
7036   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7037     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7038     // as its second argument.
7039     if (N1.getValueType() != MVT::i32)
7040       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7041     if (N2.getValueType() != MVT::i32)
7042       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7043     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7044   }
7045   return SDValue();
7046 }
7047
7048 SDValue
7049 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7050   LLVMContext *Context = DAG.getContext();
7051   DebugLoc dl = Op.getDebugLoc();
7052   EVT OpVT = Op.getValueType();
7053
7054   // If this is a 256-bit vector result, first insert into a 128-bit
7055   // vector and then insert into the 256-bit vector.
7056   if (OpVT.getSizeInBits() > 128) {
7057     // Insert into a 128-bit vector.
7058     EVT VT128 = EVT::getVectorVT(*Context,
7059                                  OpVT.getVectorElementType(),
7060                                  OpVT.getVectorNumElements() / 2);
7061
7062     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7063
7064     // Insert the 128-bit vector.
7065     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7066   }
7067
7068   if (OpVT == MVT::v1i64 &&
7069       Op.getOperand(0).getValueType() == MVT::i64)
7070     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7071
7072   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7073   assert(OpVT.getSizeInBits() == 128 && "Expected an SSE type!");
7074   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7075                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7076 }
7077
7078 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7079 // a simple subregister reference or explicit instructions to grab
7080 // upper bits of a vector.
7081 SDValue
7082 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7083   if (Subtarget->hasAVX()) {
7084     DebugLoc dl = Op.getNode()->getDebugLoc();
7085     SDValue Vec = Op.getNode()->getOperand(0);
7086     SDValue Idx = Op.getNode()->getOperand(1);
7087
7088     if (Op.getNode()->getValueType(0).getSizeInBits() == 128 &&
7089         Vec.getNode()->getValueType(0).getSizeInBits() == 256 &&
7090         isa<ConstantSDNode>(Idx)) {
7091       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7092       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7093     }
7094   }
7095   return SDValue();
7096 }
7097
7098 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7099 // simple superregister reference or explicit instructions to insert
7100 // the upper bits of a vector.
7101 SDValue
7102 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7103   if (Subtarget->hasAVX()) {
7104     DebugLoc dl = Op.getNode()->getDebugLoc();
7105     SDValue Vec = Op.getNode()->getOperand(0);
7106     SDValue SubVec = Op.getNode()->getOperand(1);
7107     SDValue Idx = Op.getNode()->getOperand(2);
7108
7109     if (Op.getNode()->getValueType(0).getSizeInBits() == 256 &&
7110         SubVec.getNode()->getValueType(0).getSizeInBits() == 128 &&
7111         isa<ConstantSDNode>(Idx)) {
7112       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7113       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7114     }
7115   }
7116   return SDValue();
7117 }
7118
7119 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7120 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7121 // one of the above mentioned nodes. It has to be wrapped because otherwise
7122 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7123 // be used to form addressing mode. These wrapped nodes will be selected
7124 // into MOV32ri.
7125 SDValue
7126 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7127   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7128
7129   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7130   // global base reg.
7131   unsigned char OpFlag = 0;
7132   unsigned WrapperKind = X86ISD::Wrapper;
7133   CodeModel::Model M = getTargetMachine().getCodeModel();
7134
7135   if (Subtarget->isPICStyleRIPRel() &&
7136       (M == CodeModel::Small || M == CodeModel::Kernel))
7137     WrapperKind = X86ISD::WrapperRIP;
7138   else if (Subtarget->isPICStyleGOT())
7139     OpFlag = X86II::MO_GOTOFF;
7140   else if (Subtarget->isPICStyleStubPIC())
7141     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7142
7143   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7144                                              CP->getAlignment(),
7145                                              CP->getOffset(), OpFlag);
7146   DebugLoc DL = CP->getDebugLoc();
7147   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7148   // With PIC, the address is actually $g + Offset.
7149   if (OpFlag) {
7150     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7151                          DAG.getNode(X86ISD::GlobalBaseReg,
7152                                      DebugLoc(), getPointerTy()),
7153                          Result);
7154   }
7155
7156   return Result;
7157 }
7158
7159 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7160   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7161
7162   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7163   // global base reg.
7164   unsigned char OpFlag = 0;
7165   unsigned WrapperKind = X86ISD::Wrapper;
7166   CodeModel::Model M = getTargetMachine().getCodeModel();
7167
7168   if (Subtarget->isPICStyleRIPRel() &&
7169       (M == CodeModel::Small || M == CodeModel::Kernel))
7170     WrapperKind = X86ISD::WrapperRIP;
7171   else if (Subtarget->isPICStyleGOT())
7172     OpFlag = X86II::MO_GOTOFF;
7173   else if (Subtarget->isPICStyleStubPIC())
7174     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7175
7176   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7177                                           OpFlag);
7178   DebugLoc DL = JT->getDebugLoc();
7179   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7180
7181   // With PIC, the address is actually $g + Offset.
7182   if (OpFlag)
7183     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7184                          DAG.getNode(X86ISD::GlobalBaseReg,
7185                                      DebugLoc(), getPointerTy()),
7186                          Result);
7187
7188   return Result;
7189 }
7190
7191 SDValue
7192 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7193   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7194
7195   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7196   // global base reg.
7197   unsigned char OpFlag = 0;
7198   unsigned WrapperKind = X86ISD::Wrapper;
7199   CodeModel::Model M = getTargetMachine().getCodeModel();
7200
7201   if (Subtarget->isPICStyleRIPRel() &&
7202       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7203     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7204       OpFlag = X86II::MO_GOTPCREL;
7205     WrapperKind = X86ISD::WrapperRIP;
7206   } else if (Subtarget->isPICStyleGOT()) {
7207     OpFlag = X86II::MO_GOT;
7208   } else if (Subtarget->isPICStyleStubPIC()) {
7209     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7210   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7211     OpFlag = X86II::MO_DARWIN_NONLAZY;
7212   }
7213
7214   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7215
7216   DebugLoc DL = Op.getDebugLoc();
7217   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7218
7219
7220   // With PIC, the address is actually $g + Offset.
7221   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7222       !Subtarget->is64Bit()) {
7223     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7224                          DAG.getNode(X86ISD::GlobalBaseReg,
7225                                      DebugLoc(), getPointerTy()),
7226                          Result);
7227   }
7228
7229   // For symbols that require a load from a stub to get the address, emit the
7230   // load.
7231   if (isGlobalStubReference(OpFlag))
7232     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7233                          MachinePointerInfo::getGOT(), false, false, false, 0);
7234
7235   return Result;
7236 }
7237
7238 SDValue
7239 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7240   // Create the TargetBlockAddressAddress node.
7241   unsigned char OpFlags =
7242     Subtarget->ClassifyBlockAddressReference();
7243   CodeModel::Model M = getTargetMachine().getCodeModel();
7244   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7245   DebugLoc dl = Op.getDebugLoc();
7246   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7247                                        /*isTarget=*/true, OpFlags);
7248
7249   if (Subtarget->isPICStyleRIPRel() &&
7250       (M == CodeModel::Small || M == CodeModel::Kernel))
7251     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7252   else
7253     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7254
7255   // With PIC, the address is actually $g + Offset.
7256   if (isGlobalRelativeToPICBase(OpFlags)) {
7257     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7258                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7259                          Result);
7260   }
7261
7262   return Result;
7263 }
7264
7265 SDValue
7266 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7267                                       int64_t Offset,
7268                                       SelectionDAG &DAG) const {
7269   // Create the TargetGlobalAddress node, folding in the constant
7270   // offset if it is legal.
7271   unsigned char OpFlags =
7272     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7273   CodeModel::Model M = getTargetMachine().getCodeModel();
7274   SDValue Result;
7275   if (OpFlags == X86II::MO_NO_FLAG &&
7276       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7277     // A direct static reference to a global.
7278     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7279     Offset = 0;
7280   } else {
7281     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7282   }
7283
7284   if (Subtarget->isPICStyleRIPRel() &&
7285       (M == CodeModel::Small || M == CodeModel::Kernel))
7286     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7287   else
7288     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7289
7290   // With PIC, the address is actually $g + Offset.
7291   if (isGlobalRelativeToPICBase(OpFlags)) {
7292     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7293                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7294                          Result);
7295   }
7296
7297   // For globals that require a load from a stub to get the address, emit the
7298   // load.
7299   if (isGlobalStubReference(OpFlags))
7300     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7301                          MachinePointerInfo::getGOT(), false, false, false, 0);
7302
7303   // If there was a non-zero offset that we didn't fold, create an explicit
7304   // addition for it.
7305   if (Offset != 0)
7306     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7307                          DAG.getConstant(Offset, getPointerTy()));
7308
7309   return Result;
7310 }
7311
7312 SDValue
7313 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7314   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7315   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7316   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7317 }
7318
7319 static SDValue
7320 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7321            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7322            unsigned char OperandFlags, bool LocalDynamic = false) {
7323   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7324   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7325   DebugLoc dl = GA->getDebugLoc();
7326   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7327                                            GA->getValueType(0),
7328                                            GA->getOffset(),
7329                                            OperandFlags);
7330
7331   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7332                                            : X86ISD::TLSADDR;
7333
7334   if (InFlag) {
7335     SDValue Ops[] = { Chain,  TGA, *InFlag };
7336     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7337   } else {
7338     SDValue Ops[]  = { Chain, TGA };
7339     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7340   }
7341
7342   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7343   MFI->setAdjustsStack(true);
7344
7345   SDValue Flag = Chain.getValue(1);
7346   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7347 }
7348
7349 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7350 static SDValue
7351 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7352                                 const EVT PtrVT) {
7353   SDValue InFlag;
7354   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7355   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7356                                      DAG.getNode(X86ISD::GlobalBaseReg,
7357                                                  DebugLoc(), PtrVT), InFlag);
7358   InFlag = Chain.getValue(1);
7359
7360   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7361 }
7362
7363 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7364 static SDValue
7365 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7366                                 const EVT PtrVT) {
7367   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7368                     X86::RAX, X86II::MO_TLSGD);
7369 }
7370
7371 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7372                                            SelectionDAG &DAG,
7373                                            const EVT PtrVT,
7374                                            bool is64Bit) {
7375   DebugLoc dl = GA->getDebugLoc();
7376
7377   // Get the start address of the TLS block for this module.
7378   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7379       .getInfo<X86MachineFunctionInfo>();
7380   MFI->incNumLocalDynamicTLSAccesses();
7381
7382   SDValue Base;
7383   if (is64Bit) {
7384     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7385                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7386   } else {
7387     SDValue InFlag;
7388     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7389         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7390     InFlag = Chain.getValue(1);
7391     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7392                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7393   }
7394
7395   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7396   // of Base.
7397
7398   // Build x@dtpoff.
7399   unsigned char OperandFlags = X86II::MO_DTPOFF;
7400   unsigned WrapperKind = X86ISD::Wrapper;
7401   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7402                                            GA->getValueType(0),
7403                                            GA->getOffset(), OperandFlags);
7404   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7405
7406   // Add x@dtpoff with the base.
7407   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7408 }
7409
7410 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7411 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7412                                    const EVT PtrVT, TLSModel::Model model,
7413                                    bool is64Bit, bool isPIC) {
7414   DebugLoc dl = GA->getDebugLoc();
7415
7416   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7417   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7418                                                          is64Bit ? 257 : 256));
7419
7420   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7421                                       DAG.getIntPtrConstant(0),
7422                                       MachinePointerInfo(Ptr),
7423                                       false, false, false, 0);
7424
7425   unsigned char OperandFlags = 0;
7426   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7427   // initialexec.
7428   unsigned WrapperKind = X86ISD::Wrapper;
7429   if (model == TLSModel::LocalExec) {
7430     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7431   } else if (model == TLSModel::InitialExec) {
7432     if (is64Bit) {
7433       OperandFlags = X86II::MO_GOTTPOFF;
7434       WrapperKind = X86ISD::WrapperRIP;
7435     } else {
7436       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7437     }
7438   } else {
7439     llvm_unreachable("Unexpected model");
7440   }
7441
7442   // emit "addl x@ntpoff,%eax" (local exec)
7443   // or "addl x@indntpoff,%eax" (initial exec)
7444   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7445   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7446                                            GA->getValueType(0),
7447                                            GA->getOffset(), OperandFlags);
7448   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7449
7450   if (model == TLSModel::InitialExec) {
7451     if (isPIC && !is64Bit) {
7452       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7453                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7454                            Offset);
7455     }
7456
7457     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7458                          MachinePointerInfo::getGOT(), false, false, false,
7459                          0);
7460   }
7461
7462   // The address of the thread local variable is the add of the thread
7463   // pointer with the offset of the variable.
7464   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7465 }
7466
7467 SDValue
7468 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7469
7470   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7471   const GlobalValue *GV = GA->getGlobal();
7472
7473   if (Subtarget->isTargetELF()) {
7474     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7475
7476     switch (model) {
7477       case TLSModel::GeneralDynamic:
7478         if (Subtarget->is64Bit())
7479           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7480         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7481       case TLSModel::LocalDynamic:
7482         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7483                                            Subtarget->is64Bit());
7484       case TLSModel::InitialExec:
7485       case TLSModel::LocalExec:
7486         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7487                                    Subtarget->is64Bit(),
7488                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7489     }
7490     llvm_unreachable("Unknown TLS model.");
7491   }
7492
7493   if (Subtarget->isTargetDarwin()) {
7494     // Darwin only has one model of TLS.  Lower to that.
7495     unsigned char OpFlag = 0;
7496     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7497                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7498
7499     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7500     // global base reg.
7501     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7502                   !Subtarget->is64Bit();
7503     if (PIC32)
7504       OpFlag = X86II::MO_TLVP_PIC_BASE;
7505     else
7506       OpFlag = X86II::MO_TLVP;
7507     DebugLoc DL = Op.getDebugLoc();
7508     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7509                                                 GA->getValueType(0),
7510                                                 GA->getOffset(), OpFlag);
7511     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7512
7513     // With PIC32, the address is actually $g + Offset.
7514     if (PIC32)
7515       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7516                            DAG.getNode(X86ISD::GlobalBaseReg,
7517                                        DebugLoc(), getPointerTy()),
7518                            Offset);
7519
7520     // Lowering the machine isd will make sure everything is in the right
7521     // location.
7522     SDValue Chain = DAG.getEntryNode();
7523     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7524     SDValue Args[] = { Chain, Offset };
7525     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7526
7527     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7528     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7529     MFI->setAdjustsStack(true);
7530
7531     // And our return value (tls address) is in the standard call return value
7532     // location.
7533     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7534     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7535                               Chain.getValue(1));
7536   }
7537
7538   if (Subtarget->isTargetWindows()) {
7539     // Just use the implicit TLS architecture
7540     // Need to generate someting similar to:
7541     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7542     //                                  ; from TEB
7543     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7544     //   mov     rcx, qword [rdx+rcx*8]
7545     //   mov     eax, .tls$:tlsvar
7546     //   [rax+rcx] contains the address
7547     // Windows 64bit: gs:0x58
7548     // Windows 32bit: fs:__tls_array
7549
7550     // If GV is an alias then use the aliasee for determining
7551     // thread-localness.
7552     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7553       GV = GA->resolveAliasedGlobal(false);
7554     DebugLoc dl = GA->getDebugLoc();
7555     SDValue Chain = DAG.getEntryNode();
7556
7557     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7558     // %gs:0x58 (64-bit).
7559     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7560                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7561                                                              256)
7562                                         : Type::getInt32PtrTy(*DAG.getContext(),
7563                                                               257));
7564
7565     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7566                                         Subtarget->is64Bit()
7567                                         ? DAG.getIntPtrConstant(0x58)
7568                                         : DAG.getExternalSymbol("_tls_array",
7569                                                                 getPointerTy()),
7570                                         MachinePointerInfo(Ptr),
7571                                         false, false, false, 0);
7572
7573     // Load the _tls_index variable
7574     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7575     if (Subtarget->is64Bit())
7576       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7577                            IDX, MachinePointerInfo(), MVT::i32,
7578                            false, false, 0);
7579     else
7580       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7581                         false, false, false, 0);
7582
7583     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7584                                     getPointerTy());
7585     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7586
7587     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7588     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7589                       false, false, false, 0);
7590
7591     // Get the offset of start of .tls section
7592     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7593                                              GA->getValueType(0),
7594                                              GA->getOffset(), X86II::MO_SECREL);
7595     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7596
7597     // The address of the thread local variable is the add of the thread
7598     // pointer with the offset of the variable.
7599     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7600   }
7601
7602   llvm_unreachable("TLS not implemented for this target.");
7603 }
7604
7605
7606 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7607 /// and take a 2 x i32 value to shift plus a shift amount.
7608 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7609   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7610   EVT VT = Op.getValueType();
7611   unsigned VTBits = VT.getSizeInBits();
7612   DebugLoc dl = Op.getDebugLoc();
7613   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7614   SDValue ShOpLo = Op.getOperand(0);
7615   SDValue ShOpHi = Op.getOperand(1);
7616   SDValue ShAmt  = Op.getOperand(2);
7617   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7618                                      DAG.getConstant(VTBits - 1, MVT::i8))
7619                        : DAG.getConstant(0, VT);
7620
7621   SDValue Tmp2, Tmp3;
7622   if (Op.getOpcode() == ISD::SHL_PARTS) {
7623     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7624     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7625   } else {
7626     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7627     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7628   }
7629
7630   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7631                                 DAG.getConstant(VTBits, MVT::i8));
7632   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7633                              AndNode, DAG.getConstant(0, MVT::i8));
7634
7635   SDValue Hi, Lo;
7636   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7637   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7638   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7639
7640   if (Op.getOpcode() == ISD::SHL_PARTS) {
7641     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7642     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7643   } else {
7644     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7645     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7646   }
7647
7648   SDValue Ops[2] = { Lo, Hi };
7649   return DAG.getMergeValues(Ops, 2, dl);
7650 }
7651
7652 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7653                                            SelectionDAG &DAG) const {
7654   EVT SrcVT = Op.getOperand(0).getValueType();
7655
7656   if (SrcVT.isVector())
7657     return SDValue();
7658
7659   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7660          "Unknown SINT_TO_FP to lower!");
7661
7662   // These are really Legal; return the operand so the caller accepts it as
7663   // Legal.
7664   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7665     return Op;
7666   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7667       Subtarget->is64Bit()) {
7668     return Op;
7669   }
7670
7671   DebugLoc dl = Op.getDebugLoc();
7672   unsigned Size = SrcVT.getSizeInBits()/8;
7673   MachineFunction &MF = DAG.getMachineFunction();
7674   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7675   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7676   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7677                                StackSlot,
7678                                MachinePointerInfo::getFixedStack(SSFI),
7679                                false, false, 0);
7680   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7681 }
7682
7683 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7684                                      SDValue StackSlot,
7685                                      SelectionDAG &DAG) const {
7686   // Build the FILD
7687   DebugLoc DL = Op.getDebugLoc();
7688   SDVTList Tys;
7689   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7690   if (useSSE)
7691     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7692   else
7693     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7694
7695   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7696
7697   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7698   MachineMemOperand *MMO;
7699   if (FI) {
7700     int SSFI = FI->getIndex();
7701     MMO =
7702       DAG.getMachineFunction()
7703       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7704                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7705   } else {
7706     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7707     StackSlot = StackSlot.getOperand(1);
7708   }
7709   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7710   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7711                                            X86ISD::FILD, DL,
7712                                            Tys, Ops, array_lengthof(Ops),
7713                                            SrcVT, MMO);
7714
7715   if (useSSE) {
7716     Chain = Result.getValue(1);
7717     SDValue InFlag = Result.getValue(2);
7718
7719     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7720     // shouldn't be necessary except that RFP cannot be live across
7721     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7722     MachineFunction &MF = DAG.getMachineFunction();
7723     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7724     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7725     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7726     Tys = DAG.getVTList(MVT::Other);
7727     SDValue Ops[] = {
7728       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7729     };
7730     MachineMemOperand *MMO =
7731       DAG.getMachineFunction()
7732       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7733                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7734
7735     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7736                                     Ops, array_lengthof(Ops),
7737                                     Op.getValueType(), MMO);
7738     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7739                          MachinePointerInfo::getFixedStack(SSFI),
7740                          false, false, false, 0);
7741   }
7742
7743   return Result;
7744 }
7745
7746 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7747 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7748                                                SelectionDAG &DAG) const {
7749   // This algorithm is not obvious. Here it is what we're trying to output:
7750   /*
7751      movq       %rax,  %xmm0
7752      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7753      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7754      #ifdef __SSE3__
7755        haddpd   %xmm0, %xmm0
7756      #else
7757        pshufd   $0x4e, %xmm0, %xmm1
7758        addpd    %xmm1, %xmm0
7759      #endif
7760   */
7761
7762   DebugLoc dl = Op.getDebugLoc();
7763   LLVMContext *Context = DAG.getContext();
7764
7765   // Build some magic constants.
7766   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7767   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7768   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7769
7770   SmallVector<Constant*,2> CV1;
7771   CV1.push_back(
7772         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7773   CV1.push_back(
7774         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7775   Constant *C1 = ConstantVector::get(CV1);
7776   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7777
7778   // Load the 64-bit value into an XMM register.
7779   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7780                             Op.getOperand(0));
7781   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7782                               MachinePointerInfo::getConstantPool(),
7783                               false, false, false, 16);
7784   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7785                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7786                               CLod0);
7787
7788   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7789                               MachinePointerInfo::getConstantPool(),
7790                               false, false, false, 16);
7791   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7792   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7793   SDValue Result;
7794
7795   if (Subtarget->hasSSE3()) {
7796     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7797     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7798   } else {
7799     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7800     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7801                                            S2F, 0x4E, DAG);
7802     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7803                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7804                          Sub);
7805   }
7806
7807   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7808                      DAG.getIntPtrConstant(0));
7809 }
7810
7811 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7812 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7813                                                SelectionDAG &DAG) const {
7814   DebugLoc dl = Op.getDebugLoc();
7815   // FP constant to bias correct the final result.
7816   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7817                                    MVT::f64);
7818
7819   // Load the 32-bit value into an XMM register.
7820   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7821                              Op.getOperand(0));
7822
7823   // Zero out the upper parts of the register.
7824   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7825
7826   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7827                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7828                      DAG.getIntPtrConstant(0));
7829
7830   // Or the load with the bias.
7831   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7832                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7833                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7834                                                    MVT::v2f64, Load)),
7835                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7836                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7837                                                    MVT::v2f64, Bias)));
7838   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7839                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7840                    DAG.getIntPtrConstant(0));
7841
7842   // Subtract the bias.
7843   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7844
7845   // Handle final rounding.
7846   EVT DestVT = Op.getValueType();
7847
7848   if (DestVT.bitsLT(MVT::f64))
7849     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7850                        DAG.getIntPtrConstant(0));
7851   if (DestVT.bitsGT(MVT::f64))
7852     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7853
7854   // Handle final rounding.
7855   return Sub;
7856 }
7857
7858 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7859                                            SelectionDAG &DAG) const {
7860   SDValue N0 = Op.getOperand(0);
7861   DebugLoc dl = Op.getDebugLoc();
7862
7863   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7864   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7865   // the optimization here.
7866   if (DAG.SignBitIsZero(N0))
7867     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7868
7869   EVT SrcVT = N0.getValueType();
7870   EVT DstVT = Op.getValueType();
7871   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7872     return LowerUINT_TO_FP_i64(Op, DAG);
7873   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7874     return LowerUINT_TO_FP_i32(Op, DAG);
7875   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7876     return SDValue();
7877
7878   // Make a 64-bit buffer, and use it to build an FILD.
7879   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7880   if (SrcVT == MVT::i32) {
7881     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7882     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7883                                      getPointerTy(), StackSlot, WordOff);
7884     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7885                                   StackSlot, MachinePointerInfo(),
7886                                   false, false, 0);
7887     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7888                                   OffsetSlot, MachinePointerInfo(),
7889                                   false, false, 0);
7890     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7891     return Fild;
7892   }
7893
7894   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7895   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7896                                StackSlot, MachinePointerInfo(),
7897                                false, false, 0);
7898   // For i64 source, we need to add the appropriate power of 2 if the input
7899   // was negative.  This is the same as the optimization in
7900   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7901   // we must be careful to do the computation in x87 extended precision, not
7902   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7903   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7904   MachineMemOperand *MMO =
7905     DAG.getMachineFunction()
7906     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7907                           MachineMemOperand::MOLoad, 8, 8);
7908
7909   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7910   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7911   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7912                                          MVT::i64, MMO);
7913
7914   APInt FF(32, 0x5F800000ULL);
7915
7916   // Check whether the sign bit is set.
7917   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7918                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7919                                  ISD::SETLT);
7920
7921   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7922   SDValue FudgePtr = DAG.getConstantPool(
7923                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7924                                          getPointerTy());
7925
7926   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7927   SDValue Zero = DAG.getIntPtrConstant(0);
7928   SDValue Four = DAG.getIntPtrConstant(4);
7929   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7930                                Zero, Four);
7931   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7932
7933   // Load the value out, extending it from f32 to f80.
7934   // FIXME: Avoid the extend by constructing the right constant pool?
7935   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7936                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7937                                  MVT::f32, false, false, 4);
7938   // Extend everything to 80 bits to force it to be done on x87.
7939   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7940   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7941 }
7942
7943 std::pair<SDValue,SDValue> X86TargetLowering::
7944 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7945   DebugLoc DL = Op.getDebugLoc();
7946
7947   EVT DstTy = Op.getValueType();
7948
7949   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7950     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7951     DstTy = MVT::i64;
7952   }
7953
7954   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7955          DstTy.getSimpleVT() >= MVT::i16 &&
7956          "Unknown FP_TO_INT to lower!");
7957
7958   // These are really Legal.
7959   if (DstTy == MVT::i32 &&
7960       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7961     return std::make_pair(SDValue(), SDValue());
7962   if (Subtarget->is64Bit() &&
7963       DstTy == MVT::i64 &&
7964       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7965     return std::make_pair(SDValue(), SDValue());
7966
7967   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
7968   // stack slot, or into the FTOL runtime function.
7969   MachineFunction &MF = DAG.getMachineFunction();
7970   unsigned MemSize = DstTy.getSizeInBits()/8;
7971   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7972   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7973
7974   unsigned Opc;
7975   if (!IsSigned && isIntegerTypeFTOL(DstTy))
7976     Opc = X86ISD::WIN_FTOL;
7977   else
7978     switch (DstTy.getSimpleVT().SimpleTy) {
7979     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7980     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7981     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7982     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7983     }
7984
7985   SDValue Chain = DAG.getEntryNode();
7986   SDValue Value = Op.getOperand(0);
7987   EVT TheVT = Op.getOperand(0).getValueType();
7988   // FIXME This causes a redundant load/store if the SSE-class value is already
7989   // in memory, such as if it is on the callstack.
7990   if (isScalarFPTypeInSSEReg(TheVT)) {
7991     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7992     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7993                          MachinePointerInfo::getFixedStack(SSFI),
7994                          false, false, 0);
7995     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7996     SDValue Ops[] = {
7997       Chain, StackSlot, DAG.getValueType(TheVT)
7998     };
7999
8000     MachineMemOperand *MMO =
8001       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8002                               MachineMemOperand::MOLoad, MemSize, MemSize);
8003     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8004                                     DstTy, MMO);
8005     Chain = Value.getValue(1);
8006     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8007     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8008   }
8009
8010   MachineMemOperand *MMO =
8011     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8012                             MachineMemOperand::MOStore, MemSize, MemSize);
8013
8014   if (Opc != X86ISD::WIN_FTOL) {
8015     // Build the FP_TO_INT*_IN_MEM
8016     SDValue Ops[] = { Chain, Value, StackSlot };
8017     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8018                                            Ops, 3, DstTy, MMO);
8019     return std::make_pair(FIST, StackSlot);
8020   } else {
8021     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8022       DAG.getVTList(MVT::Other, MVT::Glue),
8023       Chain, Value);
8024     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8025       MVT::i32, ftol.getValue(1));
8026     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8027       MVT::i32, eax.getValue(2));
8028     SDValue Ops[] = { eax, edx };
8029     SDValue pair = IsReplace
8030       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8031       : DAG.getMergeValues(Ops, 2, DL);
8032     return std::make_pair(pair, SDValue());
8033   }
8034 }
8035
8036 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8037                                            SelectionDAG &DAG) const {
8038   if (Op.getValueType().isVector())
8039     return SDValue();
8040
8041   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8042     /*IsSigned=*/ true, /*IsReplace=*/ false);
8043   SDValue FIST = Vals.first, StackSlot = Vals.second;
8044   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8045   if (FIST.getNode() == 0) return Op;
8046
8047   if (StackSlot.getNode())
8048     // Load the result.
8049     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8050                        FIST, StackSlot, MachinePointerInfo(),
8051                        false, false, false, 0);
8052
8053   // The node is the result.
8054   return FIST;
8055 }
8056
8057 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8058                                            SelectionDAG &DAG) const {
8059   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8060     /*IsSigned=*/ false, /*IsReplace=*/ false);
8061   SDValue FIST = Vals.first, StackSlot = Vals.second;
8062   assert(FIST.getNode() && "Unexpected failure");
8063
8064   if (StackSlot.getNode())
8065     // Load the result.
8066     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8067                        FIST, StackSlot, MachinePointerInfo(),
8068                        false, false, false, 0);
8069
8070   // The node is the result.
8071   return FIST;
8072 }
8073
8074 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8075                                      SelectionDAG &DAG) const {
8076   LLVMContext *Context = DAG.getContext();
8077   DebugLoc dl = Op.getDebugLoc();
8078   EVT VT = Op.getValueType();
8079   EVT EltVT = VT;
8080   if (VT.isVector())
8081     EltVT = VT.getVectorElementType();
8082   Constant *C;
8083   if (EltVT == MVT::f64) {
8084     C = ConstantVector::getSplat(2,
8085                 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8086   } else {
8087     C = ConstantVector::getSplat(4,
8088                ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8089   }
8090   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8091   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8092                              MachinePointerInfo::getConstantPool(),
8093                              false, false, false, 16);
8094   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8095 }
8096
8097 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8098   LLVMContext *Context = DAG.getContext();
8099   DebugLoc dl = Op.getDebugLoc();
8100   EVT VT = Op.getValueType();
8101   EVT EltVT = VT;
8102   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8103   if (VT.isVector()) {
8104     EltVT = VT.getVectorElementType();
8105     NumElts = VT.getVectorNumElements();
8106   }
8107   Constant *C;
8108   if (EltVT == MVT::f64)
8109     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8110   else
8111     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8112   C = ConstantVector::getSplat(NumElts, C);
8113   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8114   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8115                              MachinePointerInfo::getConstantPool(),
8116                              false, false, false, 16);
8117   if (VT.isVector()) {
8118     MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
8119     return DAG.getNode(ISD::BITCAST, dl, VT,
8120                        DAG.getNode(ISD::XOR, dl, XORVT,
8121                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8122                                                Op.getOperand(0)),
8123                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8124   }
8125
8126   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8127 }
8128
8129 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8130   LLVMContext *Context = DAG.getContext();
8131   SDValue Op0 = Op.getOperand(0);
8132   SDValue Op1 = Op.getOperand(1);
8133   DebugLoc dl = Op.getDebugLoc();
8134   EVT VT = Op.getValueType();
8135   EVT SrcVT = Op1.getValueType();
8136
8137   // If second operand is smaller, extend it first.
8138   if (SrcVT.bitsLT(VT)) {
8139     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8140     SrcVT = VT;
8141   }
8142   // And if it is bigger, shrink it first.
8143   if (SrcVT.bitsGT(VT)) {
8144     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8145     SrcVT = VT;
8146   }
8147
8148   // At this point the operands and the result should have the same
8149   // type, and that won't be f80 since that is not custom lowered.
8150
8151   // First get the sign bit of second operand.
8152   SmallVector<Constant*,4> CV;
8153   if (SrcVT == MVT::f64) {
8154     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8155     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8156   } else {
8157     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8158     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8159     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8160     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8161   }
8162   Constant *C = ConstantVector::get(CV);
8163   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8164   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8165                               MachinePointerInfo::getConstantPool(),
8166                               false, false, false, 16);
8167   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8168
8169   // Shift sign bit right or left if the two operands have different types.
8170   if (SrcVT.bitsGT(VT)) {
8171     // Op0 is MVT::f32, Op1 is MVT::f64.
8172     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8173     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8174                           DAG.getConstant(32, MVT::i32));
8175     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8176     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8177                           DAG.getIntPtrConstant(0));
8178   }
8179
8180   // Clear first operand sign bit.
8181   CV.clear();
8182   if (VT == MVT::f64) {
8183     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8184     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8185   } else {
8186     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8187     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8188     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8189     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8190   }
8191   C = ConstantVector::get(CV);
8192   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8193   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8194                               MachinePointerInfo::getConstantPool(),
8195                               false, false, false, 16);
8196   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8197
8198   // Or the value with the sign bit.
8199   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8200 }
8201
8202 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8203   SDValue N0 = Op.getOperand(0);
8204   DebugLoc dl = Op.getDebugLoc();
8205   EVT VT = Op.getValueType();
8206
8207   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8208   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8209                                   DAG.getConstant(1, VT));
8210   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8211 }
8212
8213 /// Emit nodes that will be selected as "test Op0,Op0", or something
8214 /// equivalent.
8215 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8216                                     SelectionDAG &DAG) const {
8217   DebugLoc dl = Op.getDebugLoc();
8218
8219   // CF and OF aren't always set the way we want. Determine which
8220   // of these we need.
8221   bool NeedCF = false;
8222   bool NeedOF = false;
8223   switch (X86CC) {
8224   default: break;
8225   case X86::COND_A: case X86::COND_AE:
8226   case X86::COND_B: case X86::COND_BE:
8227     NeedCF = true;
8228     break;
8229   case X86::COND_G: case X86::COND_GE:
8230   case X86::COND_L: case X86::COND_LE:
8231   case X86::COND_O: case X86::COND_NO:
8232     NeedOF = true;
8233     break;
8234   }
8235
8236   // See if we can use the EFLAGS value from the operand instead of
8237   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8238   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8239   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8240     // Emit a CMP with 0, which is the TEST pattern.
8241     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8242                        DAG.getConstant(0, Op.getValueType()));
8243
8244   unsigned Opcode = 0;
8245   unsigned NumOperands = 0;
8246   switch (Op.getNode()->getOpcode()) {
8247   case ISD::ADD:
8248     // Due to an isel shortcoming, be conservative if this add is likely to be
8249     // selected as part of a load-modify-store instruction. When the root node
8250     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8251     // uses of other nodes in the match, such as the ADD in this case. This
8252     // leads to the ADD being left around and reselected, with the result being
8253     // two adds in the output.  Alas, even if none our users are stores, that
8254     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8255     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8256     // climbing the DAG back to the root, and it doesn't seem to be worth the
8257     // effort.
8258     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8259          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8260       if (UI->getOpcode() != ISD::CopyToReg &&
8261           UI->getOpcode() != ISD::SETCC &&
8262           UI->getOpcode() != ISD::STORE)
8263         goto default_case;
8264
8265     if (ConstantSDNode *C =
8266         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8267       // An add of one will be selected as an INC.
8268       if (C->getAPIntValue() == 1) {
8269         Opcode = X86ISD::INC;
8270         NumOperands = 1;
8271         break;
8272       }
8273
8274       // An add of negative one (subtract of one) will be selected as a DEC.
8275       if (C->getAPIntValue().isAllOnesValue()) {
8276         Opcode = X86ISD::DEC;
8277         NumOperands = 1;
8278         break;
8279       }
8280     }
8281
8282     // Otherwise use a regular EFLAGS-setting add.
8283     Opcode = X86ISD::ADD;
8284     NumOperands = 2;
8285     break;
8286   case ISD::AND: {
8287     // If the primary and result isn't used, don't bother using X86ISD::AND,
8288     // because a TEST instruction will be better.
8289     bool NonFlagUse = false;
8290     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8291            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8292       SDNode *User = *UI;
8293       unsigned UOpNo = UI.getOperandNo();
8294       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8295         // Look pass truncate.
8296         UOpNo = User->use_begin().getOperandNo();
8297         User = *User->use_begin();
8298       }
8299
8300       if (User->getOpcode() != ISD::BRCOND &&
8301           User->getOpcode() != ISD::SETCC &&
8302           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8303         NonFlagUse = true;
8304         break;
8305       }
8306     }
8307
8308     if (!NonFlagUse)
8309       break;
8310   }
8311     // FALL THROUGH
8312   case ISD::SUB:
8313   case ISD::OR:
8314   case ISD::XOR:
8315     // Due to the ISEL shortcoming noted above, be conservative if this op is
8316     // likely to be selected as part of a load-modify-store instruction.
8317     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8318            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8319       if (UI->getOpcode() == ISD::STORE)
8320         goto default_case;
8321
8322     // Otherwise use a regular EFLAGS-setting instruction.
8323     switch (Op.getNode()->getOpcode()) {
8324     default: llvm_unreachable("unexpected operator!");
8325     case ISD::SUB:
8326       Opcode = X86ISD::SUB;
8327       break;
8328     case ISD::OR:  Opcode = X86ISD::OR;  break;
8329     case ISD::XOR: Opcode = X86ISD::XOR; break;
8330     case ISD::AND: Opcode = X86ISD::AND; break;
8331     }
8332
8333     NumOperands = 2;
8334     break;
8335   case X86ISD::ADD:
8336   case X86ISD::SUB:
8337   case X86ISD::INC:
8338   case X86ISD::DEC:
8339   case X86ISD::OR:
8340   case X86ISD::XOR:
8341   case X86ISD::AND:
8342     return SDValue(Op.getNode(), 1);
8343   default:
8344   default_case:
8345     break;
8346   }
8347
8348   if (Opcode == 0)
8349     // Emit a CMP with 0, which is the TEST pattern.
8350     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8351                        DAG.getConstant(0, Op.getValueType()));
8352
8353   if (Opcode == X86ISD::CMP) {
8354     SDValue New = DAG.getNode(Opcode, dl, MVT::i32, Op.getOperand(0),
8355                               Op.getOperand(1));
8356     // We can't replace usage of SUB with CMP.
8357     // The SUB node will be removed later because there is no use of it.
8358     return SDValue(New.getNode(), 0);
8359   }
8360
8361   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8362   SmallVector<SDValue, 4> Ops;
8363   for (unsigned i = 0; i != NumOperands; ++i)
8364     Ops.push_back(Op.getOperand(i));
8365
8366   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8367   DAG.ReplaceAllUsesWith(Op, New);
8368   return SDValue(New.getNode(), 1);
8369 }
8370
8371 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8372 /// equivalent.
8373 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8374                                    SelectionDAG &DAG) const {
8375   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8376     if (C->getAPIntValue() == 0)
8377       return EmitTest(Op0, X86CC, DAG);
8378
8379   DebugLoc dl = Op0.getDebugLoc();
8380   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8381        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8382     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8383     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8384     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8385                               Op0, Op1);
8386     return SDValue(Sub.getNode(), 1);
8387   }
8388   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8389 }
8390
8391 /// Convert a comparison if required by the subtarget.
8392 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8393                                                  SelectionDAG &DAG) const {
8394   // If the subtarget does not support the FUCOMI instruction, floating-point
8395   // comparisons have to be converted.
8396   if (Subtarget->hasCMov() ||
8397       Cmp.getOpcode() != X86ISD::CMP ||
8398       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8399       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8400     return Cmp;
8401
8402   // The instruction selector will select an FUCOM instruction instead of
8403   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8404   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8405   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8406   DebugLoc dl = Cmp.getDebugLoc();
8407   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8408   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8409   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8410                             DAG.getConstant(8, MVT::i8));
8411   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8412   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8413 }
8414
8415 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8416 /// if it's possible.
8417 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8418                                      DebugLoc dl, SelectionDAG &DAG) const {
8419   SDValue Op0 = And.getOperand(0);
8420   SDValue Op1 = And.getOperand(1);
8421   if (Op0.getOpcode() == ISD::TRUNCATE)
8422     Op0 = Op0.getOperand(0);
8423   if (Op1.getOpcode() == ISD::TRUNCATE)
8424     Op1 = Op1.getOperand(0);
8425
8426   SDValue LHS, RHS;
8427   if (Op1.getOpcode() == ISD::SHL)
8428     std::swap(Op0, Op1);
8429   if (Op0.getOpcode() == ISD::SHL) {
8430     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8431       if (And00C->getZExtValue() == 1) {
8432         // If we looked past a truncate, check that it's only truncating away
8433         // known zeros.
8434         unsigned BitWidth = Op0.getValueSizeInBits();
8435         unsigned AndBitWidth = And.getValueSizeInBits();
8436         if (BitWidth > AndBitWidth) {
8437           APInt Zeros, Ones;
8438           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8439           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8440             return SDValue();
8441         }
8442         LHS = Op1;
8443         RHS = Op0.getOperand(1);
8444       }
8445   } else if (Op1.getOpcode() == ISD::Constant) {
8446     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8447     uint64_t AndRHSVal = AndRHS->getZExtValue();
8448     SDValue AndLHS = Op0;
8449
8450     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8451       LHS = AndLHS.getOperand(0);
8452       RHS = AndLHS.getOperand(1);
8453     }
8454
8455     // Use BT if the immediate can't be encoded in a TEST instruction.
8456     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8457       LHS = AndLHS;
8458       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8459     }
8460   }
8461
8462   if (LHS.getNode()) {
8463     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8464     // instruction.  Since the shift amount is in-range-or-undefined, we know
8465     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8466     // the encoding for the i16 version is larger than the i32 version.
8467     // Also promote i16 to i32 for performance / code size reason.
8468     if (LHS.getValueType() == MVT::i8 ||
8469         LHS.getValueType() == MVT::i16)
8470       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8471
8472     // If the operand types disagree, extend the shift amount to match.  Since
8473     // BT ignores high bits (like shifts) we can use anyextend.
8474     if (LHS.getValueType() != RHS.getValueType())
8475       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8476
8477     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8478     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8479     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8480                        DAG.getConstant(Cond, MVT::i8), BT);
8481   }
8482
8483   return SDValue();
8484 }
8485
8486 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8487
8488   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8489
8490   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8491   SDValue Op0 = Op.getOperand(0);
8492   SDValue Op1 = Op.getOperand(1);
8493   DebugLoc dl = Op.getDebugLoc();
8494   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8495
8496   // Optimize to BT if possible.
8497   // Lower (X & (1 << N)) == 0 to BT(X, N).
8498   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8499   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8500   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8501       Op1.getOpcode() == ISD::Constant &&
8502       cast<ConstantSDNode>(Op1)->isNullValue() &&
8503       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8504     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8505     if (NewSetCC.getNode())
8506       return NewSetCC;
8507   }
8508
8509   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8510   // these.
8511   if (Op1.getOpcode() == ISD::Constant &&
8512       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8513        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8514       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8515
8516     // If the input is a setcc, then reuse the input setcc or use a new one with
8517     // the inverted condition.
8518     if (Op0.getOpcode() == X86ISD::SETCC) {
8519       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8520       bool Invert = (CC == ISD::SETNE) ^
8521         cast<ConstantSDNode>(Op1)->isNullValue();
8522       if (!Invert) return Op0;
8523
8524       CCode = X86::GetOppositeBranchCondition(CCode);
8525       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8526                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8527     }
8528   }
8529
8530   bool isFP = Op1.getValueType().isFloatingPoint();
8531   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8532   if (X86CC == X86::COND_INVALID)
8533     return SDValue();
8534
8535   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8536   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8537   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8538                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8539 }
8540
8541 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8542 // ones, and then concatenate the result back.
8543 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8544   EVT VT = Op.getValueType();
8545
8546   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8547          "Unsupported value type for operation");
8548
8549   unsigned NumElems = VT.getVectorNumElements();
8550   DebugLoc dl = Op.getDebugLoc();
8551   SDValue CC = Op.getOperand(2);
8552
8553   // Extract the LHS vectors
8554   SDValue LHS = Op.getOperand(0);
8555   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8556   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8557
8558   // Extract the RHS vectors
8559   SDValue RHS = Op.getOperand(1);
8560   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8561   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8562
8563   // Issue the operation on the smaller types and concatenate the result back
8564   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8565   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8566   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8567                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8568                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8569 }
8570
8571
8572 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8573   SDValue Cond;
8574   SDValue Op0 = Op.getOperand(0);
8575   SDValue Op1 = Op.getOperand(1);
8576   SDValue CC = Op.getOperand(2);
8577   EVT VT = Op.getValueType();
8578   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8579   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8580   DebugLoc dl = Op.getDebugLoc();
8581
8582   if (isFP) {
8583     unsigned SSECC = 8;
8584     EVT EltVT = Op0.getValueType().getVectorElementType();
8585     assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8586
8587     bool Swap = false;
8588
8589     // SSE Condition code mapping:
8590     //  0 - EQ
8591     //  1 - LT
8592     //  2 - LE
8593     //  3 - UNORD
8594     //  4 - NEQ
8595     //  5 - NLT
8596     //  6 - NLE
8597     //  7 - ORD
8598     switch (SetCCOpcode) {
8599     default: break;
8600     case ISD::SETOEQ:
8601     case ISD::SETEQ:  SSECC = 0; break;
8602     case ISD::SETOGT:
8603     case ISD::SETGT: Swap = true; // Fallthrough
8604     case ISD::SETLT:
8605     case ISD::SETOLT: SSECC = 1; break;
8606     case ISD::SETOGE:
8607     case ISD::SETGE: Swap = true; // Fallthrough
8608     case ISD::SETLE:
8609     case ISD::SETOLE: SSECC = 2; break;
8610     case ISD::SETUO:  SSECC = 3; break;
8611     case ISD::SETUNE:
8612     case ISD::SETNE:  SSECC = 4; break;
8613     case ISD::SETULE: Swap = true;
8614     case ISD::SETUGE: SSECC = 5; break;
8615     case ISD::SETULT: Swap = true;
8616     case ISD::SETUGT: SSECC = 6; break;
8617     case ISD::SETO:   SSECC = 7; break;
8618     }
8619     if (Swap)
8620       std::swap(Op0, Op1);
8621
8622     // In the two special cases we can't handle, emit two comparisons.
8623     if (SSECC == 8) {
8624       if (SetCCOpcode == ISD::SETUEQ) {
8625         SDValue UNORD, EQ;
8626         UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8627                             DAG.getConstant(3, MVT::i8));
8628         EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8629                          DAG.getConstant(0, MVT::i8));
8630         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8631       }
8632       if (SetCCOpcode == ISD::SETONE) {
8633         SDValue ORD, NEQ;
8634         ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8635                           DAG.getConstant(7, MVT::i8));
8636         NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8637                           DAG.getConstant(4, MVT::i8));
8638         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8639       }
8640       llvm_unreachable("Illegal FP comparison");
8641     }
8642     // Handle all other FP comparisons here.
8643     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8644                        DAG.getConstant(SSECC, MVT::i8));
8645   }
8646
8647   // Break 256-bit integer vector compare into smaller ones.
8648   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8649     return Lower256IntVSETCC(Op, DAG);
8650
8651   // We are handling one of the integer comparisons here.  Since SSE only has
8652   // GT and EQ comparisons for integer, swapping operands and multiple
8653   // operations may be required for some comparisons.
8654   unsigned Opc = 0;
8655   bool Swap = false, Invert = false, FlipSigns = false;
8656
8657   switch (SetCCOpcode) {
8658   default: break;
8659   case ISD::SETNE:  Invert = true;
8660   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8661   case ISD::SETLT:  Swap = true;
8662   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8663   case ISD::SETGE:  Swap = true;
8664   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8665   case ISD::SETULT: Swap = true;
8666   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8667   case ISD::SETUGE: Swap = true;
8668   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8669   }
8670   if (Swap)
8671     std::swap(Op0, Op1);
8672
8673   // Check that the operation in question is available (most are plain SSE2,
8674   // but PCMPGTQ and PCMPEQQ have different requirements).
8675   if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8676     return SDValue();
8677   if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8678     return SDValue();
8679
8680   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8681   // bits of the inputs before performing those operations.
8682   if (FlipSigns) {
8683     EVT EltVT = VT.getVectorElementType();
8684     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8685                                       EltVT);
8686     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8687     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8688                                     SignBits.size());
8689     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8690     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8691   }
8692
8693   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8694
8695   // If the logical-not of the result is required, perform that now.
8696   if (Invert)
8697     Result = DAG.getNOT(dl, Result, VT);
8698
8699   return Result;
8700 }
8701
8702 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8703 static bool isX86LogicalCmp(SDValue Op) {
8704   unsigned Opc = Op.getNode()->getOpcode();
8705   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8706       Opc == X86ISD::SAHF)
8707     return true;
8708   if (Op.getResNo() == 1 &&
8709       (Opc == X86ISD::ADD ||
8710        Opc == X86ISD::SUB ||
8711        Opc == X86ISD::ADC ||
8712        Opc == X86ISD::SBB ||
8713        Opc == X86ISD::SMUL ||
8714        Opc == X86ISD::UMUL ||
8715        Opc == X86ISD::INC ||
8716        Opc == X86ISD::DEC ||
8717        Opc == X86ISD::OR ||
8718        Opc == X86ISD::XOR ||
8719        Opc == X86ISD::AND))
8720     return true;
8721
8722   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8723     return true;
8724
8725   return false;
8726 }
8727
8728 static bool isZero(SDValue V) {
8729   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8730   return C && C->isNullValue();
8731 }
8732
8733 static bool isAllOnes(SDValue V) {
8734   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8735   return C && C->isAllOnesValue();
8736 }
8737
8738 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8739   if (V.getOpcode() != ISD::TRUNCATE)
8740     return false;
8741
8742   SDValue VOp0 = V.getOperand(0);
8743   unsigned InBits = VOp0.getValueSizeInBits();
8744   unsigned Bits = V.getValueSizeInBits();
8745   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8746 }
8747
8748 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8749   bool addTest = true;
8750   SDValue Cond  = Op.getOperand(0);
8751   SDValue Op1 = Op.getOperand(1);
8752   SDValue Op2 = Op.getOperand(2);
8753   DebugLoc DL = Op.getDebugLoc();
8754   SDValue CC;
8755
8756   if (Cond.getOpcode() == ISD::SETCC) {
8757     SDValue NewCond = LowerSETCC(Cond, DAG);
8758     if (NewCond.getNode())
8759       Cond = NewCond;
8760   }
8761
8762   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8763   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8764   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8765   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8766   if (Cond.getOpcode() == X86ISD::SETCC &&
8767       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8768       isZero(Cond.getOperand(1).getOperand(1))) {
8769     SDValue Cmp = Cond.getOperand(1);
8770
8771     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8772
8773     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8774         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8775       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8776
8777       SDValue CmpOp0 = Cmp.getOperand(0);
8778       // Apply further optimizations for special cases
8779       // (select (x != 0), -1, 0) -> neg & sbb
8780       // (select (x == 0), 0, -1) -> neg & sbb
8781       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8782         if (YC->isNullValue() &&
8783             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8784           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8785           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8786                                     DAG.getConstant(0, CmpOp0.getValueType()),
8787                                     CmpOp0);
8788           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8789                                     DAG.getConstant(X86::COND_B, MVT::i8),
8790                                     SDValue(Neg.getNode(), 1));
8791           return Res;
8792         }
8793
8794       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8795                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8796       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8797
8798       SDValue Res =   // Res = 0 or -1.
8799         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8800                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8801
8802       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8803         Res = DAG.getNOT(DL, Res, Res.getValueType());
8804
8805       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8806       if (N2C == 0 || !N2C->isNullValue())
8807         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8808       return Res;
8809     }
8810   }
8811
8812   // Look past (and (setcc_carry (cmp ...)), 1).
8813   if (Cond.getOpcode() == ISD::AND &&
8814       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8815     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8816     if (C && C->getAPIntValue() == 1)
8817       Cond = Cond.getOperand(0);
8818   }
8819
8820   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8821   // setting operand in place of the X86ISD::SETCC.
8822   unsigned CondOpcode = Cond.getOpcode();
8823   if (CondOpcode == X86ISD::SETCC ||
8824       CondOpcode == X86ISD::SETCC_CARRY) {
8825     CC = Cond.getOperand(0);
8826
8827     SDValue Cmp = Cond.getOperand(1);
8828     unsigned Opc = Cmp.getOpcode();
8829     EVT VT = Op.getValueType();
8830
8831     bool IllegalFPCMov = false;
8832     if (VT.isFloatingPoint() && !VT.isVector() &&
8833         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8834       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8835
8836     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8837         Opc == X86ISD::BT) { // FIXME
8838       Cond = Cmp;
8839       addTest = false;
8840     }
8841   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8842              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8843              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8844               Cond.getOperand(0).getValueType() != MVT::i8)) {
8845     SDValue LHS = Cond.getOperand(0);
8846     SDValue RHS = Cond.getOperand(1);
8847     unsigned X86Opcode;
8848     unsigned X86Cond;
8849     SDVTList VTs;
8850     switch (CondOpcode) {
8851     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8852     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8853     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8854     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8855     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8856     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8857     default: llvm_unreachable("unexpected overflowing operator");
8858     }
8859     if (CondOpcode == ISD::UMULO)
8860       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8861                           MVT::i32);
8862     else
8863       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8864
8865     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8866
8867     if (CondOpcode == ISD::UMULO)
8868       Cond = X86Op.getValue(2);
8869     else
8870       Cond = X86Op.getValue(1);
8871
8872     CC = DAG.getConstant(X86Cond, MVT::i8);
8873     addTest = false;
8874   }
8875
8876   if (addTest) {
8877     // Look pass the truncate if the high bits are known zero.
8878     if (isTruncWithZeroHighBitsInput(Cond, DAG))
8879         Cond = Cond.getOperand(0);
8880
8881     // We know the result of AND is compared against zero. Try to match
8882     // it to BT.
8883     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8884       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8885       if (NewSetCC.getNode()) {
8886         CC = NewSetCC.getOperand(0);
8887         Cond = NewSetCC.getOperand(1);
8888         addTest = false;
8889       }
8890     }
8891   }
8892
8893   if (addTest) {
8894     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8895     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8896   }
8897
8898   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8899   // a <  b ?  0 : -1 -> RES = setcc_carry
8900   // a >= b ? -1 :  0 -> RES = setcc_carry
8901   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8902   if (Cond.getOpcode() == X86ISD::SUB) {
8903     Cond = ConvertCmpIfNecessary(Cond, DAG);
8904     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8905
8906     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8907         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8908       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8909                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8910       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8911         return DAG.getNOT(DL, Res, Res.getValueType());
8912       return Res;
8913     }
8914   }
8915
8916   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8917   // condition is true.
8918   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8919   SDValue Ops[] = { Op2, Op1, CC, Cond };
8920   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8921 }
8922
8923 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8924 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8925 // from the AND / OR.
8926 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8927   Opc = Op.getOpcode();
8928   if (Opc != ISD::OR && Opc != ISD::AND)
8929     return false;
8930   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8931           Op.getOperand(0).hasOneUse() &&
8932           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8933           Op.getOperand(1).hasOneUse());
8934 }
8935
8936 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8937 // 1 and that the SETCC node has a single use.
8938 static bool isXor1OfSetCC(SDValue Op) {
8939   if (Op.getOpcode() != ISD::XOR)
8940     return false;
8941   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8942   if (N1C && N1C->getAPIntValue() == 1) {
8943     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8944       Op.getOperand(0).hasOneUse();
8945   }
8946   return false;
8947 }
8948
8949 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8950   bool addTest = true;
8951   SDValue Chain = Op.getOperand(0);
8952   SDValue Cond  = Op.getOperand(1);
8953   SDValue Dest  = Op.getOperand(2);
8954   DebugLoc dl = Op.getDebugLoc();
8955   SDValue CC;
8956   bool Inverted = false;
8957
8958   if (Cond.getOpcode() == ISD::SETCC) {
8959     // Check for setcc([su]{add,sub,mul}o == 0).
8960     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8961         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8962         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8963         Cond.getOperand(0).getResNo() == 1 &&
8964         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8965          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8966          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8967          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8968          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8969          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8970       Inverted = true;
8971       Cond = Cond.getOperand(0);
8972     } else {
8973       SDValue NewCond = LowerSETCC(Cond, DAG);
8974       if (NewCond.getNode())
8975         Cond = NewCond;
8976     }
8977   }
8978 #if 0
8979   // FIXME: LowerXALUO doesn't handle these!!
8980   else if (Cond.getOpcode() == X86ISD::ADD  ||
8981            Cond.getOpcode() == X86ISD::SUB  ||
8982            Cond.getOpcode() == X86ISD::SMUL ||
8983            Cond.getOpcode() == X86ISD::UMUL)
8984     Cond = LowerXALUO(Cond, DAG);
8985 #endif
8986
8987   // Look pass (and (setcc_carry (cmp ...)), 1).
8988   if (Cond.getOpcode() == ISD::AND &&
8989       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8990     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8991     if (C && C->getAPIntValue() == 1)
8992       Cond = Cond.getOperand(0);
8993   }
8994
8995   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8996   // setting operand in place of the X86ISD::SETCC.
8997   unsigned CondOpcode = Cond.getOpcode();
8998   if (CondOpcode == X86ISD::SETCC ||
8999       CondOpcode == X86ISD::SETCC_CARRY) {
9000     CC = Cond.getOperand(0);
9001
9002     SDValue Cmp = Cond.getOperand(1);
9003     unsigned Opc = Cmp.getOpcode();
9004     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9005     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9006       Cond = Cmp;
9007       addTest = false;
9008     } else {
9009       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9010       default: break;
9011       case X86::COND_O:
9012       case X86::COND_B:
9013         // These can only come from an arithmetic instruction with overflow,
9014         // e.g. SADDO, UADDO.
9015         Cond = Cond.getNode()->getOperand(1);
9016         addTest = false;
9017         break;
9018       }
9019     }
9020   }
9021   CondOpcode = Cond.getOpcode();
9022   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9023       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9024       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9025        Cond.getOperand(0).getValueType() != MVT::i8)) {
9026     SDValue LHS = Cond.getOperand(0);
9027     SDValue RHS = Cond.getOperand(1);
9028     unsigned X86Opcode;
9029     unsigned X86Cond;
9030     SDVTList VTs;
9031     switch (CondOpcode) {
9032     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9033     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9034     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9035     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9036     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9037     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9038     default: llvm_unreachable("unexpected overflowing operator");
9039     }
9040     if (Inverted)
9041       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9042     if (CondOpcode == ISD::UMULO)
9043       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9044                           MVT::i32);
9045     else
9046       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9047
9048     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9049
9050     if (CondOpcode == ISD::UMULO)
9051       Cond = X86Op.getValue(2);
9052     else
9053       Cond = X86Op.getValue(1);
9054
9055     CC = DAG.getConstant(X86Cond, MVT::i8);
9056     addTest = false;
9057   } else {
9058     unsigned CondOpc;
9059     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9060       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9061       if (CondOpc == ISD::OR) {
9062         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9063         // two branches instead of an explicit OR instruction with a
9064         // separate test.
9065         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9066             isX86LogicalCmp(Cmp)) {
9067           CC = Cond.getOperand(0).getOperand(0);
9068           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9069                               Chain, Dest, CC, Cmp);
9070           CC = Cond.getOperand(1).getOperand(0);
9071           Cond = Cmp;
9072           addTest = false;
9073         }
9074       } else { // ISD::AND
9075         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9076         // two branches instead of an explicit AND instruction with a
9077         // separate test. However, we only do this if this block doesn't
9078         // have a fall-through edge, because this requires an explicit
9079         // jmp when the condition is false.
9080         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9081             isX86LogicalCmp(Cmp) &&
9082             Op.getNode()->hasOneUse()) {
9083           X86::CondCode CCode =
9084             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9085           CCode = X86::GetOppositeBranchCondition(CCode);
9086           CC = DAG.getConstant(CCode, MVT::i8);
9087           SDNode *User = *Op.getNode()->use_begin();
9088           // Look for an unconditional branch following this conditional branch.
9089           // We need this because we need to reverse the successors in order
9090           // to implement FCMP_OEQ.
9091           if (User->getOpcode() == ISD::BR) {
9092             SDValue FalseBB = User->getOperand(1);
9093             SDNode *NewBR =
9094               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9095             assert(NewBR == User);
9096             (void)NewBR;
9097             Dest = FalseBB;
9098
9099             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9100                                 Chain, Dest, CC, Cmp);
9101             X86::CondCode CCode =
9102               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9103             CCode = X86::GetOppositeBranchCondition(CCode);
9104             CC = DAG.getConstant(CCode, MVT::i8);
9105             Cond = Cmp;
9106             addTest = false;
9107           }
9108         }
9109       }
9110     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9111       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9112       // It should be transformed during dag combiner except when the condition
9113       // is set by a arithmetics with overflow node.
9114       X86::CondCode CCode =
9115         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9116       CCode = X86::GetOppositeBranchCondition(CCode);
9117       CC = DAG.getConstant(CCode, MVT::i8);
9118       Cond = Cond.getOperand(0).getOperand(1);
9119       addTest = false;
9120     } else if (Cond.getOpcode() == ISD::SETCC &&
9121                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9122       // For FCMP_OEQ, we can emit
9123       // two branches instead of an explicit AND instruction with a
9124       // separate test. However, we only do this if this block doesn't
9125       // have a fall-through edge, because this requires an explicit
9126       // jmp when the condition is false.
9127       if (Op.getNode()->hasOneUse()) {
9128         SDNode *User = *Op.getNode()->use_begin();
9129         // Look for an unconditional branch following this conditional branch.
9130         // We need this because we need to reverse the successors in order
9131         // to implement FCMP_OEQ.
9132         if (User->getOpcode() == ISD::BR) {
9133           SDValue FalseBB = User->getOperand(1);
9134           SDNode *NewBR =
9135             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9136           assert(NewBR == User);
9137           (void)NewBR;
9138           Dest = FalseBB;
9139
9140           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9141                                     Cond.getOperand(0), Cond.getOperand(1));
9142           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9143           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9144           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9145                               Chain, Dest, CC, Cmp);
9146           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9147           Cond = Cmp;
9148           addTest = false;
9149         }
9150       }
9151     } else if (Cond.getOpcode() == ISD::SETCC &&
9152                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9153       // For FCMP_UNE, we can emit
9154       // two branches instead of an explicit AND instruction with a
9155       // separate test. However, we only do this if this block doesn't
9156       // have a fall-through edge, because this requires an explicit
9157       // jmp when the condition is false.
9158       if (Op.getNode()->hasOneUse()) {
9159         SDNode *User = *Op.getNode()->use_begin();
9160         // Look for an unconditional branch following this conditional branch.
9161         // We need this because we need to reverse the successors in order
9162         // to implement FCMP_UNE.
9163         if (User->getOpcode() == ISD::BR) {
9164           SDValue FalseBB = User->getOperand(1);
9165           SDNode *NewBR =
9166             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9167           assert(NewBR == User);
9168           (void)NewBR;
9169
9170           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9171                                     Cond.getOperand(0), Cond.getOperand(1));
9172           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9173           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9174           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9175                               Chain, Dest, CC, Cmp);
9176           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9177           Cond = Cmp;
9178           addTest = false;
9179           Dest = FalseBB;
9180         }
9181       }
9182     }
9183   }
9184
9185   if (addTest) {
9186     // Look pass the truncate if the high bits are known zero.
9187     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9188         Cond = Cond.getOperand(0);
9189
9190     // We know the result of AND is compared against zero. Try to match
9191     // it to BT.
9192     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9193       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9194       if (NewSetCC.getNode()) {
9195         CC = NewSetCC.getOperand(0);
9196         Cond = NewSetCC.getOperand(1);
9197         addTest = false;
9198       }
9199     }
9200   }
9201
9202   if (addTest) {
9203     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9204     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9205   }
9206   Cond = ConvertCmpIfNecessary(Cond, DAG);
9207   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9208                      Chain, Dest, CC, Cond);
9209 }
9210
9211
9212 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9213 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9214 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9215 // that the guard pages used by the OS virtual memory manager are allocated in
9216 // correct sequence.
9217 SDValue
9218 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9219                                            SelectionDAG &DAG) const {
9220   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9221           getTargetMachine().Options.EnableSegmentedStacks) &&
9222          "This should be used only on Windows targets or when segmented stacks "
9223          "are being used");
9224   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9225   DebugLoc dl = Op.getDebugLoc();
9226
9227   // Get the inputs.
9228   SDValue Chain = Op.getOperand(0);
9229   SDValue Size  = Op.getOperand(1);
9230   // FIXME: Ensure alignment here
9231
9232   bool Is64Bit = Subtarget->is64Bit();
9233   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9234
9235   if (getTargetMachine().Options.EnableSegmentedStacks) {
9236     MachineFunction &MF = DAG.getMachineFunction();
9237     MachineRegisterInfo &MRI = MF.getRegInfo();
9238
9239     if (Is64Bit) {
9240       // The 64 bit implementation of segmented stacks needs to clobber both r10
9241       // r11. This makes it impossible to use it along with nested parameters.
9242       const Function *F = MF.getFunction();
9243
9244       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9245            I != E; ++I)
9246         if (I->hasNestAttr())
9247           report_fatal_error("Cannot use segmented stacks with functions that "
9248                              "have nested arguments.");
9249     }
9250
9251     const TargetRegisterClass *AddrRegClass =
9252       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9253     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9254     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9255     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9256                                 DAG.getRegister(Vreg, SPTy));
9257     SDValue Ops1[2] = { Value, Chain };
9258     return DAG.getMergeValues(Ops1, 2, dl);
9259   } else {
9260     SDValue Flag;
9261     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9262
9263     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9264     Flag = Chain.getValue(1);
9265     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9266
9267     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9268     Flag = Chain.getValue(1);
9269
9270     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9271
9272     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9273     return DAG.getMergeValues(Ops1, 2, dl);
9274   }
9275 }
9276
9277 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9278   MachineFunction &MF = DAG.getMachineFunction();
9279   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9280
9281   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9282   DebugLoc DL = Op.getDebugLoc();
9283
9284   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9285     // vastart just stores the address of the VarArgsFrameIndex slot into the
9286     // memory location argument.
9287     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9288                                    getPointerTy());
9289     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9290                         MachinePointerInfo(SV), false, false, 0);
9291   }
9292
9293   // __va_list_tag:
9294   //   gp_offset         (0 - 6 * 8)
9295   //   fp_offset         (48 - 48 + 8 * 16)
9296   //   overflow_arg_area (point to parameters coming in memory).
9297   //   reg_save_area
9298   SmallVector<SDValue, 8> MemOps;
9299   SDValue FIN = Op.getOperand(1);
9300   // Store gp_offset
9301   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9302                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9303                                                MVT::i32),
9304                                FIN, MachinePointerInfo(SV), false, false, 0);
9305   MemOps.push_back(Store);
9306
9307   // Store fp_offset
9308   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9309                     FIN, DAG.getIntPtrConstant(4));
9310   Store = DAG.getStore(Op.getOperand(0), DL,
9311                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9312                                        MVT::i32),
9313                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9314   MemOps.push_back(Store);
9315
9316   // Store ptr to overflow_arg_area
9317   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9318                     FIN, DAG.getIntPtrConstant(4));
9319   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9320                                     getPointerTy());
9321   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9322                        MachinePointerInfo(SV, 8),
9323                        false, false, 0);
9324   MemOps.push_back(Store);
9325
9326   // Store ptr to reg_save_area.
9327   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9328                     FIN, DAG.getIntPtrConstant(8));
9329   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9330                                     getPointerTy());
9331   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9332                        MachinePointerInfo(SV, 16), false, false, 0);
9333   MemOps.push_back(Store);
9334   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9335                      &MemOps[0], MemOps.size());
9336 }
9337
9338 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9339   assert(Subtarget->is64Bit() &&
9340          "LowerVAARG only handles 64-bit va_arg!");
9341   assert((Subtarget->isTargetLinux() ||
9342           Subtarget->isTargetDarwin()) &&
9343           "Unhandled target in LowerVAARG");
9344   assert(Op.getNode()->getNumOperands() == 4);
9345   SDValue Chain = Op.getOperand(0);
9346   SDValue SrcPtr = Op.getOperand(1);
9347   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9348   unsigned Align = Op.getConstantOperandVal(3);
9349   DebugLoc dl = Op.getDebugLoc();
9350
9351   EVT ArgVT = Op.getNode()->getValueType(0);
9352   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9353   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9354   uint8_t ArgMode;
9355
9356   // Decide which area this value should be read from.
9357   // TODO: Implement the AMD64 ABI in its entirety. This simple
9358   // selection mechanism works only for the basic types.
9359   if (ArgVT == MVT::f80) {
9360     llvm_unreachable("va_arg for f80 not yet implemented");
9361   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9362     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9363   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9364     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9365   } else {
9366     llvm_unreachable("Unhandled argument type in LowerVAARG");
9367   }
9368
9369   if (ArgMode == 2) {
9370     // Sanity Check: Make sure using fp_offset makes sense.
9371     assert(!getTargetMachine().Options.UseSoftFloat &&
9372            !(DAG.getMachineFunction()
9373                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9374            Subtarget->hasSSE1());
9375   }
9376
9377   // Insert VAARG_64 node into the DAG
9378   // VAARG_64 returns two values: Variable Argument Address, Chain
9379   SmallVector<SDValue, 11> InstOps;
9380   InstOps.push_back(Chain);
9381   InstOps.push_back(SrcPtr);
9382   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9383   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9384   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9385   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9386   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9387                                           VTs, &InstOps[0], InstOps.size(),
9388                                           MVT::i64,
9389                                           MachinePointerInfo(SV),
9390                                           /*Align=*/0,
9391                                           /*Volatile=*/false,
9392                                           /*ReadMem=*/true,
9393                                           /*WriteMem=*/true);
9394   Chain = VAARG.getValue(1);
9395
9396   // Load the next argument and return it
9397   return DAG.getLoad(ArgVT, dl,
9398                      Chain,
9399                      VAARG,
9400                      MachinePointerInfo(),
9401                      false, false, false, 0);
9402 }
9403
9404 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9405   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9406   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9407   SDValue Chain = Op.getOperand(0);
9408   SDValue DstPtr = Op.getOperand(1);
9409   SDValue SrcPtr = Op.getOperand(2);
9410   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9411   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9412   DebugLoc DL = Op.getDebugLoc();
9413
9414   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9415                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9416                        false,
9417                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9418 }
9419
9420 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9421 // may or may not be a constant. Takes immediate version of shift as input.
9422 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9423                                    SDValue SrcOp, SDValue ShAmt,
9424                                    SelectionDAG &DAG) {
9425   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9426
9427   if (isa<ConstantSDNode>(ShAmt)) {
9428     // Constant may be a TargetConstant. Use a regular constant.
9429     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9430     switch (Opc) {
9431       default: llvm_unreachable("Unknown target vector shift node");
9432       case X86ISD::VSHLI:
9433       case X86ISD::VSRLI:
9434       case X86ISD::VSRAI:
9435         return DAG.getNode(Opc, dl, VT, SrcOp,
9436                            DAG.getConstant(ShiftAmt, MVT::i32));
9437     }
9438   }
9439
9440   // Change opcode to non-immediate version
9441   switch (Opc) {
9442     default: llvm_unreachable("Unknown target vector shift node");
9443     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9444     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9445     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9446   }
9447
9448   // Need to build a vector containing shift amount
9449   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9450   SDValue ShOps[4];
9451   ShOps[0] = ShAmt;
9452   ShOps[1] = DAG.getConstant(0, MVT::i32);
9453   ShOps[2] = DAG.getUNDEF(MVT::i32);
9454   ShOps[3] = DAG.getUNDEF(MVT::i32);
9455   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9456
9457   // The return type has to be a 128-bit type with the same element
9458   // type as the input type.
9459   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9460   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9461
9462   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9463   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9464 }
9465
9466 SDValue
9467 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9468   DebugLoc dl = Op.getDebugLoc();
9469   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9470   switch (IntNo) {
9471   default: return SDValue();    // Don't custom lower most intrinsics.
9472   // Comparison intrinsics.
9473   case Intrinsic::x86_sse_comieq_ss:
9474   case Intrinsic::x86_sse_comilt_ss:
9475   case Intrinsic::x86_sse_comile_ss:
9476   case Intrinsic::x86_sse_comigt_ss:
9477   case Intrinsic::x86_sse_comige_ss:
9478   case Intrinsic::x86_sse_comineq_ss:
9479   case Intrinsic::x86_sse_ucomieq_ss:
9480   case Intrinsic::x86_sse_ucomilt_ss:
9481   case Intrinsic::x86_sse_ucomile_ss:
9482   case Intrinsic::x86_sse_ucomigt_ss:
9483   case Intrinsic::x86_sse_ucomige_ss:
9484   case Intrinsic::x86_sse_ucomineq_ss:
9485   case Intrinsic::x86_sse2_comieq_sd:
9486   case Intrinsic::x86_sse2_comilt_sd:
9487   case Intrinsic::x86_sse2_comile_sd:
9488   case Intrinsic::x86_sse2_comigt_sd:
9489   case Intrinsic::x86_sse2_comige_sd:
9490   case Intrinsic::x86_sse2_comineq_sd:
9491   case Intrinsic::x86_sse2_ucomieq_sd:
9492   case Intrinsic::x86_sse2_ucomilt_sd:
9493   case Intrinsic::x86_sse2_ucomile_sd:
9494   case Intrinsic::x86_sse2_ucomigt_sd:
9495   case Intrinsic::x86_sse2_ucomige_sd:
9496   case Intrinsic::x86_sse2_ucomineq_sd: {
9497     unsigned Opc = 0;
9498     ISD::CondCode CC = ISD::SETCC_INVALID;
9499     switch (IntNo) {
9500     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9501     case Intrinsic::x86_sse_comieq_ss:
9502     case Intrinsic::x86_sse2_comieq_sd:
9503       Opc = X86ISD::COMI;
9504       CC = ISD::SETEQ;
9505       break;
9506     case Intrinsic::x86_sse_comilt_ss:
9507     case Intrinsic::x86_sse2_comilt_sd:
9508       Opc = X86ISD::COMI;
9509       CC = ISD::SETLT;
9510       break;
9511     case Intrinsic::x86_sse_comile_ss:
9512     case Intrinsic::x86_sse2_comile_sd:
9513       Opc = X86ISD::COMI;
9514       CC = ISD::SETLE;
9515       break;
9516     case Intrinsic::x86_sse_comigt_ss:
9517     case Intrinsic::x86_sse2_comigt_sd:
9518       Opc = X86ISD::COMI;
9519       CC = ISD::SETGT;
9520       break;
9521     case Intrinsic::x86_sse_comige_ss:
9522     case Intrinsic::x86_sse2_comige_sd:
9523       Opc = X86ISD::COMI;
9524       CC = ISD::SETGE;
9525       break;
9526     case Intrinsic::x86_sse_comineq_ss:
9527     case Intrinsic::x86_sse2_comineq_sd:
9528       Opc = X86ISD::COMI;
9529       CC = ISD::SETNE;
9530       break;
9531     case Intrinsic::x86_sse_ucomieq_ss:
9532     case Intrinsic::x86_sse2_ucomieq_sd:
9533       Opc = X86ISD::UCOMI;
9534       CC = ISD::SETEQ;
9535       break;
9536     case Intrinsic::x86_sse_ucomilt_ss:
9537     case Intrinsic::x86_sse2_ucomilt_sd:
9538       Opc = X86ISD::UCOMI;
9539       CC = ISD::SETLT;
9540       break;
9541     case Intrinsic::x86_sse_ucomile_ss:
9542     case Intrinsic::x86_sse2_ucomile_sd:
9543       Opc = X86ISD::UCOMI;
9544       CC = ISD::SETLE;
9545       break;
9546     case Intrinsic::x86_sse_ucomigt_ss:
9547     case Intrinsic::x86_sse2_ucomigt_sd:
9548       Opc = X86ISD::UCOMI;
9549       CC = ISD::SETGT;
9550       break;
9551     case Intrinsic::x86_sse_ucomige_ss:
9552     case Intrinsic::x86_sse2_ucomige_sd:
9553       Opc = X86ISD::UCOMI;
9554       CC = ISD::SETGE;
9555       break;
9556     case Intrinsic::x86_sse_ucomineq_ss:
9557     case Intrinsic::x86_sse2_ucomineq_sd:
9558       Opc = X86ISD::UCOMI;
9559       CC = ISD::SETNE;
9560       break;
9561     }
9562
9563     SDValue LHS = Op.getOperand(1);
9564     SDValue RHS = Op.getOperand(2);
9565     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9566     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9567     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9568     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9569                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9570     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9571   }
9572   // Arithmetic intrinsics.
9573   case Intrinsic::x86_sse2_pmulu_dq:
9574   case Intrinsic::x86_avx2_pmulu_dq:
9575     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9576                        Op.getOperand(1), Op.getOperand(2));
9577   case Intrinsic::x86_sse3_hadd_ps:
9578   case Intrinsic::x86_sse3_hadd_pd:
9579   case Intrinsic::x86_avx_hadd_ps_256:
9580   case Intrinsic::x86_avx_hadd_pd_256:
9581     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9582                        Op.getOperand(1), Op.getOperand(2));
9583   case Intrinsic::x86_sse3_hsub_ps:
9584   case Intrinsic::x86_sse3_hsub_pd:
9585   case Intrinsic::x86_avx_hsub_ps_256:
9586   case Intrinsic::x86_avx_hsub_pd_256:
9587     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9588                        Op.getOperand(1), Op.getOperand(2));
9589   case Intrinsic::x86_ssse3_phadd_w_128:
9590   case Intrinsic::x86_ssse3_phadd_d_128:
9591   case Intrinsic::x86_avx2_phadd_w:
9592   case Intrinsic::x86_avx2_phadd_d:
9593     return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9594                        Op.getOperand(1), Op.getOperand(2));
9595   case Intrinsic::x86_ssse3_phsub_w_128:
9596   case Intrinsic::x86_ssse3_phsub_d_128:
9597   case Intrinsic::x86_avx2_phsub_w:
9598   case Intrinsic::x86_avx2_phsub_d:
9599     return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9600                        Op.getOperand(1), Op.getOperand(2));
9601   case Intrinsic::x86_avx2_psllv_d:
9602   case Intrinsic::x86_avx2_psllv_q:
9603   case Intrinsic::x86_avx2_psllv_d_256:
9604   case Intrinsic::x86_avx2_psllv_q_256:
9605     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9606                       Op.getOperand(1), Op.getOperand(2));
9607   case Intrinsic::x86_avx2_psrlv_d:
9608   case Intrinsic::x86_avx2_psrlv_q:
9609   case Intrinsic::x86_avx2_psrlv_d_256:
9610   case Intrinsic::x86_avx2_psrlv_q_256:
9611     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9612                       Op.getOperand(1), Op.getOperand(2));
9613   case Intrinsic::x86_avx2_psrav_d:
9614   case Intrinsic::x86_avx2_psrav_d_256:
9615     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9616                       Op.getOperand(1), Op.getOperand(2));
9617   case Intrinsic::x86_ssse3_pshuf_b_128:
9618   case Intrinsic::x86_avx2_pshuf_b:
9619     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9620                        Op.getOperand(1), Op.getOperand(2));
9621   case Intrinsic::x86_ssse3_psign_b_128:
9622   case Intrinsic::x86_ssse3_psign_w_128:
9623   case Intrinsic::x86_ssse3_psign_d_128:
9624   case Intrinsic::x86_avx2_psign_b:
9625   case Intrinsic::x86_avx2_psign_w:
9626   case Intrinsic::x86_avx2_psign_d:
9627     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9628                        Op.getOperand(1), Op.getOperand(2));
9629   case Intrinsic::x86_sse41_insertps:
9630     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9631                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9632   case Intrinsic::x86_avx_vperm2f128_ps_256:
9633   case Intrinsic::x86_avx_vperm2f128_pd_256:
9634   case Intrinsic::x86_avx_vperm2f128_si_256:
9635   case Intrinsic::x86_avx2_vperm2i128:
9636     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9637                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9638   case Intrinsic::x86_avx2_permd:
9639   case Intrinsic::x86_avx2_permps:
9640     // Operands intentionally swapped. Mask is last operand to intrinsic,
9641     // but second operand for node/intruction.
9642     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9643                        Op.getOperand(2), Op.getOperand(1));
9644
9645   // ptest and testp intrinsics. The intrinsic these come from are designed to
9646   // return an integer value, not just an instruction so lower it to the ptest
9647   // or testp pattern and a setcc for the result.
9648   case Intrinsic::x86_sse41_ptestz:
9649   case Intrinsic::x86_sse41_ptestc:
9650   case Intrinsic::x86_sse41_ptestnzc:
9651   case Intrinsic::x86_avx_ptestz_256:
9652   case Intrinsic::x86_avx_ptestc_256:
9653   case Intrinsic::x86_avx_ptestnzc_256:
9654   case Intrinsic::x86_avx_vtestz_ps:
9655   case Intrinsic::x86_avx_vtestc_ps:
9656   case Intrinsic::x86_avx_vtestnzc_ps:
9657   case Intrinsic::x86_avx_vtestz_pd:
9658   case Intrinsic::x86_avx_vtestc_pd:
9659   case Intrinsic::x86_avx_vtestnzc_pd:
9660   case Intrinsic::x86_avx_vtestz_ps_256:
9661   case Intrinsic::x86_avx_vtestc_ps_256:
9662   case Intrinsic::x86_avx_vtestnzc_ps_256:
9663   case Intrinsic::x86_avx_vtestz_pd_256:
9664   case Intrinsic::x86_avx_vtestc_pd_256:
9665   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9666     bool IsTestPacked = false;
9667     unsigned X86CC = 0;
9668     switch (IntNo) {
9669     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9670     case Intrinsic::x86_avx_vtestz_ps:
9671     case Intrinsic::x86_avx_vtestz_pd:
9672     case Intrinsic::x86_avx_vtestz_ps_256:
9673     case Intrinsic::x86_avx_vtestz_pd_256:
9674       IsTestPacked = true; // Fallthrough
9675     case Intrinsic::x86_sse41_ptestz:
9676     case Intrinsic::x86_avx_ptestz_256:
9677       // ZF = 1
9678       X86CC = X86::COND_E;
9679       break;
9680     case Intrinsic::x86_avx_vtestc_ps:
9681     case Intrinsic::x86_avx_vtestc_pd:
9682     case Intrinsic::x86_avx_vtestc_ps_256:
9683     case Intrinsic::x86_avx_vtestc_pd_256:
9684       IsTestPacked = true; // Fallthrough
9685     case Intrinsic::x86_sse41_ptestc:
9686     case Intrinsic::x86_avx_ptestc_256:
9687       // CF = 1
9688       X86CC = X86::COND_B;
9689       break;
9690     case Intrinsic::x86_avx_vtestnzc_ps:
9691     case Intrinsic::x86_avx_vtestnzc_pd:
9692     case Intrinsic::x86_avx_vtestnzc_ps_256:
9693     case Intrinsic::x86_avx_vtestnzc_pd_256:
9694       IsTestPacked = true; // Fallthrough
9695     case Intrinsic::x86_sse41_ptestnzc:
9696     case Intrinsic::x86_avx_ptestnzc_256:
9697       // ZF and CF = 0
9698       X86CC = X86::COND_A;
9699       break;
9700     }
9701
9702     SDValue LHS = Op.getOperand(1);
9703     SDValue RHS = Op.getOperand(2);
9704     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9705     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9706     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9707     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9708     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9709   }
9710
9711   // SSE/AVX shift intrinsics
9712   case Intrinsic::x86_sse2_psll_w:
9713   case Intrinsic::x86_sse2_psll_d:
9714   case Intrinsic::x86_sse2_psll_q:
9715   case Intrinsic::x86_avx2_psll_w:
9716   case Intrinsic::x86_avx2_psll_d:
9717   case Intrinsic::x86_avx2_psll_q:
9718     return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9719                        Op.getOperand(1), Op.getOperand(2));
9720   case Intrinsic::x86_sse2_psrl_w:
9721   case Intrinsic::x86_sse2_psrl_d:
9722   case Intrinsic::x86_sse2_psrl_q:
9723   case Intrinsic::x86_avx2_psrl_w:
9724   case Intrinsic::x86_avx2_psrl_d:
9725   case Intrinsic::x86_avx2_psrl_q:
9726     return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9727                        Op.getOperand(1), Op.getOperand(2));
9728   case Intrinsic::x86_sse2_psra_w:
9729   case Intrinsic::x86_sse2_psra_d:
9730   case Intrinsic::x86_avx2_psra_w:
9731   case Intrinsic::x86_avx2_psra_d:
9732     return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9733                        Op.getOperand(1), Op.getOperand(2));
9734   case Intrinsic::x86_sse2_pslli_w:
9735   case Intrinsic::x86_sse2_pslli_d:
9736   case Intrinsic::x86_sse2_pslli_q:
9737   case Intrinsic::x86_avx2_pslli_w:
9738   case Intrinsic::x86_avx2_pslli_d:
9739   case Intrinsic::x86_avx2_pslli_q:
9740     return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9741                                Op.getOperand(1), Op.getOperand(2), DAG);
9742   case Intrinsic::x86_sse2_psrli_w:
9743   case Intrinsic::x86_sse2_psrli_d:
9744   case Intrinsic::x86_sse2_psrli_q:
9745   case Intrinsic::x86_avx2_psrli_w:
9746   case Intrinsic::x86_avx2_psrli_d:
9747   case Intrinsic::x86_avx2_psrli_q:
9748     return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9749                                Op.getOperand(1), Op.getOperand(2), DAG);
9750   case Intrinsic::x86_sse2_psrai_w:
9751   case Intrinsic::x86_sse2_psrai_d:
9752   case Intrinsic::x86_avx2_psrai_w:
9753   case Intrinsic::x86_avx2_psrai_d:
9754     return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9755                                Op.getOperand(1), Op.getOperand(2), DAG);
9756   // Fix vector shift instructions where the last operand is a non-immediate
9757   // i32 value.
9758   case Intrinsic::x86_mmx_pslli_w:
9759   case Intrinsic::x86_mmx_pslli_d:
9760   case Intrinsic::x86_mmx_pslli_q:
9761   case Intrinsic::x86_mmx_psrli_w:
9762   case Intrinsic::x86_mmx_psrli_d:
9763   case Intrinsic::x86_mmx_psrli_q:
9764   case Intrinsic::x86_mmx_psrai_w:
9765   case Intrinsic::x86_mmx_psrai_d: {
9766     SDValue ShAmt = Op.getOperand(2);
9767     if (isa<ConstantSDNode>(ShAmt))
9768       return SDValue();
9769
9770     unsigned NewIntNo = 0;
9771     switch (IntNo) {
9772     case Intrinsic::x86_mmx_pslli_w:
9773       NewIntNo = Intrinsic::x86_mmx_psll_w;
9774       break;
9775     case Intrinsic::x86_mmx_pslli_d:
9776       NewIntNo = Intrinsic::x86_mmx_psll_d;
9777       break;
9778     case Intrinsic::x86_mmx_pslli_q:
9779       NewIntNo = Intrinsic::x86_mmx_psll_q;
9780       break;
9781     case Intrinsic::x86_mmx_psrli_w:
9782       NewIntNo = Intrinsic::x86_mmx_psrl_w;
9783       break;
9784     case Intrinsic::x86_mmx_psrli_d:
9785       NewIntNo = Intrinsic::x86_mmx_psrl_d;
9786       break;
9787     case Intrinsic::x86_mmx_psrli_q:
9788       NewIntNo = Intrinsic::x86_mmx_psrl_q;
9789       break;
9790     case Intrinsic::x86_mmx_psrai_w:
9791       NewIntNo = Intrinsic::x86_mmx_psra_w;
9792       break;
9793     case Intrinsic::x86_mmx_psrai_d:
9794       NewIntNo = Intrinsic::x86_mmx_psra_d;
9795       break;
9796     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9797     }
9798
9799     // The vector shift intrinsics with scalars uses 32b shift amounts but
9800     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9801     // to be zero.
9802     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9803                          DAG.getConstant(0, MVT::i32));
9804 // FIXME this must be lowered to get rid of the invalid type.
9805
9806     EVT VT = Op.getValueType();
9807     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9808     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9809                        DAG.getConstant(NewIntNo, MVT::i32),
9810                        Op.getOperand(1), ShAmt);
9811   }
9812   case Intrinsic::x86_sse42_pcmpistria128:
9813   case Intrinsic::x86_sse42_pcmpestria128:
9814   case Intrinsic::x86_sse42_pcmpistric128:
9815   case Intrinsic::x86_sse42_pcmpestric128:
9816   case Intrinsic::x86_sse42_pcmpistrio128:
9817   case Intrinsic::x86_sse42_pcmpestrio128:
9818   case Intrinsic::x86_sse42_pcmpistris128:
9819   case Intrinsic::x86_sse42_pcmpestris128:
9820   case Intrinsic::x86_sse42_pcmpistriz128:
9821   case Intrinsic::x86_sse42_pcmpestriz128: {
9822     unsigned Opcode;
9823     unsigned X86CC;
9824     switch (IntNo) {
9825     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9826     case Intrinsic::x86_sse42_pcmpistria128:
9827       Opcode = X86ISD::PCMPISTRI;
9828       X86CC = X86::COND_A;
9829       break;
9830     case Intrinsic::x86_sse42_pcmpestria128:
9831       Opcode = X86ISD::PCMPESTRI;
9832       X86CC = X86::COND_A;
9833       break;
9834     case Intrinsic::x86_sse42_pcmpistric128:
9835       Opcode = X86ISD::PCMPISTRI;
9836       X86CC = X86::COND_B;
9837       break;
9838     case Intrinsic::x86_sse42_pcmpestric128:
9839       Opcode = X86ISD::PCMPESTRI;
9840       X86CC = X86::COND_B;
9841       break;
9842     case Intrinsic::x86_sse42_pcmpistrio128:
9843       Opcode = X86ISD::PCMPISTRI;
9844       X86CC = X86::COND_O;
9845       break;
9846     case Intrinsic::x86_sse42_pcmpestrio128:
9847       Opcode = X86ISD::PCMPESTRI;
9848       X86CC = X86::COND_O;
9849       break;
9850     case Intrinsic::x86_sse42_pcmpistris128:
9851       Opcode = X86ISD::PCMPISTRI;
9852       X86CC = X86::COND_S;
9853       break;
9854     case Intrinsic::x86_sse42_pcmpestris128:
9855       Opcode = X86ISD::PCMPESTRI;
9856       X86CC = X86::COND_S;
9857       break;
9858     case Intrinsic::x86_sse42_pcmpistriz128:
9859       Opcode = X86ISD::PCMPISTRI;
9860       X86CC = X86::COND_E;
9861       break;
9862     case Intrinsic::x86_sse42_pcmpestriz128:
9863       Opcode = X86ISD::PCMPESTRI;
9864       X86CC = X86::COND_E;
9865       break;
9866     }
9867     SmallVector<SDValue, 5> NewOps;
9868     NewOps.append(Op->op_begin()+1, Op->op_end());
9869     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9870     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
9871     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9872                                 DAG.getConstant(X86CC, MVT::i8),
9873                                 SDValue(PCMP.getNode(), 1));
9874     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9875   }
9876   case Intrinsic::x86_sse42_pcmpistri128:
9877   case Intrinsic::x86_sse42_pcmpestri128: {
9878     unsigned Opcode;
9879     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
9880       Opcode = X86ISD::PCMPISTRI;
9881     else
9882       Opcode = X86ISD::PCMPESTRI;
9883
9884     SmallVector<SDValue, 5> NewOps;
9885     NewOps.append(Op->op_begin()+1, Op->op_end());
9886     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9887     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
9888   }
9889   }
9890 }
9891
9892 SDValue
9893 X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9894   DebugLoc dl = Op.getDebugLoc();
9895   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9896   switch (IntNo) {
9897   default: return SDValue();    // Don't custom lower most intrinsics.
9898
9899   // RDRAND intrinsics.
9900   case Intrinsic::x86_rdrand_16:
9901   case Intrinsic::x86_rdrand_32:
9902   case Intrinsic::x86_rdrand_64: {
9903     // Emit the node with the right value type.
9904     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
9905     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
9906
9907     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
9908     // return the value from Rand, which is always 0, casted to i32.
9909     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
9910                       DAG.getConstant(1, Op->getValueType(1)),
9911                       DAG.getConstant(X86::COND_B, MVT::i32),
9912                       SDValue(Result.getNode(), 1) };
9913     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
9914                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
9915                                   Ops, 4);
9916
9917     // Return { result, isValid, chain }.
9918     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
9919                        SDValue(Result.getNode(), 2));
9920   }
9921   }
9922 }
9923
9924 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9925                                            SelectionDAG &DAG) const {
9926   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9927   MFI->setReturnAddressIsTaken(true);
9928
9929   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9930   DebugLoc dl = Op.getDebugLoc();
9931
9932   if (Depth > 0) {
9933     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9934     SDValue Offset =
9935       DAG.getConstant(TD->getPointerSize(),
9936                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9937     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9938                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9939                                    FrameAddr, Offset),
9940                        MachinePointerInfo(), false, false, false, 0);
9941   }
9942
9943   // Just load the return address.
9944   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9945   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9946                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9947 }
9948
9949 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9950   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9951   MFI->setFrameAddressIsTaken(true);
9952
9953   EVT VT = Op.getValueType();
9954   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9955   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9956   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9957   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9958   while (Depth--)
9959     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9960                             MachinePointerInfo(),
9961                             false, false, false, 0);
9962   return FrameAddr;
9963 }
9964
9965 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9966                                                      SelectionDAG &DAG) const {
9967   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9968 }
9969
9970 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9971   SDValue Chain     = Op.getOperand(0);
9972   SDValue Offset    = Op.getOperand(1);
9973   SDValue Handler   = Op.getOperand(2);
9974   DebugLoc dl       = Op.getDebugLoc();
9975
9976   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9977                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9978                                      getPointerTy());
9979   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9980
9981   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9982                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9983   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9984   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9985                        false, false, 0);
9986   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9987
9988   return DAG.getNode(X86ISD::EH_RETURN, dl,
9989                      MVT::Other,
9990                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9991 }
9992
9993 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9994                                                   SelectionDAG &DAG) const {
9995   return Op.getOperand(0);
9996 }
9997
9998 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9999                                                 SelectionDAG &DAG) const {
10000   SDValue Root = Op.getOperand(0);
10001   SDValue Trmp = Op.getOperand(1); // trampoline
10002   SDValue FPtr = Op.getOperand(2); // nested function
10003   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10004   DebugLoc dl  = Op.getDebugLoc();
10005
10006   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10007
10008   if (Subtarget->is64Bit()) {
10009     SDValue OutChains[6];
10010
10011     // Large code-model.
10012     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10013     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10014
10015     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10016     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10017
10018     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10019
10020     // Load the pointer to the nested function into R11.
10021     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10022     SDValue Addr = Trmp;
10023     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10024                                 Addr, MachinePointerInfo(TrmpAddr),
10025                                 false, false, 0);
10026
10027     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10028                        DAG.getConstant(2, MVT::i64));
10029     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10030                                 MachinePointerInfo(TrmpAddr, 2),
10031                                 false, false, 2);
10032
10033     // Load the 'nest' parameter value into R10.
10034     // R10 is specified in X86CallingConv.td
10035     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10036     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10037                        DAG.getConstant(10, MVT::i64));
10038     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10039                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10040                                 false, false, 0);
10041
10042     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10043                        DAG.getConstant(12, MVT::i64));
10044     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10045                                 MachinePointerInfo(TrmpAddr, 12),
10046                                 false, false, 2);
10047
10048     // Jump to the nested function.
10049     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10050     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10051                        DAG.getConstant(20, MVT::i64));
10052     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10053                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10054                                 false, false, 0);
10055
10056     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10057     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10058                        DAG.getConstant(22, MVT::i64));
10059     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10060                                 MachinePointerInfo(TrmpAddr, 22),
10061                                 false, false, 0);
10062
10063     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10064   } else {
10065     const Function *Func =
10066       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10067     CallingConv::ID CC = Func->getCallingConv();
10068     unsigned NestReg;
10069
10070     switch (CC) {
10071     default:
10072       llvm_unreachable("Unsupported calling convention");
10073     case CallingConv::C:
10074     case CallingConv::X86_StdCall: {
10075       // Pass 'nest' parameter in ECX.
10076       // Must be kept in sync with X86CallingConv.td
10077       NestReg = X86::ECX;
10078
10079       // Check that ECX wasn't needed by an 'inreg' parameter.
10080       FunctionType *FTy = Func->getFunctionType();
10081       const AttrListPtr &Attrs = Func->getAttributes();
10082
10083       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10084         unsigned InRegCount = 0;
10085         unsigned Idx = 1;
10086
10087         for (FunctionType::param_iterator I = FTy->param_begin(),
10088              E = FTy->param_end(); I != E; ++I, ++Idx)
10089           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10090             // FIXME: should only count parameters that are lowered to integers.
10091             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10092
10093         if (InRegCount > 2) {
10094           report_fatal_error("Nest register in use - reduce number of inreg"
10095                              " parameters!");
10096         }
10097       }
10098       break;
10099     }
10100     case CallingConv::X86_FastCall:
10101     case CallingConv::X86_ThisCall:
10102     case CallingConv::Fast:
10103       // Pass 'nest' parameter in EAX.
10104       // Must be kept in sync with X86CallingConv.td
10105       NestReg = X86::EAX;
10106       break;
10107     }
10108
10109     SDValue OutChains[4];
10110     SDValue Addr, Disp;
10111
10112     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10113                        DAG.getConstant(10, MVT::i32));
10114     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10115
10116     // This is storing the opcode for MOV32ri.
10117     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10118     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10119     OutChains[0] = DAG.getStore(Root, dl,
10120                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10121                                 Trmp, MachinePointerInfo(TrmpAddr),
10122                                 false, false, 0);
10123
10124     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10125                        DAG.getConstant(1, MVT::i32));
10126     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10127                                 MachinePointerInfo(TrmpAddr, 1),
10128                                 false, false, 1);
10129
10130     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10131     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10132                        DAG.getConstant(5, MVT::i32));
10133     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10134                                 MachinePointerInfo(TrmpAddr, 5),
10135                                 false, false, 1);
10136
10137     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10138                        DAG.getConstant(6, MVT::i32));
10139     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10140                                 MachinePointerInfo(TrmpAddr, 6),
10141                                 false, false, 1);
10142
10143     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10144   }
10145 }
10146
10147 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10148                                             SelectionDAG &DAG) const {
10149   /*
10150    The rounding mode is in bits 11:10 of FPSR, and has the following
10151    settings:
10152      00 Round to nearest
10153      01 Round to -inf
10154      10 Round to +inf
10155      11 Round to 0
10156
10157   FLT_ROUNDS, on the other hand, expects the following:
10158     -1 Undefined
10159      0 Round to 0
10160      1 Round to nearest
10161      2 Round to +inf
10162      3 Round to -inf
10163
10164   To perform the conversion, we do:
10165     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10166   */
10167
10168   MachineFunction &MF = DAG.getMachineFunction();
10169   const TargetMachine &TM = MF.getTarget();
10170   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10171   unsigned StackAlignment = TFI.getStackAlignment();
10172   EVT VT = Op.getValueType();
10173   DebugLoc DL = Op.getDebugLoc();
10174
10175   // Save FP Control Word to stack slot
10176   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10177   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10178
10179
10180   MachineMemOperand *MMO =
10181    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10182                            MachineMemOperand::MOStore, 2, 2);
10183
10184   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10185   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10186                                           DAG.getVTList(MVT::Other),
10187                                           Ops, 2, MVT::i16, MMO);
10188
10189   // Load FP Control Word from stack slot
10190   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10191                             MachinePointerInfo(), false, false, false, 0);
10192
10193   // Transform as necessary
10194   SDValue CWD1 =
10195     DAG.getNode(ISD::SRL, DL, MVT::i16,
10196                 DAG.getNode(ISD::AND, DL, MVT::i16,
10197                             CWD, DAG.getConstant(0x800, MVT::i16)),
10198                 DAG.getConstant(11, MVT::i8));
10199   SDValue CWD2 =
10200     DAG.getNode(ISD::SRL, DL, MVT::i16,
10201                 DAG.getNode(ISD::AND, DL, MVT::i16,
10202                             CWD, DAG.getConstant(0x400, MVT::i16)),
10203                 DAG.getConstant(9, MVT::i8));
10204
10205   SDValue RetVal =
10206     DAG.getNode(ISD::AND, DL, MVT::i16,
10207                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10208                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10209                             DAG.getConstant(1, MVT::i16)),
10210                 DAG.getConstant(3, MVT::i16));
10211
10212
10213   return DAG.getNode((VT.getSizeInBits() < 16 ?
10214                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10215 }
10216
10217 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10218   EVT VT = Op.getValueType();
10219   EVT OpVT = VT;
10220   unsigned NumBits = VT.getSizeInBits();
10221   DebugLoc dl = Op.getDebugLoc();
10222
10223   Op = Op.getOperand(0);
10224   if (VT == MVT::i8) {
10225     // Zero extend to i32 since there is not an i8 bsr.
10226     OpVT = MVT::i32;
10227     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10228   }
10229
10230   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10231   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10232   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10233
10234   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10235   SDValue Ops[] = {
10236     Op,
10237     DAG.getConstant(NumBits+NumBits-1, OpVT),
10238     DAG.getConstant(X86::COND_E, MVT::i8),
10239     Op.getValue(1)
10240   };
10241   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10242
10243   // Finally xor with NumBits-1.
10244   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10245
10246   if (VT == MVT::i8)
10247     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10248   return Op;
10249 }
10250
10251 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10252                                                 SelectionDAG &DAG) const {
10253   EVT VT = Op.getValueType();
10254   EVT OpVT = VT;
10255   unsigned NumBits = VT.getSizeInBits();
10256   DebugLoc dl = Op.getDebugLoc();
10257
10258   Op = Op.getOperand(0);
10259   if (VT == MVT::i8) {
10260     // Zero extend to i32 since there is not an i8 bsr.
10261     OpVT = MVT::i32;
10262     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10263   }
10264
10265   // Issue a bsr (scan bits in reverse).
10266   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10267   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10268
10269   // And xor with NumBits-1.
10270   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10271
10272   if (VT == MVT::i8)
10273     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10274   return Op;
10275 }
10276
10277 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10278   EVT VT = Op.getValueType();
10279   unsigned NumBits = VT.getSizeInBits();
10280   DebugLoc dl = Op.getDebugLoc();
10281   Op = Op.getOperand(0);
10282
10283   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10284   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10285   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10286
10287   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10288   SDValue Ops[] = {
10289     Op,
10290     DAG.getConstant(NumBits, VT),
10291     DAG.getConstant(X86::COND_E, MVT::i8),
10292     Op.getValue(1)
10293   };
10294   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10295 }
10296
10297 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10298 // ones, and then concatenate the result back.
10299 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10300   EVT VT = Op.getValueType();
10301
10302   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10303          "Unsupported value type for operation");
10304
10305   unsigned NumElems = VT.getVectorNumElements();
10306   DebugLoc dl = Op.getDebugLoc();
10307
10308   // Extract the LHS vectors
10309   SDValue LHS = Op.getOperand(0);
10310   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10311   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10312
10313   // Extract the RHS vectors
10314   SDValue RHS = Op.getOperand(1);
10315   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10316   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10317
10318   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10319   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10320
10321   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10322                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10323                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10324 }
10325
10326 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10327   assert(Op.getValueType().getSizeInBits() == 256 &&
10328          Op.getValueType().isInteger() &&
10329          "Only handle AVX 256-bit vector integer operation");
10330   return Lower256IntArith(Op, DAG);
10331 }
10332
10333 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10334   assert(Op.getValueType().getSizeInBits() == 256 &&
10335          Op.getValueType().isInteger() &&
10336          "Only handle AVX 256-bit vector integer operation");
10337   return Lower256IntArith(Op, DAG);
10338 }
10339
10340 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10341   EVT VT = Op.getValueType();
10342
10343   // Decompose 256-bit ops into smaller 128-bit ops.
10344   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10345     return Lower256IntArith(Op, DAG);
10346
10347   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10348          "Only know how to lower V2I64/V4I64 multiply");
10349
10350   DebugLoc dl = Op.getDebugLoc();
10351
10352   //  Ahi = psrlqi(a, 32);
10353   //  Bhi = psrlqi(b, 32);
10354   //
10355   //  AloBlo = pmuludq(a, b);
10356   //  AloBhi = pmuludq(a, Bhi);
10357   //  AhiBlo = pmuludq(Ahi, b);
10358
10359   //  AloBhi = psllqi(AloBhi, 32);
10360   //  AhiBlo = psllqi(AhiBlo, 32);
10361   //  return AloBlo + AloBhi + AhiBlo;
10362
10363   SDValue A = Op.getOperand(0);
10364   SDValue B = Op.getOperand(1);
10365
10366   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10367
10368   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10369   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10370
10371   // Bit cast to 32-bit vectors for MULUDQ
10372   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10373   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10374   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10375   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10376   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10377
10378   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10379   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10380   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10381
10382   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10383   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10384
10385   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10386   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10387 }
10388
10389 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10390
10391   EVT VT = Op.getValueType();
10392   DebugLoc dl = Op.getDebugLoc();
10393   SDValue R = Op.getOperand(0);
10394   SDValue Amt = Op.getOperand(1);
10395   LLVMContext *Context = DAG.getContext();
10396
10397   if (!Subtarget->hasSSE2())
10398     return SDValue();
10399
10400   // Optimize shl/srl/sra with constant shift amount.
10401   if (isSplatVector(Amt.getNode())) {
10402     SDValue SclrAmt = Amt->getOperand(0);
10403     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10404       uint64_t ShiftAmt = C->getZExtValue();
10405
10406       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10407           (Subtarget->hasAVX2() &&
10408            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10409         if (Op.getOpcode() == ISD::SHL)
10410           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10411                              DAG.getConstant(ShiftAmt, MVT::i32));
10412         if (Op.getOpcode() == ISD::SRL)
10413           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10414                              DAG.getConstant(ShiftAmt, MVT::i32));
10415         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10416           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10417                              DAG.getConstant(ShiftAmt, MVT::i32));
10418       }
10419
10420       if (VT == MVT::v16i8) {
10421         if (Op.getOpcode() == ISD::SHL) {
10422           // Make a large shift.
10423           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10424                                     DAG.getConstant(ShiftAmt, MVT::i32));
10425           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10426           // Zero out the rightmost bits.
10427           SmallVector<SDValue, 16> V(16,
10428                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10429                                                      MVT::i8));
10430           return DAG.getNode(ISD::AND, dl, VT, SHL,
10431                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10432         }
10433         if (Op.getOpcode() == ISD::SRL) {
10434           // Make a large shift.
10435           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10436                                     DAG.getConstant(ShiftAmt, MVT::i32));
10437           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10438           // Zero out the leftmost bits.
10439           SmallVector<SDValue, 16> V(16,
10440                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10441                                                      MVT::i8));
10442           return DAG.getNode(ISD::AND, dl, VT, SRL,
10443                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10444         }
10445         if (Op.getOpcode() == ISD::SRA) {
10446           if (ShiftAmt == 7) {
10447             // R s>> 7  ===  R s< 0
10448             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10449             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10450           }
10451
10452           // R s>> a === ((R u>> a) ^ m) - m
10453           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10454           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10455                                                          MVT::i8));
10456           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10457           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10458           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10459           return Res;
10460         }
10461         llvm_unreachable("Unknown shift opcode.");
10462       }
10463
10464       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10465         if (Op.getOpcode() == ISD::SHL) {
10466           // Make a large shift.
10467           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10468                                     DAG.getConstant(ShiftAmt, MVT::i32));
10469           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10470           // Zero out the rightmost bits.
10471           SmallVector<SDValue, 32> V(32,
10472                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10473                                                      MVT::i8));
10474           return DAG.getNode(ISD::AND, dl, VT, SHL,
10475                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10476         }
10477         if (Op.getOpcode() == ISD::SRL) {
10478           // Make a large shift.
10479           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10480                                     DAG.getConstant(ShiftAmt, MVT::i32));
10481           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10482           // Zero out the leftmost bits.
10483           SmallVector<SDValue, 32> V(32,
10484                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10485                                                      MVT::i8));
10486           return DAG.getNode(ISD::AND, dl, VT, SRL,
10487                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10488         }
10489         if (Op.getOpcode() == ISD::SRA) {
10490           if (ShiftAmt == 7) {
10491             // R s>> 7  ===  R s< 0
10492             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10493             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10494           }
10495
10496           // R s>> a === ((R u>> a) ^ m) - m
10497           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10498           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10499                                                          MVT::i8));
10500           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10501           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10502           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10503           return Res;
10504         }
10505         llvm_unreachable("Unknown shift opcode.");
10506       }
10507     }
10508   }
10509
10510   // Lower SHL with variable shift amount.
10511   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10512     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10513                      DAG.getConstant(23, MVT::i32));
10514
10515     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10516     Constant *C = ConstantDataVector::get(*Context, CV);
10517     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10518     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10519                                  MachinePointerInfo::getConstantPool(),
10520                                  false, false, false, 16);
10521
10522     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10523     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10524     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10525     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10526   }
10527   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10528     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10529
10530     // a = a << 5;
10531     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10532                      DAG.getConstant(5, MVT::i32));
10533     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10534
10535     // Turn 'a' into a mask suitable for VSELECT
10536     SDValue VSelM = DAG.getConstant(0x80, VT);
10537     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10538     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10539
10540     SDValue CM1 = DAG.getConstant(0x0f, VT);
10541     SDValue CM2 = DAG.getConstant(0x3f, VT);
10542
10543     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10544     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10545     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10546                             DAG.getConstant(4, MVT::i32), DAG);
10547     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10548     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10549
10550     // a += a
10551     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10552     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10553     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10554
10555     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10556     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10557     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10558                             DAG.getConstant(2, MVT::i32), DAG);
10559     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10560     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10561
10562     // a += a
10563     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10564     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10565     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10566
10567     // return VSELECT(r, r+r, a);
10568     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10569                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10570     return R;
10571   }
10572
10573   // Decompose 256-bit shifts into smaller 128-bit shifts.
10574   if (VT.getSizeInBits() == 256) {
10575     unsigned NumElems = VT.getVectorNumElements();
10576     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10577     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10578
10579     // Extract the two vectors
10580     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10581     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10582
10583     // Recreate the shift amount vectors
10584     SDValue Amt1, Amt2;
10585     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10586       // Constant shift amount
10587       SmallVector<SDValue, 4> Amt1Csts;
10588       SmallVector<SDValue, 4> Amt2Csts;
10589       for (unsigned i = 0; i != NumElems/2; ++i)
10590         Amt1Csts.push_back(Amt->getOperand(i));
10591       for (unsigned i = NumElems/2; i != NumElems; ++i)
10592         Amt2Csts.push_back(Amt->getOperand(i));
10593
10594       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10595                                  &Amt1Csts[0], NumElems/2);
10596       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10597                                  &Amt2Csts[0], NumElems/2);
10598     } else {
10599       // Variable shift amount
10600       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10601       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10602     }
10603
10604     // Issue new vector shifts for the smaller types
10605     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10606     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10607
10608     // Concatenate the result back
10609     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10610   }
10611
10612   return SDValue();
10613 }
10614
10615 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10616   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10617   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10618   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10619   // has only one use.
10620   SDNode *N = Op.getNode();
10621   SDValue LHS = N->getOperand(0);
10622   SDValue RHS = N->getOperand(1);
10623   unsigned BaseOp = 0;
10624   unsigned Cond = 0;
10625   DebugLoc DL = Op.getDebugLoc();
10626   switch (Op.getOpcode()) {
10627   default: llvm_unreachable("Unknown ovf instruction!");
10628   case ISD::SADDO:
10629     // A subtract of one will be selected as a INC. Note that INC doesn't
10630     // set CF, so we can't do this for UADDO.
10631     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10632       if (C->isOne()) {
10633         BaseOp = X86ISD::INC;
10634         Cond = X86::COND_O;
10635         break;
10636       }
10637     BaseOp = X86ISD::ADD;
10638     Cond = X86::COND_O;
10639     break;
10640   case ISD::UADDO:
10641     BaseOp = X86ISD::ADD;
10642     Cond = X86::COND_B;
10643     break;
10644   case ISD::SSUBO:
10645     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10646     // set CF, so we can't do this for USUBO.
10647     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10648       if (C->isOne()) {
10649         BaseOp = X86ISD::DEC;
10650         Cond = X86::COND_O;
10651         break;
10652       }
10653     BaseOp = X86ISD::SUB;
10654     Cond = X86::COND_O;
10655     break;
10656   case ISD::USUBO:
10657     BaseOp = X86ISD::SUB;
10658     Cond = X86::COND_B;
10659     break;
10660   case ISD::SMULO:
10661     BaseOp = X86ISD::SMUL;
10662     Cond = X86::COND_O;
10663     break;
10664   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10665     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10666                                  MVT::i32);
10667     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10668
10669     SDValue SetCC =
10670       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10671                   DAG.getConstant(X86::COND_O, MVT::i32),
10672                   SDValue(Sum.getNode(), 2));
10673
10674     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10675   }
10676   }
10677
10678   // Also sets EFLAGS.
10679   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10680   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10681
10682   SDValue SetCC =
10683     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10684                 DAG.getConstant(Cond, MVT::i32),
10685                 SDValue(Sum.getNode(), 1));
10686
10687   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10688 }
10689
10690 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10691                                                   SelectionDAG &DAG) const {
10692   DebugLoc dl = Op.getDebugLoc();
10693   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10694   EVT VT = Op.getValueType();
10695
10696   if (!Subtarget->hasSSE2() || !VT.isVector())
10697     return SDValue();
10698
10699   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10700                       ExtraVT.getScalarType().getSizeInBits();
10701   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10702
10703   switch (VT.getSimpleVT().SimpleTy) {
10704     default: return SDValue();
10705     case MVT::v8i32:
10706     case MVT::v16i16:
10707       if (!Subtarget->hasAVX())
10708         return SDValue();
10709       if (!Subtarget->hasAVX2()) {
10710         // needs to be split
10711         unsigned NumElems = VT.getVectorNumElements();
10712
10713         // Extract the LHS vectors
10714         SDValue LHS = Op.getOperand(0);
10715         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10716         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10717
10718         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10719         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10720
10721         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10722         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10723         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10724                                    ExtraNumElems/2);
10725         SDValue Extra = DAG.getValueType(ExtraVT);
10726
10727         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10728         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10729
10730         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10731       }
10732       // fall through
10733     case MVT::v4i32:
10734     case MVT::v8i16: {
10735       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10736                                          Op.getOperand(0), ShAmt, DAG);
10737       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10738     }
10739   }
10740 }
10741
10742
10743 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10744   DebugLoc dl = Op.getDebugLoc();
10745
10746   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10747   // There isn't any reason to disable it if the target processor supports it.
10748   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10749     SDValue Chain = Op.getOperand(0);
10750     SDValue Zero = DAG.getConstant(0, MVT::i32);
10751     SDValue Ops[] = {
10752       DAG.getRegister(X86::ESP, MVT::i32), // Base
10753       DAG.getTargetConstant(1, MVT::i8),   // Scale
10754       DAG.getRegister(0, MVT::i32),        // Index
10755       DAG.getTargetConstant(0, MVT::i32),  // Disp
10756       DAG.getRegister(0, MVT::i32),        // Segment.
10757       Zero,
10758       Chain
10759     };
10760     SDNode *Res =
10761       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10762                           array_lengthof(Ops));
10763     return SDValue(Res, 0);
10764   }
10765
10766   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10767   if (!isDev)
10768     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10769
10770   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10771   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10772   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10773   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10774
10775   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10776   if (!Op1 && !Op2 && !Op3 && Op4)
10777     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10778
10779   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10780   if (Op1 && !Op2 && !Op3 && !Op4)
10781     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10782
10783   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10784   //           (MFENCE)>;
10785   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10786 }
10787
10788 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10789                                              SelectionDAG &DAG) const {
10790   DebugLoc dl = Op.getDebugLoc();
10791   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10792     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10793   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10794     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10795
10796   // The only fence that needs an instruction is a sequentially-consistent
10797   // cross-thread fence.
10798   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10799     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10800     // no-sse2). There isn't any reason to disable it if the target processor
10801     // supports it.
10802     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10803       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10804
10805     SDValue Chain = Op.getOperand(0);
10806     SDValue Zero = DAG.getConstant(0, MVT::i32);
10807     SDValue Ops[] = {
10808       DAG.getRegister(X86::ESP, MVT::i32), // Base
10809       DAG.getTargetConstant(1, MVT::i8),   // Scale
10810       DAG.getRegister(0, MVT::i32),        // Index
10811       DAG.getTargetConstant(0, MVT::i32),  // Disp
10812       DAG.getRegister(0, MVT::i32),        // Segment.
10813       Zero,
10814       Chain
10815     };
10816     SDNode *Res =
10817       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10818                          array_lengthof(Ops));
10819     return SDValue(Res, 0);
10820   }
10821
10822   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10823   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10824 }
10825
10826
10827 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10828   EVT T = Op.getValueType();
10829   DebugLoc DL = Op.getDebugLoc();
10830   unsigned Reg = 0;
10831   unsigned size = 0;
10832   switch(T.getSimpleVT().SimpleTy) {
10833   default: llvm_unreachable("Invalid value type!");
10834   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10835   case MVT::i16: Reg = X86::AX;  size = 2; break;
10836   case MVT::i32: Reg = X86::EAX; size = 4; break;
10837   case MVT::i64:
10838     assert(Subtarget->is64Bit() && "Node not type legal!");
10839     Reg = X86::RAX; size = 8;
10840     break;
10841   }
10842   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10843                                     Op.getOperand(2), SDValue());
10844   SDValue Ops[] = { cpIn.getValue(0),
10845                     Op.getOperand(1),
10846                     Op.getOperand(3),
10847                     DAG.getTargetConstant(size, MVT::i8),
10848                     cpIn.getValue(1) };
10849   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10850   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10851   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10852                                            Ops, 5, T, MMO);
10853   SDValue cpOut =
10854     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10855   return cpOut;
10856 }
10857
10858 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10859                                                  SelectionDAG &DAG) const {
10860   assert(Subtarget->is64Bit() && "Result not type legalized?");
10861   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10862   SDValue TheChain = Op.getOperand(0);
10863   DebugLoc dl = Op.getDebugLoc();
10864   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10865   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10866   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10867                                    rax.getValue(2));
10868   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10869                             DAG.getConstant(32, MVT::i8));
10870   SDValue Ops[] = {
10871     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10872     rdx.getValue(1)
10873   };
10874   return DAG.getMergeValues(Ops, 2, dl);
10875 }
10876
10877 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10878                                             SelectionDAG &DAG) const {
10879   EVT SrcVT = Op.getOperand(0).getValueType();
10880   EVT DstVT = Op.getValueType();
10881   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10882          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10883   assert((DstVT == MVT::i64 ||
10884           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10885          "Unexpected custom BITCAST");
10886   // i64 <=> MMX conversions are Legal.
10887   if (SrcVT==MVT::i64 && DstVT.isVector())
10888     return Op;
10889   if (DstVT==MVT::i64 && SrcVT.isVector())
10890     return Op;
10891   // MMX <=> MMX conversions are Legal.
10892   if (SrcVT.isVector() && DstVT.isVector())
10893     return Op;
10894   // All other conversions need to be expanded.
10895   return SDValue();
10896 }
10897
10898 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10899   SDNode *Node = Op.getNode();
10900   DebugLoc dl = Node->getDebugLoc();
10901   EVT T = Node->getValueType(0);
10902   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10903                               DAG.getConstant(0, T), Node->getOperand(2));
10904   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10905                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10906                        Node->getOperand(0),
10907                        Node->getOperand(1), negOp,
10908                        cast<AtomicSDNode>(Node)->getSrcValue(),
10909                        cast<AtomicSDNode>(Node)->getAlignment(),
10910                        cast<AtomicSDNode>(Node)->getOrdering(),
10911                        cast<AtomicSDNode>(Node)->getSynchScope());
10912 }
10913
10914 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10915   SDNode *Node = Op.getNode();
10916   DebugLoc dl = Node->getDebugLoc();
10917   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10918
10919   // Convert seq_cst store -> xchg
10920   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10921   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10922   //        (The only way to get a 16-byte store is cmpxchg16b)
10923   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10924   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10925       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10926     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10927                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10928                                  Node->getOperand(0),
10929                                  Node->getOperand(1), Node->getOperand(2),
10930                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10931                                  cast<AtomicSDNode>(Node)->getOrdering(),
10932                                  cast<AtomicSDNode>(Node)->getSynchScope());
10933     return Swap.getValue(1);
10934   }
10935   // Other atomic stores have a simple pattern.
10936   return Op;
10937 }
10938
10939 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10940   EVT VT = Op.getNode()->getValueType(0);
10941
10942   // Let legalize expand this if it isn't a legal type yet.
10943   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10944     return SDValue();
10945
10946   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10947
10948   unsigned Opc;
10949   bool ExtraOp = false;
10950   switch (Op.getOpcode()) {
10951   default: llvm_unreachable("Invalid code");
10952   case ISD::ADDC: Opc = X86ISD::ADD; break;
10953   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10954   case ISD::SUBC: Opc = X86ISD::SUB; break;
10955   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10956   }
10957
10958   if (!ExtraOp)
10959     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10960                        Op.getOperand(1));
10961   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10962                      Op.getOperand(1), Op.getOperand(2));
10963 }
10964
10965 /// LowerOperation - Provide custom lowering hooks for some operations.
10966 ///
10967 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10968   switch (Op.getOpcode()) {
10969   default: llvm_unreachable("Should not custom lower this!");
10970   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10971   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10972   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10973   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10974   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10975   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10976   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10977   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10978   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10979   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10980   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10981   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10982   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10983   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10984   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10985   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10986   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10987   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10988   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10989   case ISD::SHL_PARTS:
10990   case ISD::SRA_PARTS:
10991   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10992   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10993   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10994   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10995   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10996   case ISD::FABS:               return LowerFABS(Op, DAG);
10997   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10998   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10999   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11000   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11001   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11002   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11003   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11004   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11005   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11006   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11007   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11008   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11009   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11010   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11011   case ISD::FRAME_TO_ARGS_OFFSET:
11012                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11013   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11014   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11015   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11016   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11017   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11018   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11019   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11020   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11021   case ISD::MUL:                return LowerMUL(Op, DAG);
11022   case ISD::SRA:
11023   case ISD::SRL:
11024   case ISD::SHL:                return LowerShift(Op, DAG);
11025   case ISD::SADDO:
11026   case ISD::UADDO:
11027   case ISD::SSUBO:
11028   case ISD::USUBO:
11029   case ISD::SMULO:
11030   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11031   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
11032   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11033   case ISD::ADDC:
11034   case ISD::ADDE:
11035   case ISD::SUBC:
11036   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11037   case ISD::ADD:                return LowerADD(Op, DAG);
11038   case ISD::SUB:                return LowerSUB(Op, DAG);
11039   }
11040 }
11041
11042 static void ReplaceATOMIC_LOAD(SDNode *Node,
11043                                   SmallVectorImpl<SDValue> &Results,
11044                                   SelectionDAG &DAG) {
11045   DebugLoc dl = Node->getDebugLoc();
11046   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11047
11048   // Convert wide load -> cmpxchg8b/cmpxchg16b
11049   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11050   //        (The only way to get a 16-byte load is cmpxchg16b)
11051   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11052   SDValue Zero = DAG.getConstant(0, VT);
11053   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11054                                Node->getOperand(0),
11055                                Node->getOperand(1), Zero, Zero,
11056                                cast<AtomicSDNode>(Node)->getMemOperand(),
11057                                cast<AtomicSDNode>(Node)->getOrdering(),
11058                                cast<AtomicSDNode>(Node)->getSynchScope());
11059   Results.push_back(Swap.getValue(0));
11060   Results.push_back(Swap.getValue(1));
11061 }
11062
11063 void X86TargetLowering::
11064 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11065                         SelectionDAG &DAG, unsigned NewOp) const {
11066   DebugLoc dl = Node->getDebugLoc();
11067   assert (Node->getValueType(0) == MVT::i64 &&
11068           "Only know how to expand i64 atomics");
11069
11070   SDValue Chain = Node->getOperand(0);
11071   SDValue In1 = Node->getOperand(1);
11072   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11073                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11074   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11075                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11076   SDValue Ops[] = { Chain, In1, In2L, In2H };
11077   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11078   SDValue Result =
11079     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11080                             cast<MemSDNode>(Node)->getMemOperand());
11081   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11082   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11083   Results.push_back(Result.getValue(2));
11084 }
11085
11086 /// ReplaceNodeResults - Replace a node with an illegal result type
11087 /// with a new node built out of custom code.
11088 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11089                                            SmallVectorImpl<SDValue>&Results,
11090                                            SelectionDAG &DAG) const {
11091   DebugLoc dl = N->getDebugLoc();
11092   switch (N->getOpcode()) {
11093   default:
11094     llvm_unreachable("Do not know how to custom type legalize this operation!");
11095   case ISD::SIGN_EXTEND_INREG:
11096   case ISD::ADDC:
11097   case ISD::ADDE:
11098   case ISD::SUBC:
11099   case ISD::SUBE:
11100     // We don't want to expand or promote these.
11101     return;
11102   case ISD::FP_TO_SINT:
11103   case ISD::FP_TO_UINT: {
11104     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11105
11106     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11107       return;
11108
11109     std::pair<SDValue,SDValue> Vals =
11110         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11111     SDValue FIST = Vals.first, StackSlot = Vals.second;
11112     if (FIST.getNode() != 0) {
11113       EVT VT = N->getValueType(0);
11114       // Return a load from the stack slot.
11115       if (StackSlot.getNode() != 0)
11116         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11117                                       MachinePointerInfo(),
11118                                       false, false, false, 0));
11119       else
11120         Results.push_back(FIST);
11121     }
11122     return;
11123   }
11124   case ISD::READCYCLECOUNTER: {
11125     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11126     SDValue TheChain = N->getOperand(0);
11127     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11128     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11129                                      rd.getValue(1));
11130     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11131                                      eax.getValue(2));
11132     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11133     SDValue Ops[] = { eax, edx };
11134     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11135     Results.push_back(edx.getValue(1));
11136     return;
11137   }
11138   case ISD::ATOMIC_CMP_SWAP: {
11139     EVT T = N->getValueType(0);
11140     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11141     bool Regs64bit = T == MVT::i128;
11142     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11143     SDValue cpInL, cpInH;
11144     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11145                         DAG.getConstant(0, HalfT));
11146     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11147                         DAG.getConstant(1, HalfT));
11148     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11149                              Regs64bit ? X86::RAX : X86::EAX,
11150                              cpInL, SDValue());
11151     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11152                              Regs64bit ? X86::RDX : X86::EDX,
11153                              cpInH, cpInL.getValue(1));
11154     SDValue swapInL, swapInH;
11155     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11156                           DAG.getConstant(0, HalfT));
11157     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11158                           DAG.getConstant(1, HalfT));
11159     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11160                                Regs64bit ? X86::RBX : X86::EBX,
11161                                swapInL, cpInH.getValue(1));
11162     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11163                                Regs64bit ? X86::RCX : X86::ECX,
11164                                swapInH, swapInL.getValue(1));
11165     SDValue Ops[] = { swapInH.getValue(0),
11166                       N->getOperand(1),
11167                       swapInH.getValue(1) };
11168     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11169     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11170     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11171                                   X86ISD::LCMPXCHG8_DAG;
11172     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11173                                              Ops, 3, T, MMO);
11174     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11175                                         Regs64bit ? X86::RAX : X86::EAX,
11176                                         HalfT, Result.getValue(1));
11177     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11178                                         Regs64bit ? X86::RDX : X86::EDX,
11179                                         HalfT, cpOutL.getValue(2));
11180     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11181     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11182     Results.push_back(cpOutH.getValue(1));
11183     return;
11184   }
11185   case ISD::ATOMIC_LOAD_ADD:
11186     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11187     return;
11188   case ISD::ATOMIC_LOAD_AND:
11189     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11190     return;
11191   case ISD::ATOMIC_LOAD_NAND:
11192     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11193     return;
11194   case ISD::ATOMIC_LOAD_OR:
11195     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11196     return;
11197   case ISD::ATOMIC_LOAD_SUB:
11198     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11199     return;
11200   case ISD::ATOMIC_LOAD_XOR:
11201     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11202     return;
11203   case ISD::ATOMIC_SWAP:
11204     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11205     return;
11206   case ISD::ATOMIC_LOAD:
11207     ReplaceATOMIC_LOAD(N, Results, DAG);
11208   }
11209 }
11210
11211 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11212   switch (Opcode) {
11213   default: return NULL;
11214   case X86ISD::BSF:                return "X86ISD::BSF";
11215   case X86ISD::BSR:                return "X86ISD::BSR";
11216   case X86ISD::SHLD:               return "X86ISD::SHLD";
11217   case X86ISD::SHRD:               return "X86ISD::SHRD";
11218   case X86ISD::FAND:               return "X86ISD::FAND";
11219   case X86ISD::FOR:                return "X86ISD::FOR";
11220   case X86ISD::FXOR:               return "X86ISD::FXOR";
11221   case X86ISD::FSRL:               return "X86ISD::FSRL";
11222   case X86ISD::FILD:               return "X86ISD::FILD";
11223   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11224   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11225   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11226   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11227   case X86ISD::FLD:                return "X86ISD::FLD";
11228   case X86ISD::FST:                return "X86ISD::FST";
11229   case X86ISD::CALL:               return "X86ISD::CALL";
11230   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11231   case X86ISD::BT:                 return "X86ISD::BT";
11232   case X86ISD::CMP:                return "X86ISD::CMP";
11233   case X86ISD::COMI:               return "X86ISD::COMI";
11234   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11235   case X86ISD::SETCC:              return "X86ISD::SETCC";
11236   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11237   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11238   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11239   case X86ISD::CMOV:               return "X86ISD::CMOV";
11240   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11241   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11242   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11243   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11244   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11245   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11246   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11247   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11248   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11249   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11250   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11251   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11252   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11253   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11254   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11255   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11256   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11257   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11258   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11259   case X86ISD::HADD:               return "X86ISD::HADD";
11260   case X86ISD::HSUB:               return "X86ISD::HSUB";
11261   case X86ISD::FHADD:              return "X86ISD::FHADD";
11262   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11263   case X86ISD::FMAX:               return "X86ISD::FMAX";
11264   case X86ISD::FMIN:               return "X86ISD::FMIN";
11265   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11266   case X86ISD::FRCP:               return "X86ISD::FRCP";
11267   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11268   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11269   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11270   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11271   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11272   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11273   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11274   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11275   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11276   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11277   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11278   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11279   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11280   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11281   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11282   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11283   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11284   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11285   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11286   case X86ISD::VSHL:               return "X86ISD::VSHL";
11287   case X86ISD::VSRL:               return "X86ISD::VSRL";
11288   case X86ISD::VSRA:               return "X86ISD::VSRA";
11289   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11290   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11291   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11292   case X86ISD::CMPP:               return "X86ISD::CMPP";
11293   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11294   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11295   case X86ISD::ADD:                return "X86ISD::ADD";
11296   case X86ISD::SUB:                return "X86ISD::SUB";
11297   case X86ISD::ADC:                return "X86ISD::ADC";
11298   case X86ISD::SBB:                return "X86ISD::SBB";
11299   case X86ISD::SMUL:               return "X86ISD::SMUL";
11300   case X86ISD::UMUL:               return "X86ISD::UMUL";
11301   case X86ISD::INC:                return "X86ISD::INC";
11302   case X86ISD::DEC:                return "X86ISD::DEC";
11303   case X86ISD::OR:                 return "X86ISD::OR";
11304   case X86ISD::XOR:                return "X86ISD::XOR";
11305   case X86ISD::AND:                return "X86ISD::AND";
11306   case X86ISD::ANDN:               return "X86ISD::ANDN";
11307   case X86ISD::BLSI:               return "X86ISD::BLSI";
11308   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11309   case X86ISD::BLSR:               return "X86ISD::BLSR";
11310   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11311   case X86ISD::PTEST:              return "X86ISD::PTEST";
11312   case X86ISD::TESTP:              return "X86ISD::TESTP";
11313   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11314   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11315   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11316   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11317   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11318   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11319   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11320   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11321   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11322   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11323   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11324   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11325   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11326   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11327   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11328   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11329   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11330   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11331   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11332   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11333   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11334   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11335   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11336   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11337   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11338   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11339   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11340   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11341   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11342   case X86ISD::SAHF:               return "X86ISD::SAHF";
11343   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11344   case X86ISD::FMADD:              return "X86ISD::FMADD";
11345   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11346   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11347   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11348   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11349   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11350   }
11351 }
11352
11353 // isLegalAddressingMode - Return true if the addressing mode represented
11354 // by AM is legal for this target, for a load/store of the specified type.
11355 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11356                                               Type *Ty) const {
11357   // X86 supports extremely general addressing modes.
11358   CodeModel::Model M = getTargetMachine().getCodeModel();
11359   Reloc::Model R = getTargetMachine().getRelocationModel();
11360
11361   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11362   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11363     return false;
11364
11365   if (AM.BaseGV) {
11366     unsigned GVFlags =
11367       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11368
11369     // If a reference to this global requires an extra load, we can't fold it.
11370     if (isGlobalStubReference(GVFlags))
11371       return false;
11372
11373     // If BaseGV requires a register for the PIC base, we cannot also have a
11374     // BaseReg specified.
11375     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11376       return false;
11377
11378     // If lower 4G is not available, then we must use rip-relative addressing.
11379     if ((M != CodeModel::Small || R != Reloc::Static) &&
11380         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11381       return false;
11382   }
11383
11384   switch (AM.Scale) {
11385   case 0:
11386   case 1:
11387   case 2:
11388   case 4:
11389   case 8:
11390     // These scales always work.
11391     break;
11392   case 3:
11393   case 5:
11394   case 9:
11395     // These scales are formed with basereg+scalereg.  Only accept if there is
11396     // no basereg yet.
11397     if (AM.HasBaseReg)
11398       return false;
11399     break;
11400   default:  // Other stuff never works.
11401     return false;
11402   }
11403
11404   return true;
11405 }
11406
11407
11408 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11409   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11410     return false;
11411   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11412   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11413   if (NumBits1 <= NumBits2)
11414     return false;
11415   return true;
11416 }
11417
11418 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11419   return Imm == (int32_t)Imm;
11420 }
11421
11422 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11423   // Can also use sub to handle negated immediates.
11424   return Imm == (int32_t)Imm;
11425 }
11426
11427 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11428   if (!VT1.isInteger() || !VT2.isInteger())
11429     return false;
11430   unsigned NumBits1 = VT1.getSizeInBits();
11431   unsigned NumBits2 = VT2.getSizeInBits();
11432   if (NumBits1 <= NumBits2)
11433     return false;
11434   return true;
11435 }
11436
11437 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11438   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11439   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11440 }
11441
11442 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11443   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11444   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11445 }
11446
11447 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11448   // i16 instructions are longer (0x66 prefix) and potentially slower.
11449   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11450 }
11451
11452 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11453 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11454 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11455 /// are assumed to be legal.
11456 bool
11457 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11458                                       EVT VT) const {
11459   // Very little shuffling can be done for 64-bit vectors right now.
11460   if (VT.getSizeInBits() == 64)
11461     return false;
11462
11463   // FIXME: pshufb, blends, shifts.
11464   return (VT.getVectorNumElements() == 2 ||
11465           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11466           isMOVLMask(M, VT) ||
11467           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11468           isPSHUFDMask(M, VT) ||
11469           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11470           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11471           isPALIGNRMask(M, VT, Subtarget) ||
11472           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11473           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11474           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11475           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11476 }
11477
11478 bool
11479 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11480                                           EVT VT) const {
11481   unsigned NumElts = VT.getVectorNumElements();
11482   // FIXME: This collection of masks seems suspect.
11483   if (NumElts == 2)
11484     return true;
11485   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11486     return (isMOVLMask(Mask, VT)  ||
11487             isCommutedMOVLMask(Mask, VT, true) ||
11488             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11489             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11490   }
11491   return false;
11492 }
11493
11494 //===----------------------------------------------------------------------===//
11495 //                           X86 Scheduler Hooks
11496 //===----------------------------------------------------------------------===//
11497
11498 // private utility function
11499 MachineBasicBlock *
11500 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11501                                                        MachineBasicBlock *MBB,
11502                                                        unsigned regOpc,
11503                                                        unsigned immOpc,
11504                                                        unsigned LoadOpc,
11505                                                        unsigned CXchgOpc,
11506                                                        unsigned notOpc,
11507                                                        unsigned EAXreg,
11508                                                  const TargetRegisterClass *RC,
11509                                                        bool Invert) const {
11510   // For the atomic bitwise operator, we generate
11511   //   thisMBB:
11512   //   newMBB:
11513   //     ld  t1 = [bitinstr.addr]
11514   //     op  t2 = t1, [bitinstr.val]
11515   //     not t3 = t2  (if Invert)
11516   //     mov EAX = t1
11517   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11518   //     bz  newMBB
11519   //     fallthrough -->nextMBB
11520   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11521   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11522   MachineFunction::iterator MBBIter = MBB;
11523   ++MBBIter;
11524
11525   /// First build the CFG
11526   MachineFunction *F = MBB->getParent();
11527   MachineBasicBlock *thisMBB = MBB;
11528   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11529   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11530   F->insert(MBBIter, newMBB);
11531   F->insert(MBBIter, nextMBB);
11532
11533   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11534   nextMBB->splice(nextMBB->begin(), thisMBB,
11535                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11536                   thisMBB->end());
11537   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11538
11539   // Update thisMBB to fall through to newMBB
11540   thisMBB->addSuccessor(newMBB);
11541
11542   // newMBB jumps to itself and fall through to nextMBB
11543   newMBB->addSuccessor(nextMBB);
11544   newMBB->addSuccessor(newMBB);
11545
11546   // Insert instructions into newMBB based on incoming instruction
11547   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11548          "unexpected number of operands");
11549   DebugLoc dl = bInstr->getDebugLoc();
11550   MachineOperand& destOper = bInstr->getOperand(0);
11551   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11552   int numArgs = bInstr->getNumOperands() - 1;
11553   for (int i=0; i < numArgs; ++i)
11554     argOpers[i] = &bInstr->getOperand(i+1);
11555
11556   // x86 address has 4 operands: base, index, scale, and displacement
11557   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11558   int valArgIndx = lastAddrIndx + 1;
11559
11560   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11561   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11562   for (int i=0; i <= lastAddrIndx; ++i)
11563     (*MIB).addOperand(*argOpers[i]);
11564
11565   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11566   assert((argOpers[valArgIndx]->isReg() ||
11567           argOpers[valArgIndx]->isImm()) &&
11568          "invalid operand");
11569   if (argOpers[valArgIndx]->isReg())
11570     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11571   else
11572     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11573   MIB.addReg(t1);
11574   (*MIB).addOperand(*argOpers[valArgIndx]);
11575
11576   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11577   if (Invert) {
11578     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11579   }
11580   else
11581     t3 = t2;
11582
11583   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11584   MIB.addReg(t1);
11585
11586   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11587   for (int i=0; i <= lastAddrIndx; ++i)
11588     (*MIB).addOperand(*argOpers[i]);
11589   MIB.addReg(t3);
11590   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11591   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11592                     bInstr->memoperands_end());
11593
11594   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11595   MIB.addReg(EAXreg);
11596
11597   // insert branch
11598   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11599
11600   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11601   return nextMBB;
11602 }
11603
11604 // private utility function:  64 bit atomics on 32 bit host.
11605 MachineBasicBlock *
11606 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11607                                                        MachineBasicBlock *MBB,
11608                                                        unsigned regOpcL,
11609                                                        unsigned regOpcH,
11610                                                        unsigned immOpcL,
11611                                                        unsigned immOpcH,
11612                                                        bool Invert) const {
11613   // For the atomic bitwise operator, we generate
11614   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11615   //     ld t1,t2 = [bitinstr.addr]
11616   //   newMBB:
11617   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11618   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11619   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11620   //     neg t7, t8 < t5, t6  (if Invert)
11621   //     mov ECX, EBX <- t5, t6
11622   //     mov EAX, EDX <- t1, t2
11623   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11624   //     mov t3, t4 <- EAX, EDX
11625   //     bz  newMBB
11626   //     result in out1, out2
11627   //     fallthrough -->nextMBB
11628
11629   const TargetRegisterClass *RC = &X86::GR32RegClass;
11630   const unsigned LoadOpc = X86::MOV32rm;
11631   const unsigned NotOpc = X86::NOT32r;
11632   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11633   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11634   MachineFunction::iterator MBBIter = MBB;
11635   ++MBBIter;
11636
11637   /// First build the CFG
11638   MachineFunction *F = MBB->getParent();
11639   MachineBasicBlock *thisMBB = MBB;
11640   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11641   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11642   F->insert(MBBIter, newMBB);
11643   F->insert(MBBIter, nextMBB);
11644
11645   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11646   nextMBB->splice(nextMBB->begin(), thisMBB,
11647                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11648                   thisMBB->end());
11649   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11650
11651   // Update thisMBB to fall through to newMBB
11652   thisMBB->addSuccessor(newMBB);
11653
11654   // newMBB jumps to itself and fall through to nextMBB
11655   newMBB->addSuccessor(nextMBB);
11656   newMBB->addSuccessor(newMBB);
11657
11658   DebugLoc dl = bInstr->getDebugLoc();
11659   // Insert instructions into newMBB based on incoming instruction
11660   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11661   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11662          "unexpected number of operands");
11663   MachineOperand& dest1Oper = bInstr->getOperand(0);
11664   MachineOperand& dest2Oper = bInstr->getOperand(1);
11665   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11666   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11667     argOpers[i] = &bInstr->getOperand(i+2);
11668
11669     // We use some of the operands multiple times, so conservatively just
11670     // clear any kill flags that might be present.
11671     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11672       argOpers[i]->setIsKill(false);
11673   }
11674
11675   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11676   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11677
11678   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11679   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11680   for (int i=0; i <= lastAddrIndx; ++i)
11681     (*MIB).addOperand(*argOpers[i]);
11682   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11683   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11684   // add 4 to displacement.
11685   for (int i=0; i <= lastAddrIndx-2; ++i)
11686     (*MIB).addOperand(*argOpers[i]);
11687   MachineOperand newOp3 = *(argOpers[3]);
11688   if (newOp3.isImm())
11689     newOp3.setImm(newOp3.getImm()+4);
11690   else
11691     newOp3.setOffset(newOp3.getOffset()+4);
11692   (*MIB).addOperand(newOp3);
11693   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11694
11695   // t3/4 are defined later, at the bottom of the loop
11696   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11697   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11698   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11699     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11700   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11701     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11702
11703   // The subsequent operations should be using the destination registers of
11704   // the PHI instructions.
11705   t1 = dest1Oper.getReg();
11706   t2 = dest2Oper.getReg();
11707
11708   int valArgIndx = lastAddrIndx + 1;
11709   assert((argOpers[valArgIndx]->isReg() ||
11710           argOpers[valArgIndx]->isImm()) &&
11711          "invalid operand");
11712   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11713   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11714   if (argOpers[valArgIndx]->isReg())
11715     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11716   else
11717     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11718   if (regOpcL != X86::MOV32rr)
11719     MIB.addReg(t1);
11720   (*MIB).addOperand(*argOpers[valArgIndx]);
11721   assert(argOpers[valArgIndx + 1]->isReg() ==
11722          argOpers[valArgIndx]->isReg());
11723   assert(argOpers[valArgIndx + 1]->isImm() ==
11724          argOpers[valArgIndx]->isImm());
11725   if (argOpers[valArgIndx + 1]->isReg())
11726     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11727   else
11728     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11729   if (regOpcH != X86::MOV32rr)
11730     MIB.addReg(t2);
11731   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11732
11733   unsigned t7, t8;
11734   if (Invert) {
11735     t7 = F->getRegInfo().createVirtualRegister(RC);
11736     t8 = F->getRegInfo().createVirtualRegister(RC);
11737     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11738     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11739   } else {
11740     t7 = t5;
11741     t8 = t6;
11742   }
11743
11744   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11745   MIB.addReg(t1);
11746   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11747   MIB.addReg(t2);
11748
11749   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11750   MIB.addReg(t7);
11751   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11752   MIB.addReg(t8);
11753
11754   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11755   for (int i=0; i <= lastAddrIndx; ++i)
11756     (*MIB).addOperand(*argOpers[i]);
11757
11758   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11759   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11760                     bInstr->memoperands_end());
11761
11762   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11763   MIB.addReg(X86::EAX);
11764   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11765   MIB.addReg(X86::EDX);
11766
11767   // insert branch
11768   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11769
11770   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11771   return nextMBB;
11772 }
11773
11774 // private utility function
11775 MachineBasicBlock *
11776 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11777                                                       MachineBasicBlock *MBB,
11778                                                       unsigned cmovOpc) const {
11779   // For the atomic min/max operator, we generate
11780   //   thisMBB:
11781   //   newMBB:
11782   //     ld t1 = [min/max.addr]
11783   //     mov t2 = [min/max.val]
11784   //     cmp  t1, t2
11785   //     cmov[cond] t2 = t1
11786   //     mov EAX = t1
11787   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11788   //     bz   newMBB
11789   //     fallthrough -->nextMBB
11790   //
11791   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11792   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11793   MachineFunction::iterator MBBIter = MBB;
11794   ++MBBIter;
11795
11796   /// First build the CFG
11797   MachineFunction *F = MBB->getParent();
11798   MachineBasicBlock *thisMBB = MBB;
11799   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11800   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11801   F->insert(MBBIter, newMBB);
11802   F->insert(MBBIter, nextMBB);
11803
11804   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11805   nextMBB->splice(nextMBB->begin(), thisMBB,
11806                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11807                   thisMBB->end());
11808   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11809
11810   // Update thisMBB to fall through to newMBB
11811   thisMBB->addSuccessor(newMBB);
11812
11813   // newMBB jumps to newMBB and fall through to nextMBB
11814   newMBB->addSuccessor(nextMBB);
11815   newMBB->addSuccessor(newMBB);
11816
11817   DebugLoc dl = mInstr->getDebugLoc();
11818   // Insert instructions into newMBB based on incoming instruction
11819   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11820          "unexpected number of operands");
11821   MachineOperand& destOper = mInstr->getOperand(0);
11822   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11823   int numArgs = mInstr->getNumOperands() - 1;
11824   for (int i=0; i < numArgs; ++i)
11825     argOpers[i] = &mInstr->getOperand(i+1);
11826
11827   // x86 address has 4 operands: base, index, scale, and displacement
11828   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11829   int valArgIndx = lastAddrIndx + 1;
11830
11831   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11832   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11833   for (int i=0; i <= lastAddrIndx; ++i)
11834     (*MIB).addOperand(*argOpers[i]);
11835
11836   // We only support register and immediate values
11837   assert((argOpers[valArgIndx]->isReg() ||
11838           argOpers[valArgIndx]->isImm()) &&
11839          "invalid operand");
11840
11841   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11842   if (argOpers[valArgIndx]->isReg())
11843     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11844   else
11845     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11846   (*MIB).addOperand(*argOpers[valArgIndx]);
11847
11848   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11849   MIB.addReg(t1);
11850
11851   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11852   MIB.addReg(t1);
11853   MIB.addReg(t2);
11854
11855   // Generate movc
11856   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11857   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11858   MIB.addReg(t2);
11859   MIB.addReg(t1);
11860
11861   // Cmp and exchange if none has modified the memory location
11862   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11863   for (int i=0; i <= lastAddrIndx; ++i)
11864     (*MIB).addOperand(*argOpers[i]);
11865   MIB.addReg(t3);
11866   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11867   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11868                     mInstr->memoperands_end());
11869
11870   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11871   MIB.addReg(X86::EAX);
11872
11873   // insert branch
11874   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11875
11876   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11877   return nextMBB;
11878 }
11879
11880 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11881 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11882 // in the .td file.
11883 MachineBasicBlock *
11884 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11885                             unsigned numArgs, bool memArg) const {
11886   assert(Subtarget->hasSSE42() &&
11887          "Target must have SSE4.2 or AVX features enabled");
11888
11889   DebugLoc dl = MI->getDebugLoc();
11890   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11891   unsigned Opc;
11892   if (!Subtarget->hasAVX()) {
11893     if (memArg)
11894       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11895     else
11896       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11897   } else {
11898     if (memArg)
11899       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11900     else
11901       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11902   }
11903
11904   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11905   for (unsigned i = 0; i < numArgs; ++i) {
11906     MachineOperand &Op = MI->getOperand(i+1);
11907     if (!(Op.isReg() && Op.isImplicit()))
11908       MIB.addOperand(Op);
11909   }
11910   BuildMI(*BB, MI, dl,
11911     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
11912     .addReg(X86::XMM0);
11913
11914   MI->eraseFromParent();
11915   return BB;
11916 }
11917
11918 MachineBasicBlock *
11919 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11920   DebugLoc dl = MI->getDebugLoc();
11921   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11922
11923   // Address into RAX/EAX, other two args into ECX, EDX.
11924   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11925   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11926   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11927   for (int i = 0; i < X86::AddrNumOperands; ++i)
11928     MIB.addOperand(MI->getOperand(i));
11929
11930   unsigned ValOps = X86::AddrNumOperands;
11931   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11932     .addReg(MI->getOperand(ValOps).getReg());
11933   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11934     .addReg(MI->getOperand(ValOps+1).getReg());
11935
11936   // The instruction doesn't actually take any operands though.
11937   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11938
11939   MI->eraseFromParent(); // The pseudo is gone now.
11940   return BB;
11941 }
11942
11943 MachineBasicBlock *
11944 X86TargetLowering::EmitVAARG64WithCustomInserter(
11945                    MachineInstr *MI,
11946                    MachineBasicBlock *MBB) const {
11947   // Emit va_arg instruction on X86-64.
11948
11949   // Operands to this pseudo-instruction:
11950   // 0  ) Output        : destination address (reg)
11951   // 1-5) Input         : va_list address (addr, i64mem)
11952   // 6  ) ArgSize       : Size (in bytes) of vararg type
11953   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11954   // 8  ) Align         : Alignment of type
11955   // 9  ) EFLAGS (implicit-def)
11956
11957   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11958   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11959
11960   unsigned DestReg = MI->getOperand(0).getReg();
11961   MachineOperand &Base = MI->getOperand(1);
11962   MachineOperand &Scale = MI->getOperand(2);
11963   MachineOperand &Index = MI->getOperand(3);
11964   MachineOperand &Disp = MI->getOperand(4);
11965   MachineOperand &Segment = MI->getOperand(5);
11966   unsigned ArgSize = MI->getOperand(6).getImm();
11967   unsigned ArgMode = MI->getOperand(7).getImm();
11968   unsigned Align = MI->getOperand(8).getImm();
11969
11970   // Memory Reference
11971   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11972   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11973   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11974
11975   // Machine Information
11976   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11977   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11978   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11979   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11980   DebugLoc DL = MI->getDebugLoc();
11981
11982   // struct va_list {
11983   //   i32   gp_offset
11984   //   i32   fp_offset
11985   //   i64   overflow_area (address)
11986   //   i64   reg_save_area (address)
11987   // }
11988   // sizeof(va_list) = 24
11989   // alignment(va_list) = 8
11990
11991   unsigned TotalNumIntRegs = 6;
11992   unsigned TotalNumXMMRegs = 8;
11993   bool UseGPOffset = (ArgMode == 1);
11994   bool UseFPOffset = (ArgMode == 2);
11995   unsigned MaxOffset = TotalNumIntRegs * 8 +
11996                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11997
11998   /* Align ArgSize to a multiple of 8 */
11999   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12000   bool NeedsAlign = (Align > 8);
12001
12002   MachineBasicBlock *thisMBB = MBB;
12003   MachineBasicBlock *overflowMBB;
12004   MachineBasicBlock *offsetMBB;
12005   MachineBasicBlock *endMBB;
12006
12007   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12008   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12009   unsigned OffsetReg = 0;
12010
12011   if (!UseGPOffset && !UseFPOffset) {
12012     // If we only pull from the overflow region, we don't create a branch.
12013     // We don't need to alter control flow.
12014     OffsetDestReg = 0; // unused
12015     OverflowDestReg = DestReg;
12016
12017     offsetMBB = NULL;
12018     overflowMBB = thisMBB;
12019     endMBB = thisMBB;
12020   } else {
12021     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12022     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12023     // If not, pull from overflow_area. (branch to overflowMBB)
12024     //
12025     //       thisMBB
12026     //         |     .
12027     //         |        .
12028     //     offsetMBB   overflowMBB
12029     //         |        .
12030     //         |     .
12031     //        endMBB
12032
12033     // Registers for the PHI in endMBB
12034     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12035     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12036
12037     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12038     MachineFunction *MF = MBB->getParent();
12039     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12040     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12041     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12042
12043     MachineFunction::iterator MBBIter = MBB;
12044     ++MBBIter;
12045
12046     // Insert the new basic blocks
12047     MF->insert(MBBIter, offsetMBB);
12048     MF->insert(MBBIter, overflowMBB);
12049     MF->insert(MBBIter, endMBB);
12050
12051     // Transfer the remainder of MBB and its successor edges to endMBB.
12052     endMBB->splice(endMBB->begin(), thisMBB,
12053                     llvm::next(MachineBasicBlock::iterator(MI)),
12054                     thisMBB->end());
12055     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12056
12057     // Make offsetMBB and overflowMBB successors of thisMBB
12058     thisMBB->addSuccessor(offsetMBB);
12059     thisMBB->addSuccessor(overflowMBB);
12060
12061     // endMBB is a successor of both offsetMBB and overflowMBB
12062     offsetMBB->addSuccessor(endMBB);
12063     overflowMBB->addSuccessor(endMBB);
12064
12065     // Load the offset value into a register
12066     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12067     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12068       .addOperand(Base)
12069       .addOperand(Scale)
12070       .addOperand(Index)
12071       .addDisp(Disp, UseFPOffset ? 4 : 0)
12072       .addOperand(Segment)
12073       .setMemRefs(MMOBegin, MMOEnd);
12074
12075     // Check if there is enough room left to pull this argument.
12076     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12077       .addReg(OffsetReg)
12078       .addImm(MaxOffset + 8 - ArgSizeA8);
12079
12080     // Branch to "overflowMBB" if offset >= max
12081     // Fall through to "offsetMBB" otherwise
12082     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12083       .addMBB(overflowMBB);
12084   }
12085
12086   // In offsetMBB, emit code to use the reg_save_area.
12087   if (offsetMBB) {
12088     assert(OffsetReg != 0);
12089
12090     // Read the reg_save_area address.
12091     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12092     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12093       .addOperand(Base)
12094       .addOperand(Scale)
12095       .addOperand(Index)
12096       .addDisp(Disp, 16)
12097       .addOperand(Segment)
12098       .setMemRefs(MMOBegin, MMOEnd);
12099
12100     // Zero-extend the offset
12101     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12102       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12103         .addImm(0)
12104         .addReg(OffsetReg)
12105         .addImm(X86::sub_32bit);
12106
12107     // Add the offset to the reg_save_area to get the final address.
12108     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12109       .addReg(OffsetReg64)
12110       .addReg(RegSaveReg);
12111
12112     // Compute the offset for the next argument
12113     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12114     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12115       .addReg(OffsetReg)
12116       .addImm(UseFPOffset ? 16 : 8);
12117
12118     // Store it back into the va_list.
12119     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12120       .addOperand(Base)
12121       .addOperand(Scale)
12122       .addOperand(Index)
12123       .addDisp(Disp, UseFPOffset ? 4 : 0)
12124       .addOperand(Segment)
12125       .addReg(NextOffsetReg)
12126       .setMemRefs(MMOBegin, MMOEnd);
12127
12128     // Jump to endMBB
12129     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12130       .addMBB(endMBB);
12131   }
12132
12133   //
12134   // Emit code to use overflow area
12135   //
12136
12137   // Load the overflow_area address into a register.
12138   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12139   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12140     .addOperand(Base)
12141     .addOperand(Scale)
12142     .addOperand(Index)
12143     .addDisp(Disp, 8)
12144     .addOperand(Segment)
12145     .setMemRefs(MMOBegin, MMOEnd);
12146
12147   // If we need to align it, do so. Otherwise, just copy the address
12148   // to OverflowDestReg.
12149   if (NeedsAlign) {
12150     // Align the overflow address
12151     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12152     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12153
12154     // aligned_addr = (addr + (align-1)) & ~(align-1)
12155     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12156       .addReg(OverflowAddrReg)
12157       .addImm(Align-1);
12158
12159     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12160       .addReg(TmpReg)
12161       .addImm(~(uint64_t)(Align-1));
12162   } else {
12163     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12164       .addReg(OverflowAddrReg);
12165   }
12166
12167   // Compute the next overflow address after this argument.
12168   // (the overflow address should be kept 8-byte aligned)
12169   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12170   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12171     .addReg(OverflowDestReg)
12172     .addImm(ArgSizeA8);
12173
12174   // Store the new overflow address.
12175   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12176     .addOperand(Base)
12177     .addOperand(Scale)
12178     .addOperand(Index)
12179     .addDisp(Disp, 8)
12180     .addOperand(Segment)
12181     .addReg(NextAddrReg)
12182     .setMemRefs(MMOBegin, MMOEnd);
12183
12184   // If we branched, emit the PHI to the front of endMBB.
12185   if (offsetMBB) {
12186     BuildMI(*endMBB, endMBB->begin(), DL,
12187             TII->get(X86::PHI), DestReg)
12188       .addReg(OffsetDestReg).addMBB(offsetMBB)
12189       .addReg(OverflowDestReg).addMBB(overflowMBB);
12190   }
12191
12192   // Erase the pseudo instruction
12193   MI->eraseFromParent();
12194
12195   return endMBB;
12196 }
12197
12198 MachineBasicBlock *
12199 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12200                                                  MachineInstr *MI,
12201                                                  MachineBasicBlock *MBB) const {
12202   // Emit code to save XMM registers to the stack. The ABI says that the
12203   // number of registers to save is given in %al, so it's theoretically
12204   // possible to do an indirect jump trick to avoid saving all of them,
12205   // however this code takes a simpler approach and just executes all
12206   // of the stores if %al is non-zero. It's less code, and it's probably
12207   // easier on the hardware branch predictor, and stores aren't all that
12208   // expensive anyway.
12209
12210   // Create the new basic blocks. One block contains all the XMM stores,
12211   // and one block is the final destination regardless of whether any
12212   // stores were performed.
12213   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12214   MachineFunction *F = MBB->getParent();
12215   MachineFunction::iterator MBBIter = MBB;
12216   ++MBBIter;
12217   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12218   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12219   F->insert(MBBIter, XMMSaveMBB);
12220   F->insert(MBBIter, EndMBB);
12221
12222   // Transfer the remainder of MBB and its successor edges to EndMBB.
12223   EndMBB->splice(EndMBB->begin(), MBB,
12224                  llvm::next(MachineBasicBlock::iterator(MI)),
12225                  MBB->end());
12226   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12227
12228   // The original block will now fall through to the XMM save block.
12229   MBB->addSuccessor(XMMSaveMBB);
12230   // The XMMSaveMBB will fall through to the end block.
12231   XMMSaveMBB->addSuccessor(EndMBB);
12232
12233   // Now add the instructions.
12234   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12235   DebugLoc DL = MI->getDebugLoc();
12236
12237   unsigned CountReg = MI->getOperand(0).getReg();
12238   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12239   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12240
12241   if (!Subtarget->isTargetWin64()) {
12242     // If %al is 0, branch around the XMM save block.
12243     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12244     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12245     MBB->addSuccessor(EndMBB);
12246   }
12247
12248   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12249   // In the XMM save block, save all the XMM argument registers.
12250   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12251     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12252     MachineMemOperand *MMO =
12253       F->getMachineMemOperand(
12254           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12255         MachineMemOperand::MOStore,
12256         /*Size=*/16, /*Align=*/16);
12257     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12258       .addFrameIndex(RegSaveFrameIndex)
12259       .addImm(/*Scale=*/1)
12260       .addReg(/*IndexReg=*/0)
12261       .addImm(/*Disp=*/Offset)
12262       .addReg(/*Segment=*/0)
12263       .addReg(MI->getOperand(i).getReg())
12264       .addMemOperand(MMO);
12265   }
12266
12267   MI->eraseFromParent();   // The pseudo instruction is gone now.
12268
12269   return EndMBB;
12270 }
12271
12272 // The EFLAGS operand of SelectItr might be missing a kill marker
12273 // because there were multiple uses of EFLAGS, and ISel didn't know
12274 // which to mark. Figure out whether SelectItr should have had a
12275 // kill marker, and set it if it should. Returns the correct kill
12276 // marker value.
12277 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12278                                      MachineBasicBlock* BB,
12279                                      const TargetRegisterInfo* TRI) {
12280   // Scan forward through BB for a use/def of EFLAGS.
12281   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12282   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12283     const MachineInstr& mi = *miI;
12284     if (mi.readsRegister(X86::EFLAGS))
12285       return false;
12286     if (mi.definesRegister(X86::EFLAGS))
12287       break; // Should have kill-flag - update below.
12288   }
12289
12290   // If we hit the end of the block, check whether EFLAGS is live into a
12291   // successor.
12292   if (miI == BB->end()) {
12293     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12294                                           sEnd = BB->succ_end();
12295          sItr != sEnd; ++sItr) {
12296       MachineBasicBlock* succ = *sItr;
12297       if (succ->isLiveIn(X86::EFLAGS))
12298         return false;
12299     }
12300   }
12301
12302   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12303   // out. SelectMI should have a kill flag on EFLAGS.
12304   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12305   return true;
12306 }
12307
12308 MachineBasicBlock *
12309 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12310                                      MachineBasicBlock *BB) const {
12311   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12312   DebugLoc DL = MI->getDebugLoc();
12313
12314   // To "insert" a SELECT_CC instruction, we actually have to insert the
12315   // diamond control-flow pattern.  The incoming instruction knows the
12316   // destination vreg to set, the condition code register to branch on, the
12317   // true/false values to select between, and a branch opcode to use.
12318   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12319   MachineFunction::iterator It = BB;
12320   ++It;
12321
12322   //  thisMBB:
12323   //  ...
12324   //   TrueVal = ...
12325   //   cmpTY ccX, r1, r2
12326   //   bCC copy1MBB
12327   //   fallthrough --> copy0MBB
12328   MachineBasicBlock *thisMBB = BB;
12329   MachineFunction *F = BB->getParent();
12330   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12331   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12332   F->insert(It, copy0MBB);
12333   F->insert(It, sinkMBB);
12334
12335   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12336   // live into the sink and copy blocks.
12337   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12338   if (!MI->killsRegister(X86::EFLAGS) &&
12339       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12340     copy0MBB->addLiveIn(X86::EFLAGS);
12341     sinkMBB->addLiveIn(X86::EFLAGS);
12342   }
12343
12344   // Transfer the remainder of BB and its successor edges to sinkMBB.
12345   sinkMBB->splice(sinkMBB->begin(), BB,
12346                   llvm::next(MachineBasicBlock::iterator(MI)),
12347                   BB->end());
12348   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12349
12350   // Add the true and fallthrough blocks as its successors.
12351   BB->addSuccessor(copy0MBB);
12352   BB->addSuccessor(sinkMBB);
12353
12354   // Create the conditional branch instruction.
12355   unsigned Opc =
12356     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12357   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12358
12359   //  copy0MBB:
12360   //   %FalseValue = ...
12361   //   # fallthrough to sinkMBB
12362   copy0MBB->addSuccessor(sinkMBB);
12363
12364   //  sinkMBB:
12365   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12366   //  ...
12367   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12368           TII->get(X86::PHI), MI->getOperand(0).getReg())
12369     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12370     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12371
12372   MI->eraseFromParent();   // The pseudo instruction is gone now.
12373   return sinkMBB;
12374 }
12375
12376 MachineBasicBlock *
12377 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12378                                         bool Is64Bit) const {
12379   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12380   DebugLoc DL = MI->getDebugLoc();
12381   MachineFunction *MF = BB->getParent();
12382   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12383
12384   assert(getTargetMachine().Options.EnableSegmentedStacks);
12385
12386   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12387   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12388
12389   // BB:
12390   //  ... [Till the alloca]
12391   // If stacklet is not large enough, jump to mallocMBB
12392   //
12393   // bumpMBB:
12394   //  Allocate by subtracting from RSP
12395   //  Jump to continueMBB
12396   //
12397   // mallocMBB:
12398   //  Allocate by call to runtime
12399   //
12400   // continueMBB:
12401   //  ...
12402   //  [rest of original BB]
12403   //
12404
12405   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12406   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12407   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12408
12409   MachineRegisterInfo &MRI = MF->getRegInfo();
12410   const TargetRegisterClass *AddrRegClass =
12411     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12412
12413   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12414     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12415     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12416     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12417     sizeVReg = MI->getOperand(1).getReg(),
12418     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12419
12420   MachineFunction::iterator MBBIter = BB;
12421   ++MBBIter;
12422
12423   MF->insert(MBBIter, bumpMBB);
12424   MF->insert(MBBIter, mallocMBB);
12425   MF->insert(MBBIter, continueMBB);
12426
12427   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12428                       (MachineBasicBlock::iterator(MI)), BB->end());
12429   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12430
12431   // Add code to the main basic block to check if the stack limit has been hit,
12432   // and if so, jump to mallocMBB otherwise to bumpMBB.
12433   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12434   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12435     .addReg(tmpSPVReg).addReg(sizeVReg);
12436   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12437     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12438     .addReg(SPLimitVReg);
12439   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12440
12441   // bumpMBB simply decreases the stack pointer, since we know the current
12442   // stacklet has enough space.
12443   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12444     .addReg(SPLimitVReg);
12445   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12446     .addReg(SPLimitVReg);
12447   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12448
12449   // Calls into a routine in libgcc to allocate more space from the heap.
12450   const uint32_t *RegMask =
12451     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12452   if (Is64Bit) {
12453     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12454       .addReg(sizeVReg);
12455     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12456       .addExternalSymbol("__morestack_allocate_stack_space")
12457       .addRegMask(RegMask)
12458       .addReg(X86::RDI, RegState::Implicit)
12459       .addReg(X86::RAX, RegState::ImplicitDefine);
12460   } else {
12461     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12462       .addImm(12);
12463     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12464     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12465       .addExternalSymbol("__morestack_allocate_stack_space")
12466       .addRegMask(RegMask)
12467       .addReg(X86::EAX, RegState::ImplicitDefine);
12468   }
12469
12470   if (!Is64Bit)
12471     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12472       .addImm(16);
12473
12474   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12475     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12476   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12477
12478   // Set up the CFG correctly.
12479   BB->addSuccessor(bumpMBB);
12480   BB->addSuccessor(mallocMBB);
12481   mallocMBB->addSuccessor(continueMBB);
12482   bumpMBB->addSuccessor(continueMBB);
12483
12484   // Take care of the PHI nodes.
12485   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12486           MI->getOperand(0).getReg())
12487     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12488     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12489
12490   // Delete the original pseudo instruction.
12491   MI->eraseFromParent();
12492
12493   // And we're done.
12494   return continueMBB;
12495 }
12496
12497 MachineBasicBlock *
12498 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12499                                           MachineBasicBlock *BB) const {
12500   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12501   DebugLoc DL = MI->getDebugLoc();
12502
12503   assert(!Subtarget->isTargetEnvMacho());
12504
12505   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12506   // non-trivial part is impdef of ESP.
12507
12508   if (Subtarget->isTargetWin64()) {
12509     if (Subtarget->isTargetCygMing()) {
12510       // ___chkstk(Mingw64):
12511       // Clobbers R10, R11, RAX and EFLAGS.
12512       // Updates RSP.
12513       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12514         .addExternalSymbol("___chkstk")
12515         .addReg(X86::RAX, RegState::Implicit)
12516         .addReg(X86::RSP, RegState::Implicit)
12517         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12518         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12519         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12520     } else {
12521       // __chkstk(MSVCRT): does not update stack pointer.
12522       // Clobbers R10, R11 and EFLAGS.
12523       // FIXME: RAX(allocated size) might be reused and not killed.
12524       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12525         .addExternalSymbol("__chkstk")
12526         .addReg(X86::RAX, RegState::Implicit)
12527         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12528       // RAX has the offset to subtracted from RSP.
12529       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12530         .addReg(X86::RSP)
12531         .addReg(X86::RAX);
12532     }
12533   } else {
12534     const char *StackProbeSymbol =
12535       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12536
12537     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12538       .addExternalSymbol(StackProbeSymbol)
12539       .addReg(X86::EAX, RegState::Implicit)
12540       .addReg(X86::ESP, RegState::Implicit)
12541       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12542       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12543       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12544   }
12545
12546   MI->eraseFromParent();   // The pseudo instruction is gone now.
12547   return BB;
12548 }
12549
12550 MachineBasicBlock *
12551 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12552                                       MachineBasicBlock *BB) const {
12553   // This is pretty easy.  We're taking the value that we received from
12554   // our load from the relocation, sticking it in either RDI (x86-64)
12555   // or EAX and doing an indirect call.  The return value will then
12556   // be in the normal return register.
12557   const X86InstrInfo *TII
12558     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12559   DebugLoc DL = MI->getDebugLoc();
12560   MachineFunction *F = BB->getParent();
12561
12562   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12563   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12564
12565   // Get a register mask for the lowered call.
12566   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12567   // proper register mask.
12568   const uint32_t *RegMask =
12569     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12570   if (Subtarget->is64Bit()) {
12571     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12572                                       TII->get(X86::MOV64rm), X86::RDI)
12573     .addReg(X86::RIP)
12574     .addImm(0).addReg(0)
12575     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12576                       MI->getOperand(3).getTargetFlags())
12577     .addReg(0);
12578     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12579     addDirectMem(MIB, X86::RDI);
12580     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12581   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12582     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12583                                       TII->get(X86::MOV32rm), X86::EAX)
12584     .addReg(0)
12585     .addImm(0).addReg(0)
12586     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12587                       MI->getOperand(3).getTargetFlags())
12588     .addReg(0);
12589     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12590     addDirectMem(MIB, X86::EAX);
12591     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12592   } else {
12593     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12594                                       TII->get(X86::MOV32rm), X86::EAX)
12595     .addReg(TII->getGlobalBaseReg(F))
12596     .addImm(0).addReg(0)
12597     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12598                       MI->getOperand(3).getTargetFlags())
12599     .addReg(0);
12600     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12601     addDirectMem(MIB, X86::EAX);
12602     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12603   }
12604
12605   MI->eraseFromParent(); // The pseudo instruction is gone now.
12606   return BB;
12607 }
12608
12609 MachineBasicBlock *
12610 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12611                                                MachineBasicBlock *BB) const {
12612   switch (MI->getOpcode()) {
12613   default: llvm_unreachable("Unexpected instr type to insert");
12614   case X86::TAILJMPd64:
12615   case X86::TAILJMPr64:
12616   case X86::TAILJMPm64:
12617     llvm_unreachable("TAILJMP64 would not be touched here.");
12618   case X86::TCRETURNdi64:
12619   case X86::TCRETURNri64:
12620   case X86::TCRETURNmi64:
12621     return BB;
12622   case X86::WIN_ALLOCA:
12623     return EmitLoweredWinAlloca(MI, BB);
12624   case X86::SEG_ALLOCA_32:
12625     return EmitLoweredSegAlloca(MI, BB, false);
12626   case X86::SEG_ALLOCA_64:
12627     return EmitLoweredSegAlloca(MI, BB, true);
12628   case X86::TLSCall_32:
12629   case X86::TLSCall_64:
12630     return EmitLoweredTLSCall(MI, BB);
12631   case X86::CMOV_GR8:
12632   case X86::CMOV_FR32:
12633   case X86::CMOV_FR64:
12634   case X86::CMOV_V4F32:
12635   case X86::CMOV_V2F64:
12636   case X86::CMOV_V2I64:
12637   case X86::CMOV_V8F32:
12638   case X86::CMOV_V4F64:
12639   case X86::CMOV_V4I64:
12640   case X86::CMOV_GR16:
12641   case X86::CMOV_GR32:
12642   case X86::CMOV_RFP32:
12643   case X86::CMOV_RFP64:
12644   case X86::CMOV_RFP80:
12645     return EmitLoweredSelect(MI, BB);
12646
12647   case X86::FP32_TO_INT16_IN_MEM:
12648   case X86::FP32_TO_INT32_IN_MEM:
12649   case X86::FP32_TO_INT64_IN_MEM:
12650   case X86::FP64_TO_INT16_IN_MEM:
12651   case X86::FP64_TO_INT32_IN_MEM:
12652   case X86::FP64_TO_INT64_IN_MEM:
12653   case X86::FP80_TO_INT16_IN_MEM:
12654   case X86::FP80_TO_INT32_IN_MEM:
12655   case X86::FP80_TO_INT64_IN_MEM: {
12656     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12657     DebugLoc DL = MI->getDebugLoc();
12658
12659     // Change the floating point control register to use "round towards zero"
12660     // mode when truncating to an integer value.
12661     MachineFunction *F = BB->getParent();
12662     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12663     addFrameReference(BuildMI(*BB, MI, DL,
12664                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12665
12666     // Load the old value of the high byte of the control word...
12667     unsigned OldCW =
12668       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12669     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12670                       CWFrameIdx);
12671
12672     // Set the high part to be round to zero...
12673     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12674       .addImm(0xC7F);
12675
12676     // Reload the modified control word now...
12677     addFrameReference(BuildMI(*BB, MI, DL,
12678                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12679
12680     // Restore the memory image of control word to original value
12681     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12682       .addReg(OldCW);
12683
12684     // Get the X86 opcode to use.
12685     unsigned Opc;
12686     switch (MI->getOpcode()) {
12687     default: llvm_unreachable("illegal opcode!");
12688     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12689     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12690     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12691     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12692     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12693     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12694     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12695     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12696     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12697     }
12698
12699     X86AddressMode AM;
12700     MachineOperand &Op = MI->getOperand(0);
12701     if (Op.isReg()) {
12702       AM.BaseType = X86AddressMode::RegBase;
12703       AM.Base.Reg = Op.getReg();
12704     } else {
12705       AM.BaseType = X86AddressMode::FrameIndexBase;
12706       AM.Base.FrameIndex = Op.getIndex();
12707     }
12708     Op = MI->getOperand(1);
12709     if (Op.isImm())
12710       AM.Scale = Op.getImm();
12711     Op = MI->getOperand(2);
12712     if (Op.isImm())
12713       AM.IndexReg = Op.getImm();
12714     Op = MI->getOperand(3);
12715     if (Op.isGlobal()) {
12716       AM.GV = Op.getGlobal();
12717     } else {
12718       AM.Disp = Op.getImm();
12719     }
12720     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12721                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12722
12723     // Reload the original control word now.
12724     addFrameReference(BuildMI(*BB, MI, DL,
12725                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12726
12727     MI->eraseFromParent();   // The pseudo instruction is gone now.
12728     return BB;
12729   }
12730     // String/text processing lowering.
12731   case X86::PCMPISTRM128REG:
12732   case X86::VPCMPISTRM128REG:
12733     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12734   case X86::PCMPISTRM128MEM:
12735   case X86::VPCMPISTRM128MEM:
12736     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12737   case X86::PCMPESTRM128REG:
12738   case X86::VPCMPESTRM128REG:
12739     return EmitPCMP(MI, BB, 5, false /* in mem */);
12740   case X86::PCMPESTRM128MEM:
12741   case X86::VPCMPESTRM128MEM:
12742     return EmitPCMP(MI, BB, 5, true /* in mem */);
12743
12744     // Thread synchronization.
12745   case X86::MONITOR:
12746     return EmitMonitor(MI, BB);
12747
12748     // Atomic Lowering.
12749   case X86::ATOMAND32:
12750     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12751                                                X86::AND32ri, X86::MOV32rm,
12752                                                X86::LCMPXCHG32,
12753                                                X86::NOT32r, X86::EAX,
12754                                                &X86::GR32RegClass);
12755   case X86::ATOMOR32:
12756     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12757                                                X86::OR32ri, X86::MOV32rm,
12758                                                X86::LCMPXCHG32,
12759                                                X86::NOT32r, X86::EAX,
12760                                                &X86::GR32RegClass);
12761   case X86::ATOMXOR32:
12762     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12763                                                X86::XOR32ri, X86::MOV32rm,
12764                                                X86::LCMPXCHG32,
12765                                                X86::NOT32r, X86::EAX,
12766                                                &X86::GR32RegClass);
12767   case X86::ATOMNAND32:
12768     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12769                                                X86::AND32ri, X86::MOV32rm,
12770                                                X86::LCMPXCHG32,
12771                                                X86::NOT32r, X86::EAX,
12772                                                &X86::GR32RegClass, true);
12773   case X86::ATOMMIN32:
12774     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12775   case X86::ATOMMAX32:
12776     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12777   case X86::ATOMUMIN32:
12778     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12779   case X86::ATOMUMAX32:
12780     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12781
12782   case X86::ATOMAND16:
12783     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12784                                                X86::AND16ri, X86::MOV16rm,
12785                                                X86::LCMPXCHG16,
12786                                                X86::NOT16r, X86::AX,
12787                                                &X86::GR16RegClass);
12788   case X86::ATOMOR16:
12789     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12790                                                X86::OR16ri, X86::MOV16rm,
12791                                                X86::LCMPXCHG16,
12792                                                X86::NOT16r, X86::AX,
12793                                                &X86::GR16RegClass);
12794   case X86::ATOMXOR16:
12795     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12796                                                X86::XOR16ri, X86::MOV16rm,
12797                                                X86::LCMPXCHG16,
12798                                                X86::NOT16r, X86::AX,
12799                                                &X86::GR16RegClass);
12800   case X86::ATOMNAND16:
12801     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12802                                                X86::AND16ri, X86::MOV16rm,
12803                                                X86::LCMPXCHG16,
12804                                                X86::NOT16r, X86::AX,
12805                                                &X86::GR16RegClass, true);
12806   case X86::ATOMMIN16:
12807     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12808   case X86::ATOMMAX16:
12809     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12810   case X86::ATOMUMIN16:
12811     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12812   case X86::ATOMUMAX16:
12813     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12814
12815   case X86::ATOMAND8:
12816     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12817                                                X86::AND8ri, X86::MOV8rm,
12818                                                X86::LCMPXCHG8,
12819                                                X86::NOT8r, X86::AL,
12820                                                &X86::GR8RegClass);
12821   case X86::ATOMOR8:
12822     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12823                                                X86::OR8ri, X86::MOV8rm,
12824                                                X86::LCMPXCHG8,
12825                                                X86::NOT8r, X86::AL,
12826                                                &X86::GR8RegClass);
12827   case X86::ATOMXOR8:
12828     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12829                                                X86::XOR8ri, X86::MOV8rm,
12830                                                X86::LCMPXCHG8,
12831                                                X86::NOT8r, X86::AL,
12832                                                &X86::GR8RegClass);
12833   case X86::ATOMNAND8:
12834     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12835                                                X86::AND8ri, X86::MOV8rm,
12836                                                X86::LCMPXCHG8,
12837                                                X86::NOT8r, X86::AL,
12838                                                &X86::GR8RegClass, true);
12839   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12840   // This group is for 64-bit host.
12841   case X86::ATOMAND64:
12842     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12843                                                X86::AND64ri32, X86::MOV64rm,
12844                                                X86::LCMPXCHG64,
12845                                                X86::NOT64r, X86::RAX,
12846                                                &X86::GR64RegClass);
12847   case X86::ATOMOR64:
12848     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12849                                                X86::OR64ri32, X86::MOV64rm,
12850                                                X86::LCMPXCHG64,
12851                                                X86::NOT64r, X86::RAX,
12852                                                &X86::GR64RegClass);
12853   case X86::ATOMXOR64:
12854     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12855                                                X86::XOR64ri32, X86::MOV64rm,
12856                                                X86::LCMPXCHG64,
12857                                                X86::NOT64r, X86::RAX,
12858                                                &X86::GR64RegClass);
12859   case X86::ATOMNAND64:
12860     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12861                                                X86::AND64ri32, X86::MOV64rm,
12862                                                X86::LCMPXCHG64,
12863                                                X86::NOT64r, X86::RAX,
12864                                                &X86::GR64RegClass, true);
12865   case X86::ATOMMIN64:
12866     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12867   case X86::ATOMMAX64:
12868     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12869   case X86::ATOMUMIN64:
12870     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12871   case X86::ATOMUMAX64:
12872     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12873
12874   // This group does 64-bit operations on a 32-bit host.
12875   case X86::ATOMAND6432:
12876     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12877                                                X86::AND32rr, X86::AND32rr,
12878                                                X86::AND32ri, X86::AND32ri,
12879                                                false);
12880   case X86::ATOMOR6432:
12881     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12882                                                X86::OR32rr, X86::OR32rr,
12883                                                X86::OR32ri, X86::OR32ri,
12884                                                false);
12885   case X86::ATOMXOR6432:
12886     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12887                                                X86::XOR32rr, X86::XOR32rr,
12888                                                X86::XOR32ri, X86::XOR32ri,
12889                                                false);
12890   case X86::ATOMNAND6432:
12891     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12892                                                X86::AND32rr, X86::AND32rr,
12893                                                X86::AND32ri, X86::AND32ri,
12894                                                true);
12895   case X86::ATOMADD6432:
12896     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12897                                                X86::ADD32rr, X86::ADC32rr,
12898                                                X86::ADD32ri, X86::ADC32ri,
12899                                                false);
12900   case X86::ATOMSUB6432:
12901     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12902                                                X86::SUB32rr, X86::SBB32rr,
12903                                                X86::SUB32ri, X86::SBB32ri,
12904                                                false);
12905   case X86::ATOMSWAP6432:
12906     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12907                                                X86::MOV32rr, X86::MOV32rr,
12908                                                X86::MOV32ri, X86::MOV32ri,
12909                                                false);
12910   case X86::VASTART_SAVE_XMM_REGS:
12911     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12912
12913   case X86::VAARG_64:
12914     return EmitVAARG64WithCustomInserter(MI, BB);
12915   }
12916 }
12917
12918 //===----------------------------------------------------------------------===//
12919 //                           X86 Optimization Hooks
12920 //===----------------------------------------------------------------------===//
12921
12922 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12923                                                        APInt &KnownZero,
12924                                                        APInt &KnownOne,
12925                                                        const SelectionDAG &DAG,
12926                                                        unsigned Depth) const {
12927   unsigned BitWidth = KnownZero.getBitWidth();
12928   unsigned Opc = Op.getOpcode();
12929   assert((Opc >= ISD::BUILTIN_OP_END ||
12930           Opc == ISD::INTRINSIC_WO_CHAIN ||
12931           Opc == ISD::INTRINSIC_W_CHAIN ||
12932           Opc == ISD::INTRINSIC_VOID) &&
12933          "Should use MaskedValueIsZero if you don't know whether Op"
12934          " is a target node!");
12935
12936   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
12937   switch (Opc) {
12938   default: break;
12939   case X86ISD::ADD:
12940   case X86ISD::SUB:
12941   case X86ISD::ADC:
12942   case X86ISD::SBB:
12943   case X86ISD::SMUL:
12944   case X86ISD::UMUL:
12945   case X86ISD::INC:
12946   case X86ISD::DEC:
12947   case X86ISD::OR:
12948   case X86ISD::XOR:
12949   case X86ISD::AND:
12950     // These nodes' second result is a boolean.
12951     if (Op.getResNo() == 0)
12952       break;
12953     // Fallthrough
12954   case X86ISD::SETCC:
12955     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12956     break;
12957   case ISD::INTRINSIC_WO_CHAIN: {
12958     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12959     unsigned NumLoBits = 0;
12960     switch (IntId) {
12961     default: break;
12962     case Intrinsic::x86_sse_movmsk_ps:
12963     case Intrinsic::x86_avx_movmsk_ps_256:
12964     case Intrinsic::x86_sse2_movmsk_pd:
12965     case Intrinsic::x86_avx_movmsk_pd_256:
12966     case Intrinsic::x86_mmx_pmovmskb:
12967     case Intrinsic::x86_sse2_pmovmskb_128:
12968     case Intrinsic::x86_avx2_pmovmskb: {
12969       // High bits of movmskp{s|d}, pmovmskb are known zero.
12970       switch (IntId) {
12971         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12972         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12973         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12974         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12975         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12976         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12977         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12978         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
12979       }
12980       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
12981       break;
12982     }
12983     }
12984     break;
12985   }
12986   }
12987 }
12988
12989 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12990                                                          unsigned Depth) const {
12991   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12992   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12993     return Op.getValueType().getScalarType().getSizeInBits();
12994
12995   // Fallback case.
12996   return 1;
12997 }
12998
12999 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13000 /// node is a GlobalAddress + offset.
13001 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13002                                        const GlobalValue* &GA,
13003                                        int64_t &Offset) const {
13004   if (N->getOpcode() == X86ISD::Wrapper) {
13005     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13006       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13007       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13008       return true;
13009     }
13010   }
13011   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13012 }
13013
13014 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13015 /// same as extracting the high 128-bit part of 256-bit vector and then
13016 /// inserting the result into the low part of a new 256-bit vector
13017 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13018   EVT VT = SVOp->getValueType(0);
13019   unsigned NumElems = VT.getVectorNumElements();
13020
13021   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13022   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13023     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13024         SVOp->getMaskElt(j) >= 0)
13025       return false;
13026
13027   return true;
13028 }
13029
13030 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13031 /// same as extracting the low 128-bit part of 256-bit vector and then
13032 /// inserting the result into the high part of a new 256-bit vector
13033 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13034   EVT VT = SVOp->getValueType(0);
13035   unsigned NumElems = VT.getVectorNumElements();
13036
13037   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13038   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13039     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13040         SVOp->getMaskElt(j) >= 0)
13041       return false;
13042
13043   return true;
13044 }
13045
13046 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13047 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13048                                         TargetLowering::DAGCombinerInfo &DCI,
13049                                         const X86Subtarget* Subtarget) {
13050   DebugLoc dl = N->getDebugLoc();
13051   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13052   SDValue V1 = SVOp->getOperand(0);
13053   SDValue V2 = SVOp->getOperand(1);
13054   EVT VT = SVOp->getValueType(0);
13055   unsigned NumElems = VT.getVectorNumElements();
13056
13057   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13058       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13059     //
13060     //                   0,0,0,...
13061     //                      |
13062     //    V      UNDEF    BUILD_VECTOR    UNDEF
13063     //     \      /           \           /
13064     //  CONCAT_VECTOR         CONCAT_VECTOR
13065     //         \                  /
13066     //          \                /
13067     //          RESULT: V + zero extended
13068     //
13069     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13070         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13071         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13072       return SDValue();
13073
13074     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13075       return SDValue();
13076
13077     // To match the shuffle mask, the first half of the mask should
13078     // be exactly the first vector, and all the rest a splat with the
13079     // first element of the second one.
13080     for (unsigned i = 0; i != NumElems/2; ++i)
13081       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13082           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13083         return SDValue();
13084
13085     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13086     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13087       if (Ld->hasNUsesOfValue(1, 0)) {
13088         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13089         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13090         SDValue ResNode =
13091           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13092                                   Ld->getMemoryVT(),
13093                                   Ld->getPointerInfo(),
13094                                   Ld->getAlignment(),
13095                                   false/*isVolatile*/, true/*ReadMem*/,
13096                                   false/*WriteMem*/);
13097         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13098       }
13099     }
13100
13101     // Emit a zeroed vector and insert the desired subvector on its
13102     // first half.
13103     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13104     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13105     return DCI.CombineTo(N, InsV);
13106   }
13107
13108   //===--------------------------------------------------------------------===//
13109   // Combine some shuffles into subvector extracts and inserts:
13110   //
13111
13112   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13113   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13114     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13115     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13116     return DCI.CombineTo(N, InsV);
13117   }
13118
13119   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13120   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13121     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13122     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13123     return DCI.CombineTo(N, InsV);
13124   }
13125
13126   return SDValue();
13127 }
13128
13129 /// PerformShuffleCombine - Performs several different shuffle combines.
13130 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13131                                      TargetLowering::DAGCombinerInfo &DCI,
13132                                      const X86Subtarget *Subtarget) {
13133   DebugLoc dl = N->getDebugLoc();
13134   EVT VT = N->getValueType(0);
13135
13136   // Don't create instructions with illegal types after legalize types has run.
13137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13138   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13139     return SDValue();
13140
13141   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13142   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13143       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13144     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13145
13146   // Only handle 128 wide vector from here on.
13147   if (VT.getSizeInBits() != 128)
13148     return SDValue();
13149
13150   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13151   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13152   // consecutive, non-overlapping, and in the right order.
13153   SmallVector<SDValue, 16> Elts;
13154   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13155     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13156
13157   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13158 }
13159
13160
13161 /// DCI, PerformTruncateCombine - Converts truncate operation to
13162 /// a sequence of vector shuffle operations.
13163 /// It is possible when we truncate 256-bit vector to 128-bit vector
13164
13165 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13166                                                   DAGCombinerInfo &DCI) const {
13167   if (!DCI.isBeforeLegalizeOps())
13168     return SDValue();
13169
13170   if (!Subtarget->hasAVX())
13171     return SDValue();
13172
13173   EVT VT = N->getValueType(0);
13174   SDValue Op = N->getOperand(0);
13175   EVT OpVT = Op.getValueType();
13176   DebugLoc dl = N->getDebugLoc();
13177
13178   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13179
13180     if (Subtarget->hasAVX2()) {
13181       // AVX2: v4i64 -> v4i32
13182
13183       // VPERMD
13184       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13185
13186       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13187       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13188                                 ShufMask);
13189
13190       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13191                          DAG.getIntPtrConstant(0));
13192     }
13193
13194     // AVX: v4i64 -> v4i32
13195     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13196                                DAG.getIntPtrConstant(0));
13197
13198     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13199                                DAG.getIntPtrConstant(2));
13200
13201     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13202     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13203
13204     // PSHUFD
13205     static const int ShufMask1[] = {0, 2, 0, 0};
13206
13207     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1);
13208     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1);
13209
13210     // MOVLHPS
13211     static const int ShufMask2[] = {0, 1, 4, 5};
13212
13213     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13214   }
13215
13216   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13217
13218     if (Subtarget->hasAVX2()) {
13219       // AVX2: v8i32 -> v8i16
13220
13221       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13222
13223       // PSHUFB
13224       SmallVector<SDValue,32> pshufbMask;
13225       for (unsigned i = 0; i < 2; ++i) {
13226         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13227         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13228         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13229         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13230         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13231         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13232         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13233         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13234         for (unsigned j = 0; j < 8; ++j)
13235           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13236       }
13237       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13238                                &pshufbMask[0], 32);
13239       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13240
13241       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13242
13243       static const int ShufMask[] = {0,  2,  -1,  -1};
13244       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13245                                 &ShufMask[0]);
13246
13247       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13248                        DAG.getIntPtrConstant(0));
13249
13250       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13251     }
13252
13253     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13254                                DAG.getIntPtrConstant(0));
13255
13256     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13257                                DAG.getIntPtrConstant(4));
13258
13259     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13260     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13261
13262     // PSHUFB
13263     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13264                                    -1, -1, -1, -1, -1, -1, -1, -1};
13265
13266     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8),
13267                                 ShufMask1);
13268     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8),
13269                                 ShufMask1);
13270
13271     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13272     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13273
13274     // MOVLHPS
13275     static const int ShufMask2[] = {0, 1, 4, 5};
13276
13277     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13278     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13279   }
13280
13281   return SDValue();
13282 }
13283
13284 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13285 /// specific shuffle of a load can be folded into a single element load.
13286 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13287 /// shuffles have been customed lowered so we need to handle those here.
13288 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13289                                          TargetLowering::DAGCombinerInfo &DCI) {
13290   if (DCI.isBeforeLegalizeOps())
13291     return SDValue();
13292
13293   SDValue InVec = N->getOperand(0);
13294   SDValue EltNo = N->getOperand(1);
13295
13296   if (!isa<ConstantSDNode>(EltNo))
13297     return SDValue();
13298
13299   EVT VT = InVec.getValueType();
13300
13301   bool HasShuffleIntoBitcast = false;
13302   if (InVec.getOpcode() == ISD::BITCAST) {
13303     // Don't duplicate a load with other uses.
13304     if (!InVec.hasOneUse())
13305       return SDValue();
13306     EVT BCVT = InVec.getOperand(0).getValueType();
13307     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13308       return SDValue();
13309     InVec = InVec.getOperand(0);
13310     HasShuffleIntoBitcast = true;
13311   }
13312
13313   if (!isTargetShuffle(InVec.getOpcode()))
13314     return SDValue();
13315
13316   // Don't duplicate a load with other uses.
13317   if (!InVec.hasOneUse())
13318     return SDValue();
13319
13320   SmallVector<int, 16> ShuffleMask;
13321   bool UnaryShuffle;
13322   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13323                             UnaryShuffle))
13324     return SDValue();
13325
13326   // Select the input vector, guarding against out of range extract vector.
13327   unsigned NumElems = VT.getVectorNumElements();
13328   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13329   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13330   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13331                                          : InVec.getOperand(1);
13332
13333   // If inputs to shuffle are the same for both ops, then allow 2 uses
13334   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13335
13336   if (LdNode.getOpcode() == ISD::BITCAST) {
13337     // Don't duplicate a load with other uses.
13338     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13339       return SDValue();
13340
13341     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13342     LdNode = LdNode.getOperand(0);
13343   }
13344
13345   if (!ISD::isNormalLoad(LdNode.getNode()))
13346     return SDValue();
13347
13348   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13349
13350   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13351     return SDValue();
13352
13353   if (HasShuffleIntoBitcast) {
13354     // If there's a bitcast before the shuffle, check if the load type and
13355     // alignment is valid.
13356     unsigned Align = LN0->getAlignment();
13357     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13358     unsigned NewAlign = TLI.getTargetData()->
13359       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13360
13361     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13362       return SDValue();
13363   }
13364
13365   // All checks match so transform back to vector_shuffle so that DAG combiner
13366   // can finish the job
13367   DebugLoc dl = N->getDebugLoc();
13368
13369   // Create shuffle node taking into account the case that its a unary shuffle
13370   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13371   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13372                                  InVec.getOperand(0), Shuffle,
13373                                  &ShuffleMask[0]);
13374   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13375   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13376                      EltNo);
13377 }
13378
13379 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13380 /// generation and convert it from being a bunch of shuffles and extracts
13381 /// to a simple store and scalar loads to extract the elements.
13382 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13383                                          TargetLowering::DAGCombinerInfo &DCI) {
13384   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13385   if (NewOp.getNode())
13386     return NewOp;
13387
13388   SDValue InputVector = N->getOperand(0);
13389
13390   // Only operate on vectors of 4 elements, where the alternative shuffling
13391   // gets to be more expensive.
13392   if (InputVector.getValueType() != MVT::v4i32)
13393     return SDValue();
13394
13395   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13396   // single use which is a sign-extend or zero-extend, and all elements are
13397   // used.
13398   SmallVector<SDNode *, 4> Uses;
13399   unsigned ExtractedElements = 0;
13400   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13401        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13402     if (UI.getUse().getResNo() != InputVector.getResNo())
13403       return SDValue();
13404
13405     SDNode *Extract = *UI;
13406     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13407       return SDValue();
13408
13409     if (Extract->getValueType(0) != MVT::i32)
13410       return SDValue();
13411     if (!Extract->hasOneUse())
13412       return SDValue();
13413     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13414         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13415       return SDValue();
13416     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13417       return SDValue();
13418
13419     // Record which element was extracted.
13420     ExtractedElements |=
13421       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13422
13423     Uses.push_back(Extract);
13424   }
13425
13426   // If not all the elements were used, this may not be worthwhile.
13427   if (ExtractedElements != 15)
13428     return SDValue();
13429
13430   // Ok, we've now decided to do the transformation.
13431   DebugLoc dl = InputVector.getDebugLoc();
13432
13433   // Store the value to a temporary stack slot.
13434   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13435   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13436                             MachinePointerInfo(), false, false, 0);
13437
13438   // Replace each use (extract) with a load of the appropriate element.
13439   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13440        UE = Uses.end(); UI != UE; ++UI) {
13441     SDNode *Extract = *UI;
13442
13443     // cOMpute the element's address.
13444     SDValue Idx = Extract->getOperand(1);
13445     unsigned EltSize =
13446         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13447     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13448     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13449     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13450
13451     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13452                                      StackPtr, OffsetVal);
13453
13454     // Load the scalar.
13455     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13456                                      ScalarAddr, MachinePointerInfo(),
13457                                      false, false, false, 0);
13458
13459     // Replace the exact with the load.
13460     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13461   }
13462
13463   // The replacement was made in place; don't return anything.
13464   return SDValue();
13465 }
13466
13467 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13468 /// nodes.
13469 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13470                                     TargetLowering::DAGCombinerInfo &DCI,
13471                                     const X86Subtarget *Subtarget) {
13472   DebugLoc DL = N->getDebugLoc();
13473   SDValue Cond = N->getOperand(0);
13474   // Get the LHS/RHS of the select.
13475   SDValue LHS = N->getOperand(1);
13476   SDValue RHS = N->getOperand(2);
13477   EVT VT = LHS.getValueType();
13478
13479   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13480   // instructions match the semantics of the common C idiom x<y?x:y but not
13481   // x<=y?x:y, because of how they handle negative zero (which can be
13482   // ignored in unsafe-math mode).
13483   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13484       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13485       (Subtarget->hasSSE2() ||
13486        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13487     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13488
13489     unsigned Opcode = 0;
13490     // Check for x CC y ? x : y.
13491     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13492         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13493       switch (CC) {
13494       default: break;
13495       case ISD::SETULT:
13496         // Converting this to a min would handle NaNs incorrectly, and swapping
13497         // the operands would cause it to handle comparisons between positive
13498         // and negative zero incorrectly.
13499         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13500           if (!DAG.getTarget().Options.UnsafeFPMath &&
13501               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13502             break;
13503           std::swap(LHS, RHS);
13504         }
13505         Opcode = X86ISD::FMIN;
13506         break;
13507       case ISD::SETOLE:
13508         // Converting this to a min would handle comparisons between positive
13509         // and negative zero incorrectly.
13510         if (!DAG.getTarget().Options.UnsafeFPMath &&
13511             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13512           break;
13513         Opcode = X86ISD::FMIN;
13514         break;
13515       case ISD::SETULE:
13516         // Converting this to a min would handle both negative zeros and NaNs
13517         // incorrectly, but we can swap the operands to fix both.
13518         std::swap(LHS, RHS);
13519       case ISD::SETOLT:
13520       case ISD::SETLT:
13521       case ISD::SETLE:
13522         Opcode = X86ISD::FMIN;
13523         break;
13524
13525       case ISD::SETOGE:
13526         // Converting this to a max would handle comparisons between positive
13527         // and negative zero incorrectly.
13528         if (!DAG.getTarget().Options.UnsafeFPMath &&
13529             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13530           break;
13531         Opcode = X86ISD::FMAX;
13532         break;
13533       case ISD::SETUGT:
13534         // Converting this to a max would handle NaNs incorrectly, and swapping
13535         // the operands would cause it to handle comparisons between positive
13536         // and negative zero incorrectly.
13537         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13538           if (!DAG.getTarget().Options.UnsafeFPMath &&
13539               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13540             break;
13541           std::swap(LHS, RHS);
13542         }
13543         Opcode = X86ISD::FMAX;
13544         break;
13545       case ISD::SETUGE:
13546         // Converting this to a max would handle both negative zeros and NaNs
13547         // incorrectly, but we can swap the operands to fix both.
13548         std::swap(LHS, RHS);
13549       case ISD::SETOGT:
13550       case ISD::SETGT:
13551       case ISD::SETGE:
13552         Opcode = X86ISD::FMAX;
13553         break;
13554       }
13555     // Check for x CC y ? y : x -- a min/max with reversed arms.
13556     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13557                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13558       switch (CC) {
13559       default: break;
13560       case ISD::SETOGE:
13561         // Converting this to a min would handle comparisons between positive
13562         // and negative zero incorrectly, and swapping the operands would
13563         // cause it to handle NaNs incorrectly.
13564         if (!DAG.getTarget().Options.UnsafeFPMath &&
13565             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13566           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13567             break;
13568           std::swap(LHS, RHS);
13569         }
13570         Opcode = X86ISD::FMIN;
13571         break;
13572       case ISD::SETUGT:
13573         // Converting this to a min would handle NaNs incorrectly.
13574         if (!DAG.getTarget().Options.UnsafeFPMath &&
13575             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13576           break;
13577         Opcode = X86ISD::FMIN;
13578         break;
13579       case ISD::SETUGE:
13580         // Converting this to a min would handle both negative zeros and NaNs
13581         // incorrectly, but we can swap the operands to fix both.
13582         std::swap(LHS, RHS);
13583       case ISD::SETOGT:
13584       case ISD::SETGT:
13585       case ISD::SETGE:
13586         Opcode = X86ISD::FMIN;
13587         break;
13588
13589       case ISD::SETULT:
13590         // Converting this to a max would handle NaNs incorrectly.
13591         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13592           break;
13593         Opcode = X86ISD::FMAX;
13594         break;
13595       case ISD::SETOLE:
13596         // Converting this to a max would handle comparisons between positive
13597         // and negative zero incorrectly, and swapping the operands would
13598         // cause it to handle NaNs incorrectly.
13599         if (!DAG.getTarget().Options.UnsafeFPMath &&
13600             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13601           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13602             break;
13603           std::swap(LHS, RHS);
13604         }
13605         Opcode = X86ISD::FMAX;
13606         break;
13607       case ISD::SETULE:
13608         // Converting this to a max would handle both negative zeros and NaNs
13609         // incorrectly, but we can swap the operands to fix both.
13610         std::swap(LHS, RHS);
13611       case ISD::SETOLT:
13612       case ISD::SETLT:
13613       case ISD::SETLE:
13614         Opcode = X86ISD::FMAX;
13615         break;
13616       }
13617     }
13618
13619     if (Opcode)
13620       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13621   }
13622
13623   // If this is a select between two integer constants, try to do some
13624   // optimizations.
13625   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13626     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13627       // Don't do this for crazy integer types.
13628       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13629         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13630         // so that TrueC (the true value) is larger than FalseC.
13631         bool NeedsCondInvert = false;
13632
13633         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13634             // Efficiently invertible.
13635             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13636              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13637               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13638           NeedsCondInvert = true;
13639           std::swap(TrueC, FalseC);
13640         }
13641
13642         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13643         if (FalseC->getAPIntValue() == 0 &&
13644             TrueC->getAPIntValue().isPowerOf2()) {
13645           if (NeedsCondInvert) // Invert the condition if needed.
13646             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13647                                DAG.getConstant(1, Cond.getValueType()));
13648
13649           // Zero extend the condition if needed.
13650           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13651
13652           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13653           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13654                              DAG.getConstant(ShAmt, MVT::i8));
13655         }
13656
13657         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13658         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13659           if (NeedsCondInvert) // Invert the condition if needed.
13660             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13661                                DAG.getConstant(1, Cond.getValueType()));
13662
13663           // Zero extend the condition if needed.
13664           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13665                              FalseC->getValueType(0), Cond);
13666           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13667                              SDValue(FalseC, 0));
13668         }
13669
13670         // Optimize cases that will turn into an LEA instruction.  This requires
13671         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13672         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13673           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13674           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13675
13676           bool isFastMultiplier = false;
13677           if (Diff < 10) {
13678             switch ((unsigned char)Diff) {
13679               default: break;
13680               case 1:  // result = add base, cond
13681               case 2:  // result = lea base(    , cond*2)
13682               case 3:  // result = lea base(cond, cond*2)
13683               case 4:  // result = lea base(    , cond*4)
13684               case 5:  // result = lea base(cond, cond*4)
13685               case 8:  // result = lea base(    , cond*8)
13686               case 9:  // result = lea base(cond, cond*8)
13687                 isFastMultiplier = true;
13688                 break;
13689             }
13690           }
13691
13692           if (isFastMultiplier) {
13693             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13694             if (NeedsCondInvert) // Invert the condition if needed.
13695               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13696                                  DAG.getConstant(1, Cond.getValueType()));
13697
13698             // Zero extend the condition if needed.
13699             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13700                                Cond);
13701             // Scale the condition by the difference.
13702             if (Diff != 1)
13703               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13704                                  DAG.getConstant(Diff, Cond.getValueType()));
13705
13706             // Add the base if non-zero.
13707             if (FalseC->getAPIntValue() != 0)
13708               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13709                                  SDValue(FalseC, 0));
13710             return Cond;
13711           }
13712         }
13713       }
13714   }
13715
13716   // Canonicalize max and min:
13717   // (x > y) ? x : y -> (x >= y) ? x : y
13718   // (x < y) ? x : y -> (x <= y) ? x : y
13719   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13720   // the need for an extra compare
13721   // against zero. e.g.
13722   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13723   // subl   %esi, %edi
13724   // testl  %edi, %edi
13725   // movl   $0, %eax
13726   // cmovgl %edi, %eax
13727   // =>
13728   // xorl   %eax, %eax
13729   // subl   %esi, $edi
13730   // cmovsl %eax, %edi
13731   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13732       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13733       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13734     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13735     switch (CC) {
13736     default: break;
13737     case ISD::SETLT:
13738     case ISD::SETGT: {
13739       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13740       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13741                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
13742       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13743     }
13744     }
13745   }
13746
13747   // If we know that this node is legal then we know that it is going to be
13748   // matched by one of the SSE/AVX BLEND instructions. These instructions only
13749   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13750   // to simplify previous instructions.
13751   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13752   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13753       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
13754     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13755
13756     // Don't optimize vector selects that map to mask-registers.
13757     if (BitWidth == 1)
13758       return SDValue();
13759
13760     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13761     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13762
13763     APInt KnownZero, KnownOne;
13764     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13765                                           DCI.isBeforeLegalizeOps());
13766     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13767         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13768       DCI.CommitTargetLoweringOpt(TLO);
13769   }
13770
13771   return SDValue();
13772 }
13773
13774 // Check whether a boolean test is testing a boolean value generated by
13775 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
13776 // code.
13777 //
13778 // Simplify the following patterns:
13779 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
13780 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
13781 // to (Op EFLAGS Cond)
13782 //
13783 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
13784 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
13785 // to (Op EFLAGS !Cond)
13786 //
13787 // where Op could be BRCOND or CMOV.
13788 //
13789 static SDValue BoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
13790   // Quit if not CMP and SUB with its value result used.
13791   if (Cmp.getOpcode() != X86ISD::CMP &&
13792       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
13793       return SDValue();
13794
13795   // Quit if not used as a boolean value.
13796   if (CC != X86::COND_E && CC != X86::COND_NE)
13797     return SDValue();
13798
13799   // Check CMP operands. One of them should be 0 or 1 and the other should be
13800   // an SetCC or extended from it.
13801   SDValue Op1 = Cmp.getOperand(0);
13802   SDValue Op2 = Cmp.getOperand(1);
13803
13804   SDValue SetCC;
13805   const ConstantSDNode* C = 0;
13806   bool needOppositeCond = (CC == X86::COND_E);
13807
13808   if ((C = dyn_cast<ConstantSDNode>(Op1)))
13809     SetCC = Op2;
13810   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
13811     SetCC = Op1;
13812   else // Quit if all operands are not constants.
13813     return SDValue();
13814
13815   if (C->getZExtValue() == 1)
13816     needOppositeCond = !needOppositeCond;
13817   else if (C->getZExtValue() != 0)
13818     // Quit if the constant is neither 0 or 1.
13819     return SDValue();
13820
13821   // Skip 'zext' node.
13822   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
13823     SetCC = SetCC.getOperand(0);
13824
13825   // Quit if not SETCC.
13826   // FIXME: So far we only handle the boolean value generated from SETCC. If
13827   // there is other ways to generate boolean values, we need handle them here
13828   // as well.
13829   if (SetCC.getOpcode() != X86ISD::SETCC)
13830     return SDValue();
13831
13832   // Set the condition code or opposite one if necessary.
13833   CC = X86::CondCode(SetCC.getConstantOperandVal(0));
13834   if (needOppositeCond)
13835     CC = X86::GetOppositeBranchCondition(CC);
13836
13837   return SetCC.getOperand(1);
13838 }
13839
13840 static bool IsValidFCMOVCondition(X86::CondCode CC) {
13841   switch (CC) {
13842   default:
13843     return false;
13844   case X86::COND_B:
13845   case X86::COND_BE:
13846   case X86::COND_E:
13847   case X86::COND_P:
13848   case X86::COND_AE:
13849   case X86::COND_A:
13850   case X86::COND_NE:
13851   case X86::COND_NP:
13852     return true;
13853   }
13854 }
13855
13856 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13857 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13858                                   TargetLowering::DAGCombinerInfo &DCI) {
13859   DebugLoc DL = N->getDebugLoc();
13860
13861   // If the flag operand isn't dead, don't touch this CMOV.
13862   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13863     return SDValue();
13864
13865   SDValue FalseOp = N->getOperand(0);
13866   SDValue TrueOp = N->getOperand(1);
13867   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13868   SDValue Cond = N->getOperand(3);
13869
13870   if (CC == X86::COND_E || CC == X86::COND_NE) {
13871     switch (Cond.getOpcode()) {
13872     default: break;
13873     case X86ISD::BSR:
13874     case X86ISD::BSF:
13875       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13876       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13877         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13878     }
13879   }
13880
13881   SDValue Flags;
13882
13883   Flags = BoolTestSetCCCombine(Cond, CC);
13884   if (Flags.getNode() &&
13885       // Extra check as FCMOV only supports a subset of X86 cond.
13886       (FalseOp.getValueType() != MVT::f80 || IsValidFCMOVCondition(CC))) {
13887     SDValue Ops[] = { FalseOp, TrueOp,
13888                       DAG.getConstant(CC, MVT::i8), Flags };
13889     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
13890                        Ops, array_lengthof(Ops));
13891   }
13892
13893   // If this is a select between two integer constants, try to do some
13894   // optimizations.  Note that the operands are ordered the opposite of SELECT
13895   // operands.
13896   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13897     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13898       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13899       // larger than FalseC (the false value).
13900       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13901         CC = X86::GetOppositeBranchCondition(CC);
13902         std::swap(TrueC, FalseC);
13903       }
13904
13905       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13906       // This is efficient for any integer data type (including i8/i16) and
13907       // shift amount.
13908       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13909         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13910                            DAG.getConstant(CC, MVT::i8), Cond);
13911
13912         // Zero extend the condition if needed.
13913         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13914
13915         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13916         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13917                            DAG.getConstant(ShAmt, MVT::i8));
13918         if (N->getNumValues() == 2)  // Dead flag value?
13919           return DCI.CombineTo(N, Cond, SDValue());
13920         return Cond;
13921       }
13922
13923       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13924       // for any integer data type, including i8/i16.
13925       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13926         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13927                            DAG.getConstant(CC, MVT::i8), Cond);
13928
13929         // Zero extend the condition if needed.
13930         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13931                            FalseC->getValueType(0), Cond);
13932         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13933                            SDValue(FalseC, 0));
13934
13935         if (N->getNumValues() == 2)  // Dead flag value?
13936           return DCI.CombineTo(N, Cond, SDValue());
13937         return Cond;
13938       }
13939
13940       // Optimize cases that will turn into an LEA instruction.  This requires
13941       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13942       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13943         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13944         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13945
13946         bool isFastMultiplier = false;
13947         if (Diff < 10) {
13948           switch ((unsigned char)Diff) {
13949           default: break;
13950           case 1:  // result = add base, cond
13951           case 2:  // result = lea base(    , cond*2)
13952           case 3:  // result = lea base(cond, cond*2)
13953           case 4:  // result = lea base(    , cond*4)
13954           case 5:  // result = lea base(cond, cond*4)
13955           case 8:  // result = lea base(    , cond*8)
13956           case 9:  // result = lea base(cond, cond*8)
13957             isFastMultiplier = true;
13958             break;
13959           }
13960         }
13961
13962         if (isFastMultiplier) {
13963           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13964           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13965                              DAG.getConstant(CC, MVT::i8), Cond);
13966           // Zero extend the condition if needed.
13967           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13968                              Cond);
13969           // Scale the condition by the difference.
13970           if (Diff != 1)
13971             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13972                                DAG.getConstant(Diff, Cond.getValueType()));
13973
13974           // Add the base if non-zero.
13975           if (FalseC->getAPIntValue() != 0)
13976             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13977                                SDValue(FalseC, 0));
13978           if (N->getNumValues() == 2)  // Dead flag value?
13979             return DCI.CombineTo(N, Cond, SDValue());
13980           return Cond;
13981         }
13982       }
13983     }
13984   }
13985   return SDValue();
13986 }
13987
13988
13989 /// PerformMulCombine - Optimize a single multiply with constant into two
13990 /// in order to implement it with two cheaper instructions, e.g.
13991 /// LEA + SHL, LEA + LEA.
13992 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13993                                  TargetLowering::DAGCombinerInfo &DCI) {
13994   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13995     return SDValue();
13996
13997   EVT VT = N->getValueType(0);
13998   if (VT != MVT::i64)
13999     return SDValue();
14000
14001   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14002   if (!C)
14003     return SDValue();
14004   uint64_t MulAmt = C->getZExtValue();
14005   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14006     return SDValue();
14007
14008   uint64_t MulAmt1 = 0;
14009   uint64_t MulAmt2 = 0;
14010   if ((MulAmt % 9) == 0) {
14011     MulAmt1 = 9;
14012     MulAmt2 = MulAmt / 9;
14013   } else if ((MulAmt % 5) == 0) {
14014     MulAmt1 = 5;
14015     MulAmt2 = MulAmt / 5;
14016   } else if ((MulAmt % 3) == 0) {
14017     MulAmt1 = 3;
14018     MulAmt2 = MulAmt / 3;
14019   }
14020   if (MulAmt2 &&
14021       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14022     DebugLoc DL = N->getDebugLoc();
14023
14024     if (isPowerOf2_64(MulAmt2) &&
14025         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14026       // If second multiplifer is pow2, issue it first. We want the multiply by
14027       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14028       // is an add.
14029       std::swap(MulAmt1, MulAmt2);
14030
14031     SDValue NewMul;
14032     if (isPowerOf2_64(MulAmt1))
14033       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14034                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14035     else
14036       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14037                            DAG.getConstant(MulAmt1, VT));
14038
14039     if (isPowerOf2_64(MulAmt2))
14040       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14041                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14042     else
14043       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14044                            DAG.getConstant(MulAmt2, VT));
14045
14046     // Do not add new nodes to DAG combiner worklist.
14047     DCI.CombineTo(N, NewMul, false);
14048   }
14049   return SDValue();
14050 }
14051
14052 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14053   SDValue N0 = N->getOperand(0);
14054   SDValue N1 = N->getOperand(1);
14055   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14056   EVT VT = N0.getValueType();
14057
14058   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14059   // since the result of setcc_c is all zero's or all ones.
14060   if (VT.isInteger() && !VT.isVector() &&
14061       N1C && N0.getOpcode() == ISD::AND &&
14062       N0.getOperand(1).getOpcode() == ISD::Constant) {
14063     SDValue N00 = N0.getOperand(0);
14064     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14065         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14066           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14067          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14068       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14069       APInt ShAmt = N1C->getAPIntValue();
14070       Mask = Mask.shl(ShAmt);
14071       if (Mask != 0)
14072         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14073                            N00, DAG.getConstant(Mask, VT));
14074     }
14075   }
14076
14077
14078   // Hardware support for vector shifts is sparse which makes us scalarize the
14079   // vector operations in many cases. Also, on sandybridge ADD is faster than
14080   // shl.
14081   // (shl V, 1) -> add V,V
14082   if (isSplatVector(N1.getNode())) {
14083     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14084     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14085     // We shift all of the values by one. In many cases we do not have
14086     // hardware support for this operation. This is better expressed as an ADD
14087     // of two values.
14088     if (N1C && (1 == N1C->getZExtValue())) {
14089       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14090     }
14091   }
14092
14093   return SDValue();
14094 }
14095
14096 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14097 ///                       when possible.
14098 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14099                                    TargetLowering::DAGCombinerInfo &DCI,
14100                                    const X86Subtarget *Subtarget) {
14101   EVT VT = N->getValueType(0);
14102   if (N->getOpcode() == ISD::SHL) {
14103     SDValue V = PerformSHLCombine(N, DAG);
14104     if (V.getNode()) return V;
14105   }
14106
14107   // On X86 with SSE2 support, we can transform this to a vector shift if
14108   // all elements are shifted by the same amount.  We can't do this in legalize
14109   // because the a constant vector is typically transformed to a constant pool
14110   // so we have no knowledge of the shift amount.
14111   if (!Subtarget->hasSSE2())
14112     return SDValue();
14113
14114   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14115       (!Subtarget->hasAVX2() ||
14116        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14117     return SDValue();
14118
14119   SDValue ShAmtOp = N->getOperand(1);
14120   EVT EltVT = VT.getVectorElementType();
14121   DebugLoc DL = N->getDebugLoc();
14122   SDValue BaseShAmt = SDValue();
14123   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14124     unsigned NumElts = VT.getVectorNumElements();
14125     unsigned i = 0;
14126     for (; i != NumElts; ++i) {
14127       SDValue Arg = ShAmtOp.getOperand(i);
14128       if (Arg.getOpcode() == ISD::UNDEF) continue;
14129       BaseShAmt = Arg;
14130       break;
14131     }
14132     // Handle the case where the build_vector is all undef
14133     // FIXME: Should DAG allow this?
14134     if (i == NumElts)
14135       return SDValue();
14136
14137     for (; i != NumElts; ++i) {
14138       SDValue Arg = ShAmtOp.getOperand(i);
14139       if (Arg.getOpcode() == ISD::UNDEF) continue;
14140       if (Arg != BaseShAmt) {
14141         return SDValue();
14142       }
14143     }
14144   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14145              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14146     SDValue InVec = ShAmtOp.getOperand(0);
14147     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14148       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14149       unsigned i = 0;
14150       for (; i != NumElts; ++i) {
14151         SDValue Arg = InVec.getOperand(i);
14152         if (Arg.getOpcode() == ISD::UNDEF) continue;
14153         BaseShAmt = Arg;
14154         break;
14155       }
14156     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14157        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14158          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14159          if (C->getZExtValue() == SplatIdx)
14160            BaseShAmt = InVec.getOperand(1);
14161        }
14162     }
14163     if (BaseShAmt.getNode() == 0) {
14164       // Don't create instructions with illegal types after legalize
14165       // types has run.
14166       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14167           !DCI.isBeforeLegalize())
14168         return SDValue();
14169
14170       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14171                               DAG.getIntPtrConstant(0));
14172     }
14173   } else
14174     return SDValue();
14175
14176   // The shift amount is an i32.
14177   if (EltVT.bitsGT(MVT::i32))
14178     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14179   else if (EltVT.bitsLT(MVT::i32))
14180     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14181
14182   // The shift amount is identical so we can do a vector shift.
14183   SDValue  ValOp = N->getOperand(0);
14184   switch (N->getOpcode()) {
14185   default:
14186     llvm_unreachable("Unknown shift opcode!");
14187   case ISD::SHL:
14188     switch (VT.getSimpleVT().SimpleTy) {
14189     default: return SDValue();
14190     case MVT::v2i64:
14191     case MVT::v4i32:
14192     case MVT::v8i16:
14193     case MVT::v4i64:
14194     case MVT::v8i32:
14195     case MVT::v16i16:
14196       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14197     }
14198   case ISD::SRA:
14199     switch (VT.getSimpleVT().SimpleTy) {
14200     default: return SDValue();
14201     case MVT::v4i32:
14202     case MVT::v8i16:
14203     case MVT::v8i32:
14204     case MVT::v16i16:
14205       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14206     }
14207   case ISD::SRL:
14208     switch (VT.getSimpleVT().SimpleTy) {
14209     default: return SDValue();
14210     case MVT::v2i64:
14211     case MVT::v4i32:
14212     case MVT::v8i16:
14213     case MVT::v4i64:
14214     case MVT::v8i32:
14215     case MVT::v16i16:
14216       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14217     }
14218   }
14219 }
14220
14221
14222 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14223 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14224 // and friends.  Likewise for OR -> CMPNEQSS.
14225 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14226                             TargetLowering::DAGCombinerInfo &DCI,
14227                             const X86Subtarget *Subtarget) {
14228   unsigned opcode;
14229
14230   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14231   // we're requiring SSE2 for both.
14232   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14233     SDValue N0 = N->getOperand(0);
14234     SDValue N1 = N->getOperand(1);
14235     SDValue CMP0 = N0->getOperand(1);
14236     SDValue CMP1 = N1->getOperand(1);
14237     DebugLoc DL = N->getDebugLoc();
14238
14239     // The SETCCs should both refer to the same CMP.
14240     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14241       return SDValue();
14242
14243     SDValue CMP00 = CMP0->getOperand(0);
14244     SDValue CMP01 = CMP0->getOperand(1);
14245     EVT     VT    = CMP00.getValueType();
14246
14247     if (VT == MVT::f32 || VT == MVT::f64) {
14248       bool ExpectingFlags = false;
14249       // Check for any users that want flags:
14250       for (SDNode::use_iterator UI = N->use_begin(),
14251              UE = N->use_end();
14252            !ExpectingFlags && UI != UE; ++UI)
14253         switch (UI->getOpcode()) {
14254         default:
14255         case ISD::BR_CC:
14256         case ISD::BRCOND:
14257         case ISD::SELECT:
14258           ExpectingFlags = true;
14259           break;
14260         case ISD::CopyToReg:
14261         case ISD::SIGN_EXTEND:
14262         case ISD::ZERO_EXTEND:
14263         case ISD::ANY_EXTEND:
14264           break;
14265         }
14266
14267       if (!ExpectingFlags) {
14268         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14269         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14270
14271         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14272           X86::CondCode tmp = cc0;
14273           cc0 = cc1;
14274           cc1 = tmp;
14275         }
14276
14277         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14278             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14279           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14280           X86ISD::NodeType NTOperator = is64BitFP ?
14281             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14282           // FIXME: need symbolic constants for these magic numbers.
14283           // See X86ATTInstPrinter.cpp:printSSECC().
14284           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14285           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14286                                               DAG.getConstant(x86cc, MVT::i8));
14287           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14288                                               OnesOrZeroesF);
14289           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14290                                       DAG.getConstant(1, MVT::i32));
14291           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14292           return OneBitOfTruth;
14293         }
14294       }
14295     }
14296   }
14297   return SDValue();
14298 }
14299
14300 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14301 /// so it can be folded inside ANDNP.
14302 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14303   EVT VT = N->getValueType(0);
14304
14305   // Match direct AllOnes for 128 and 256-bit vectors
14306   if (ISD::isBuildVectorAllOnes(N))
14307     return true;
14308
14309   // Look through a bit convert.
14310   if (N->getOpcode() == ISD::BITCAST)
14311     N = N->getOperand(0).getNode();
14312
14313   // Sometimes the operand may come from a insert_subvector building a 256-bit
14314   // allones vector
14315   if (VT.getSizeInBits() == 256 &&
14316       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14317     SDValue V1 = N->getOperand(0);
14318     SDValue V2 = N->getOperand(1);
14319
14320     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14321         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14322         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14323         ISD::isBuildVectorAllOnes(V2.getNode()))
14324       return true;
14325   }
14326
14327   return false;
14328 }
14329
14330 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14331                                  TargetLowering::DAGCombinerInfo &DCI,
14332                                  const X86Subtarget *Subtarget) {
14333   if (DCI.isBeforeLegalizeOps())
14334     return SDValue();
14335
14336   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14337   if (R.getNode())
14338     return R;
14339
14340   EVT VT = N->getValueType(0);
14341
14342   // Create ANDN, BLSI, and BLSR instructions
14343   // BLSI is X & (-X)
14344   // BLSR is X & (X-1)
14345   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14346     SDValue N0 = N->getOperand(0);
14347     SDValue N1 = N->getOperand(1);
14348     DebugLoc DL = N->getDebugLoc();
14349
14350     // Check LHS for not
14351     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14352       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14353     // Check RHS for not
14354     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14355       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14356
14357     // Check LHS for neg
14358     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14359         isZero(N0.getOperand(0)))
14360       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14361
14362     // Check RHS for neg
14363     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14364         isZero(N1.getOperand(0)))
14365       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14366
14367     // Check LHS for X-1
14368     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14369         isAllOnes(N0.getOperand(1)))
14370       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14371
14372     // Check RHS for X-1
14373     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14374         isAllOnes(N1.getOperand(1)))
14375       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14376
14377     return SDValue();
14378   }
14379
14380   // Want to form ANDNP nodes:
14381   // 1) In the hopes of then easily combining them with OR and AND nodes
14382   //    to form PBLEND/PSIGN.
14383   // 2) To match ANDN packed intrinsics
14384   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14385     return SDValue();
14386
14387   SDValue N0 = N->getOperand(0);
14388   SDValue N1 = N->getOperand(1);
14389   DebugLoc DL = N->getDebugLoc();
14390
14391   // Check LHS for vnot
14392   if (N0.getOpcode() == ISD::XOR &&
14393       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14394       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14395     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14396
14397   // Check RHS for vnot
14398   if (N1.getOpcode() == ISD::XOR &&
14399       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14400       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14401     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14402
14403   return SDValue();
14404 }
14405
14406 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14407                                 TargetLowering::DAGCombinerInfo &DCI,
14408                                 const X86Subtarget *Subtarget) {
14409   if (DCI.isBeforeLegalizeOps())
14410     return SDValue();
14411
14412   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14413   if (R.getNode())
14414     return R;
14415
14416   EVT VT = N->getValueType(0);
14417
14418   SDValue N0 = N->getOperand(0);
14419   SDValue N1 = N->getOperand(1);
14420
14421   // look for psign/blend
14422   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14423     if (!Subtarget->hasSSSE3() ||
14424         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14425       return SDValue();
14426
14427     // Canonicalize pandn to RHS
14428     if (N0.getOpcode() == X86ISD::ANDNP)
14429       std::swap(N0, N1);
14430     // or (and (m, y), (pandn m, x))
14431     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14432       SDValue Mask = N1.getOperand(0);
14433       SDValue X    = N1.getOperand(1);
14434       SDValue Y;
14435       if (N0.getOperand(0) == Mask)
14436         Y = N0.getOperand(1);
14437       if (N0.getOperand(1) == Mask)
14438         Y = N0.getOperand(0);
14439
14440       // Check to see if the mask appeared in both the AND and ANDNP and
14441       if (!Y.getNode())
14442         return SDValue();
14443
14444       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14445       // Look through mask bitcast.
14446       if (Mask.getOpcode() == ISD::BITCAST)
14447         Mask = Mask.getOperand(0);
14448       if (X.getOpcode() == ISD::BITCAST)
14449         X = X.getOperand(0);
14450       if (Y.getOpcode() == ISD::BITCAST)
14451         Y = Y.getOperand(0);
14452
14453       EVT MaskVT = Mask.getValueType();
14454
14455       // Validate that the Mask operand is a vector sra node.
14456       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14457       // there is no psrai.b
14458       if (Mask.getOpcode() != X86ISD::VSRAI)
14459         return SDValue();
14460
14461       // Check that the SRA is all signbits.
14462       SDValue SraC = Mask.getOperand(1);
14463       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14464       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14465       if ((SraAmt + 1) != EltBits)
14466         return SDValue();
14467
14468       DebugLoc DL = N->getDebugLoc();
14469
14470       // Now we know we at least have a plendvb with the mask val.  See if
14471       // we can form a psignb/w/d.
14472       // psign = x.type == y.type == mask.type && y = sub(0, x);
14473       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14474           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14475           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14476         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14477                "Unsupported VT for PSIGN");
14478         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14479         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14480       }
14481       // PBLENDVB only available on SSE 4.1
14482       if (!Subtarget->hasSSE41())
14483         return SDValue();
14484
14485       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14486
14487       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14488       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14489       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14490       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14491       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14492     }
14493   }
14494
14495   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14496     return SDValue();
14497
14498   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14499   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14500     std::swap(N0, N1);
14501   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14502     return SDValue();
14503   if (!N0.hasOneUse() || !N1.hasOneUse())
14504     return SDValue();
14505
14506   SDValue ShAmt0 = N0.getOperand(1);
14507   if (ShAmt0.getValueType() != MVT::i8)
14508     return SDValue();
14509   SDValue ShAmt1 = N1.getOperand(1);
14510   if (ShAmt1.getValueType() != MVT::i8)
14511     return SDValue();
14512   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14513     ShAmt0 = ShAmt0.getOperand(0);
14514   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14515     ShAmt1 = ShAmt1.getOperand(0);
14516
14517   DebugLoc DL = N->getDebugLoc();
14518   unsigned Opc = X86ISD::SHLD;
14519   SDValue Op0 = N0.getOperand(0);
14520   SDValue Op1 = N1.getOperand(0);
14521   if (ShAmt0.getOpcode() == ISD::SUB) {
14522     Opc = X86ISD::SHRD;
14523     std::swap(Op0, Op1);
14524     std::swap(ShAmt0, ShAmt1);
14525   }
14526
14527   unsigned Bits = VT.getSizeInBits();
14528   if (ShAmt1.getOpcode() == ISD::SUB) {
14529     SDValue Sum = ShAmt1.getOperand(0);
14530     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14531       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14532       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14533         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14534       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14535         return DAG.getNode(Opc, DL, VT,
14536                            Op0, Op1,
14537                            DAG.getNode(ISD::TRUNCATE, DL,
14538                                        MVT::i8, ShAmt0));
14539     }
14540   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14541     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14542     if (ShAmt0C &&
14543         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14544       return DAG.getNode(Opc, DL, VT,
14545                          N0.getOperand(0), N1.getOperand(0),
14546                          DAG.getNode(ISD::TRUNCATE, DL,
14547                                        MVT::i8, ShAmt0));
14548   }
14549
14550   return SDValue();
14551 }
14552
14553 // Generate NEG and CMOV for integer abs.
14554 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14555   EVT VT = N->getValueType(0);
14556
14557   // Since X86 does not have CMOV for 8-bit integer, we don't convert
14558   // 8-bit integer abs to NEG and CMOV.
14559   if (VT.isInteger() && VT.getSizeInBits() == 8)
14560     return SDValue();
14561
14562   SDValue N0 = N->getOperand(0);
14563   SDValue N1 = N->getOperand(1);
14564   DebugLoc DL = N->getDebugLoc();
14565
14566   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14567   // and change it to SUB and CMOV.
14568   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14569       N0.getOpcode() == ISD::ADD &&
14570       N0.getOperand(1) == N1 &&
14571       N1.getOpcode() == ISD::SRA &&
14572       N1.getOperand(0) == N0.getOperand(0))
14573     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14574       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14575         // Generate SUB & CMOV.
14576         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14577                                   DAG.getConstant(0, VT), N0.getOperand(0));
14578
14579         SDValue Ops[] = { N0.getOperand(0), Neg,
14580                           DAG.getConstant(X86::COND_GE, MVT::i8),
14581                           SDValue(Neg.getNode(), 1) };
14582         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14583                            Ops, array_lengthof(Ops));
14584       }
14585   return SDValue();
14586 }
14587
14588 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14589 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14590                                  TargetLowering::DAGCombinerInfo &DCI,
14591                                  const X86Subtarget *Subtarget) {
14592   if (DCI.isBeforeLegalizeOps())
14593     return SDValue();
14594
14595   if (Subtarget->hasCMov()) {
14596     SDValue RV = performIntegerAbsCombine(N, DAG);
14597     if (RV.getNode())
14598       return RV;
14599   }
14600
14601   // Try forming BMI if it is available.
14602   if (!Subtarget->hasBMI())
14603     return SDValue();
14604
14605   EVT VT = N->getValueType(0);
14606
14607   if (VT != MVT::i32 && VT != MVT::i64)
14608     return SDValue();
14609
14610   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14611
14612   // Create BLSMSK instructions by finding X ^ (X-1)
14613   SDValue N0 = N->getOperand(0);
14614   SDValue N1 = N->getOperand(1);
14615   DebugLoc DL = N->getDebugLoc();
14616
14617   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14618       isAllOnes(N0.getOperand(1)))
14619     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14620
14621   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14622       isAllOnes(N1.getOperand(1)))
14623     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14624
14625   return SDValue();
14626 }
14627
14628 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14629 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14630                                   TargetLowering::DAGCombinerInfo &DCI,
14631                                   const X86Subtarget *Subtarget) {
14632   LoadSDNode *Ld = cast<LoadSDNode>(N);
14633   EVT RegVT = Ld->getValueType(0);
14634   EVT MemVT = Ld->getMemoryVT();
14635   DebugLoc dl = Ld->getDebugLoc();
14636   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14637
14638   ISD::LoadExtType Ext = Ld->getExtensionType();
14639
14640   // If this is a vector EXT Load then attempt to optimize it using a
14641   // shuffle. We need SSE4 for the shuffles.
14642   // TODO: It is possible to support ZExt by zeroing the undef values
14643   // during the shuffle phase or after the shuffle.
14644   if (RegVT.isVector() && RegVT.isInteger() &&
14645       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14646     assert(MemVT != RegVT && "Cannot extend to the same type");
14647     assert(MemVT.isVector() && "Must load a vector from memory");
14648
14649     unsigned NumElems = RegVT.getVectorNumElements();
14650     unsigned RegSz = RegVT.getSizeInBits();
14651     unsigned MemSz = MemVT.getSizeInBits();
14652     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14653
14654     // All sizes must be a power of two.
14655     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
14656       return SDValue();
14657
14658     // Attempt to load the original value using scalar loads.
14659     // Find the largest scalar type that divides the total loaded size.
14660     MVT SclrLoadTy = MVT::i8;
14661     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14662          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14663       MVT Tp = (MVT::SimpleValueType)tp;
14664       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14665         SclrLoadTy = Tp;
14666       }
14667     }
14668
14669     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14670     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14671         (64 <= MemSz))
14672       SclrLoadTy = MVT::f64;
14673
14674     // Calculate the number of scalar loads that we need to perform
14675     // in order to load our vector from memory.
14676     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14677
14678     // Represent our vector as a sequence of elements which are the
14679     // largest scalar that we can load.
14680     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14681       RegSz/SclrLoadTy.getSizeInBits());
14682
14683     // Represent the data using the same element type that is stored in
14684     // memory. In practice, we ''widen'' MemVT.
14685     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14686                                   RegSz/MemVT.getScalarType().getSizeInBits());
14687
14688     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14689       "Invalid vector type");
14690
14691     // We can't shuffle using an illegal type.
14692     if (!TLI.isTypeLegal(WideVecVT))
14693       return SDValue();
14694
14695     SmallVector<SDValue, 8> Chains;
14696     SDValue Ptr = Ld->getBasePtr();
14697     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
14698                                         TLI.getPointerTy());
14699     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14700
14701     for (unsigned i = 0; i < NumLoads; ++i) {
14702       // Perform a single load.
14703       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14704                                        Ptr, Ld->getPointerInfo(),
14705                                        Ld->isVolatile(), Ld->isNonTemporal(),
14706                                        Ld->isInvariant(), Ld->getAlignment());
14707       Chains.push_back(ScalarLoad.getValue(1));
14708       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14709       // another round of DAGCombining.
14710       if (i == 0)
14711         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14712       else
14713         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14714                           ScalarLoad, DAG.getIntPtrConstant(i));
14715
14716       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14717     }
14718
14719     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14720                                Chains.size());
14721
14722     // Bitcast the loaded value to a vector of the original element type, in
14723     // the size of the target vector type.
14724     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14725     unsigned SizeRatio = RegSz/MemSz;
14726
14727     // Redistribute the loaded elements into the different locations.
14728     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14729     for (unsigned i = 0; i != NumElems; ++i)
14730       ShuffleVec[i*SizeRatio] = i;
14731
14732     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14733                                          DAG.getUNDEF(WideVecVT),
14734                                          &ShuffleVec[0]);
14735
14736     // Bitcast to the requested type.
14737     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14738     // Replace the original load with the new sequence
14739     // and return the new chain.
14740     return DCI.CombineTo(N, Shuff, TF, true);
14741   }
14742
14743   return SDValue();
14744 }
14745
14746 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14747 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14748                                    const X86Subtarget *Subtarget) {
14749   StoreSDNode *St = cast<StoreSDNode>(N);
14750   EVT VT = St->getValue().getValueType();
14751   EVT StVT = St->getMemoryVT();
14752   DebugLoc dl = St->getDebugLoc();
14753   SDValue StoredVal = St->getOperand(1);
14754   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14755
14756   // If we are saving a concatenation of two XMM registers, perform two stores.
14757   // On Sandy Bridge, 256-bit memory operations are executed by two
14758   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
14759   // memory  operation.
14760   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2() &&
14761       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14762       StoredVal.getNumOperands() == 2) {
14763     SDValue Value0 = StoredVal.getOperand(0);
14764     SDValue Value1 = StoredVal.getOperand(1);
14765
14766     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14767     SDValue Ptr0 = St->getBasePtr();
14768     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14769
14770     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14771                                 St->getPointerInfo(), St->isVolatile(),
14772                                 St->isNonTemporal(), St->getAlignment());
14773     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14774                                 St->getPointerInfo(), St->isVolatile(),
14775                                 St->isNonTemporal(), St->getAlignment());
14776     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14777   }
14778
14779   // Optimize trunc store (of multiple scalars) to shuffle and store.
14780   // First, pack all of the elements in one place. Next, store to memory
14781   // in fewer chunks.
14782   if (St->isTruncatingStore() && VT.isVector()) {
14783     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14784     unsigned NumElems = VT.getVectorNumElements();
14785     assert(StVT != VT && "Cannot truncate to the same type");
14786     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14787     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14788
14789     // From, To sizes and ElemCount must be pow of two
14790     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14791     // We are going to use the original vector elt for storing.
14792     // Accumulated smaller vector elements must be a multiple of the store size.
14793     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14794
14795     unsigned SizeRatio  = FromSz / ToSz;
14796
14797     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14798
14799     // Create a type on which we perform the shuffle
14800     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14801             StVT.getScalarType(), NumElems*SizeRatio);
14802
14803     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14804
14805     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14806     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14807     for (unsigned i = 0; i != NumElems; ++i)
14808       ShuffleVec[i] = i * SizeRatio;
14809
14810     // Can't shuffle using an illegal type.
14811     if (!TLI.isTypeLegal(WideVecVT))
14812       return SDValue();
14813
14814     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14815                                          DAG.getUNDEF(WideVecVT),
14816                                          &ShuffleVec[0]);
14817     // At this point all of the data is stored at the bottom of the
14818     // register. We now need to save it to mem.
14819
14820     // Find the largest store unit
14821     MVT StoreType = MVT::i8;
14822     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14823          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14824       MVT Tp = (MVT::SimpleValueType)tp;
14825       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
14826         StoreType = Tp;
14827     }
14828
14829     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14830     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
14831         (64 <= NumElems * ToSz))
14832       StoreType = MVT::f64;
14833
14834     // Bitcast the original vector into a vector of store-size units
14835     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14836             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
14837     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14838     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14839     SmallVector<SDValue, 8> Chains;
14840     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14841                                         TLI.getPointerTy());
14842     SDValue Ptr = St->getBasePtr();
14843
14844     // Perform one or more big stores into memory.
14845     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
14846       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14847                                    StoreType, ShuffWide,
14848                                    DAG.getIntPtrConstant(i));
14849       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14850                                 St->getPointerInfo(), St->isVolatile(),
14851                                 St->isNonTemporal(), St->getAlignment());
14852       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14853       Chains.push_back(Ch);
14854     }
14855
14856     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14857                                Chains.size());
14858   }
14859
14860
14861   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14862   // the FP state in cases where an emms may be missing.
14863   // A preferable solution to the general problem is to figure out the right
14864   // places to insert EMMS.  This qualifies as a quick hack.
14865
14866   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14867   if (VT.getSizeInBits() != 64)
14868     return SDValue();
14869
14870   const Function *F = DAG.getMachineFunction().getFunction();
14871   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14872   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14873                      && Subtarget->hasSSE2();
14874   if ((VT.isVector() ||
14875        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14876       isa<LoadSDNode>(St->getValue()) &&
14877       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14878       St->getChain().hasOneUse() && !St->isVolatile()) {
14879     SDNode* LdVal = St->getValue().getNode();
14880     LoadSDNode *Ld = 0;
14881     int TokenFactorIndex = -1;
14882     SmallVector<SDValue, 8> Ops;
14883     SDNode* ChainVal = St->getChain().getNode();
14884     // Must be a store of a load.  We currently handle two cases:  the load
14885     // is a direct child, and it's under an intervening TokenFactor.  It is
14886     // possible to dig deeper under nested TokenFactors.
14887     if (ChainVal == LdVal)
14888       Ld = cast<LoadSDNode>(St->getChain());
14889     else if (St->getValue().hasOneUse() &&
14890              ChainVal->getOpcode() == ISD::TokenFactor) {
14891       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14892         if (ChainVal->getOperand(i).getNode() == LdVal) {
14893           TokenFactorIndex = i;
14894           Ld = cast<LoadSDNode>(St->getValue());
14895         } else
14896           Ops.push_back(ChainVal->getOperand(i));
14897       }
14898     }
14899
14900     if (!Ld || !ISD::isNormalLoad(Ld))
14901       return SDValue();
14902
14903     // If this is not the MMX case, i.e. we are just turning i64 load/store
14904     // into f64 load/store, avoid the transformation if there are multiple
14905     // uses of the loaded value.
14906     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14907       return SDValue();
14908
14909     DebugLoc LdDL = Ld->getDebugLoc();
14910     DebugLoc StDL = N->getDebugLoc();
14911     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14912     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14913     // pair instead.
14914     if (Subtarget->is64Bit() || F64IsLegal) {
14915       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14916       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14917                                   Ld->getPointerInfo(), Ld->isVolatile(),
14918                                   Ld->isNonTemporal(), Ld->isInvariant(),
14919                                   Ld->getAlignment());
14920       SDValue NewChain = NewLd.getValue(1);
14921       if (TokenFactorIndex != -1) {
14922         Ops.push_back(NewChain);
14923         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14924                                Ops.size());
14925       }
14926       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14927                           St->getPointerInfo(),
14928                           St->isVolatile(), St->isNonTemporal(),
14929                           St->getAlignment());
14930     }
14931
14932     // Otherwise, lower to two pairs of 32-bit loads / stores.
14933     SDValue LoAddr = Ld->getBasePtr();
14934     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14935                                  DAG.getConstant(4, MVT::i32));
14936
14937     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14938                                Ld->getPointerInfo(),
14939                                Ld->isVolatile(), Ld->isNonTemporal(),
14940                                Ld->isInvariant(), Ld->getAlignment());
14941     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14942                                Ld->getPointerInfo().getWithOffset(4),
14943                                Ld->isVolatile(), Ld->isNonTemporal(),
14944                                Ld->isInvariant(),
14945                                MinAlign(Ld->getAlignment(), 4));
14946
14947     SDValue NewChain = LoLd.getValue(1);
14948     if (TokenFactorIndex != -1) {
14949       Ops.push_back(LoLd);
14950       Ops.push_back(HiLd);
14951       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14952                              Ops.size());
14953     }
14954
14955     LoAddr = St->getBasePtr();
14956     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14957                          DAG.getConstant(4, MVT::i32));
14958
14959     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14960                                 St->getPointerInfo(),
14961                                 St->isVolatile(), St->isNonTemporal(),
14962                                 St->getAlignment());
14963     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14964                                 St->getPointerInfo().getWithOffset(4),
14965                                 St->isVolatile(),
14966                                 St->isNonTemporal(),
14967                                 MinAlign(St->getAlignment(), 4));
14968     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14969   }
14970   return SDValue();
14971 }
14972
14973 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14974 /// and return the operands for the horizontal operation in LHS and RHS.  A
14975 /// horizontal operation performs the binary operation on successive elements
14976 /// of its first operand, then on successive elements of its second operand,
14977 /// returning the resulting values in a vector.  For example, if
14978 ///   A = < float a0, float a1, float a2, float a3 >
14979 /// and
14980 ///   B = < float b0, float b1, float b2, float b3 >
14981 /// then the result of doing a horizontal operation on A and B is
14982 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14983 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14984 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14985 /// set to A, RHS to B, and the routine returns 'true'.
14986 /// Note that the binary operation should have the property that if one of the
14987 /// operands is UNDEF then the result is UNDEF.
14988 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14989   // Look for the following pattern: if
14990   //   A = < float a0, float a1, float a2, float a3 >
14991   //   B = < float b0, float b1, float b2, float b3 >
14992   // and
14993   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14994   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14995   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14996   // which is A horizontal-op B.
14997
14998   // At least one of the operands should be a vector shuffle.
14999   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15000       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15001     return false;
15002
15003   EVT VT = LHS.getValueType();
15004
15005   assert((VT.is128BitVector() || VT.is256BitVector()) &&
15006          "Unsupported vector type for horizontal add/sub");
15007
15008   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15009   // operate independently on 128-bit lanes.
15010   unsigned NumElts = VT.getVectorNumElements();
15011   unsigned NumLanes = VT.getSizeInBits()/128;
15012   unsigned NumLaneElts = NumElts / NumLanes;
15013   assert((NumLaneElts % 2 == 0) &&
15014          "Vector type should have an even number of elements in each lane");
15015   unsigned HalfLaneElts = NumLaneElts/2;
15016
15017   // View LHS in the form
15018   //   LHS = VECTOR_SHUFFLE A, B, LMask
15019   // If LHS is not a shuffle then pretend it is the shuffle
15020   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15021   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15022   // type VT.
15023   SDValue A, B;
15024   SmallVector<int, 16> LMask(NumElts);
15025   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15026     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15027       A = LHS.getOperand(0);
15028     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15029       B = LHS.getOperand(1);
15030     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15031     std::copy(Mask.begin(), Mask.end(), LMask.begin());
15032   } else {
15033     if (LHS.getOpcode() != ISD::UNDEF)
15034       A = LHS;
15035     for (unsigned i = 0; i != NumElts; ++i)
15036       LMask[i] = i;
15037   }
15038
15039   // Likewise, view RHS in the form
15040   //   RHS = VECTOR_SHUFFLE C, D, RMask
15041   SDValue C, D;
15042   SmallVector<int, 16> RMask(NumElts);
15043   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15044     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15045       C = RHS.getOperand(0);
15046     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15047       D = RHS.getOperand(1);
15048     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15049     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15050   } else {
15051     if (RHS.getOpcode() != ISD::UNDEF)
15052       C = RHS;
15053     for (unsigned i = 0; i != NumElts; ++i)
15054       RMask[i] = i;
15055   }
15056
15057   // Check that the shuffles are both shuffling the same vectors.
15058   if (!(A == C && B == D) && !(A == D && B == C))
15059     return false;
15060
15061   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15062   if (!A.getNode() && !B.getNode())
15063     return false;
15064
15065   // If A and B occur in reverse order in RHS, then "swap" them (which means
15066   // rewriting the mask).
15067   if (A != C)
15068     CommuteVectorShuffleMask(RMask, NumElts);
15069
15070   // At this point LHS and RHS are equivalent to
15071   //   LHS = VECTOR_SHUFFLE A, B, LMask
15072   //   RHS = VECTOR_SHUFFLE A, B, RMask
15073   // Check that the masks correspond to performing a horizontal operation.
15074   for (unsigned i = 0; i != NumElts; ++i) {
15075     int LIdx = LMask[i], RIdx = RMask[i];
15076
15077     // Ignore any UNDEF components.
15078     if (LIdx < 0 || RIdx < 0 ||
15079         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15080         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15081       continue;
15082
15083     // Check that successive elements are being operated on.  If not, this is
15084     // not a horizontal operation.
15085     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15086     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15087     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15088     if (!(LIdx == Index && RIdx == Index + 1) &&
15089         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15090       return false;
15091   }
15092
15093   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15094   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15095   return true;
15096 }
15097
15098 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15099 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15100                                   const X86Subtarget *Subtarget) {
15101   EVT VT = N->getValueType(0);
15102   SDValue LHS = N->getOperand(0);
15103   SDValue RHS = N->getOperand(1);
15104
15105   // Try to synthesize horizontal adds from adds of shuffles.
15106   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15107        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15108       isHorizontalBinOp(LHS, RHS, true))
15109     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15110   return SDValue();
15111 }
15112
15113 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15114 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15115                                   const X86Subtarget *Subtarget) {
15116   EVT VT = N->getValueType(0);
15117   SDValue LHS = N->getOperand(0);
15118   SDValue RHS = N->getOperand(1);
15119
15120   // Try to synthesize horizontal subs from subs of shuffles.
15121   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15122        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15123       isHorizontalBinOp(LHS, RHS, false))
15124     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15125   return SDValue();
15126 }
15127
15128 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15129 /// X86ISD::FXOR nodes.
15130 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15131   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15132   // F[X]OR(0.0, x) -> x
15133   // F[X]OR(x, 0.0) -> x
15134   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15135     if (C->getValueAPF().isPosZero())
15136       return N->getOperand(1);
15137   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15138     if (C->getValueAPF().isPosZero())
15139       return N->getOperand(0);
15140   return SDValue();
15141 }
15142
15143 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15144 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15145   // FAND(0.0, x) -> 0.0
15146   // FAND(x, 0.0) -> 0.0
15147   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15148     if (C->getValueAPF().isPosZero())
15149       return N->getOperand(0);
15150   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15151     if (C->getValueAPF().isPosZero())
15152       return N->getOperand(1);
15153   return SDValue();
15154 }
15155
15156 static SDValue PerformBTCombine(SDNode *N,
15157                                 SelectionDAG &DAG,
15158                                 TargetLowering::DAGCombinerInfo &DCI) {
15159   // BT ignores high bits in the bit index operand.
15160   SDValue Op1 = N->getOperand(1);
15161   if (Op1.hasOneUse()) {
15162     unsigned BitWidth = Op1.getValueSizeInBits();
15163     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15164     APInt KnownZero, KnownOne;
15165     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15166                                           !DCI.isBeforeLegalizeOps());
15167     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15168     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15169         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15170       DCI.CommitTargetLoweringOpt(TLO);
15171   }
15172   return SDValue();
15173 }
15174
15175 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15176   SDValue Op = N->getOperand(0);
15177   if (Op.getOpcode() == ISD::BITCAST)
15178     Op = Op.getOperand(0);
15179   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15180   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15181       VT.getVectorElementType().getSizeInBits() ==
15182       OpVT.getVectorElementType().getSizeInBits()) {
15183     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15184   }
15185   return SDValue();
15186 }
15187
15188 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15189                                   TargetLowering::DAGCombinerInfo &DCI,
15190                                   const X86Subtarget *Subtarget) {
15191   if (!DCI.isBeforeLegalizeOps())
15192     return SDValue();
15193
15194   if (!Subtarget->hasAVX())
15195     return SDValue();
15196
15197   EVT VT = N->getValueType(0);
15198   SDValue Op = N->getOperand(0);
15199   EVT OpVT = Op.getValueType();
15200   DebugLoc dl = N->getDebugLoc();
15201
15202   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15203       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15204
15205     if (Subtarget->hasAVX2())
15206       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15207
15208     // Optimize vectors in AVX mode
15209     // Sign extend  v8i16 to v8i32 and
15210     //              v4i32 to v4i64
15211     //
15212     // Divide input vector into two parts
15213     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15214     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15215     // concat the vectors to original VT
15216
15217     unsigned NumElems = OpVT.getVectorNumElements();
15218     SmallVector<int,8> ShufMask1(NumElems, -1);
15219     for (unsigned i = 0; i != NumElems/2; ++i)
15220       ShufMask1[i] = i;
15221
15222     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15223                                         &ShufMask1[0]);
15224
15225     SmallVector<int,8> ShufMask2(NumElems, -1);
15226     for (unsigned i = 0; i != NumElems/2; ++i)
15227       ShufMask2[i] = i + NumElems/2;
15228
15229     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15230                                         &ShufMask2[0]);
15231
15232     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15233                                   VT.getVectorNumElements()/2);
15234
15235     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15236     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15237
15238     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15239   }
15240   return SDValue();
15241 }
15242
15243 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15244                                  const X86Subtarget* Subtarget) {
15245   DebugLoc dl = N->getDebugLoc();
15246   EVT VT = N->getValueType(0);
15247
15248   EVT ScalarVT = VT.getScalarType();
15249   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasFMA())
15250     return SDValue();
15251
15252   SDValue A = N->getOperand(0);
15253   SDValue B = N->getOperand(1);
15254   SDValue C = N->getOperand(2);
15255
15256   bool NegA = (A.getOpcode() == ISD::FNEG);
15257   bool NegB = (B.getOpcode() == ISD::FNEG);
15258   bool NegC = (C.getOpcode() == ISD::FNEG);
15259
15260   // Negative multiplication when NegA xor NegB
15261   bool NegMul = (NegA != NegB);
15262   if (NegA)
15263     A = A.getOperand(0);
15264   if (NegB)
15265     B = B.getOperand(0);
15266   if (NegC)
15267     C = C.getOperand(0);
15268
15269   unsigned Opcode;
15270   if (!NegMul)
15271     Opcode = (!NegC)? X86ISD::FMADD : X86ISD::FMSUB;
15272   else
15273     Opcode = (!NegC)? X86ISD::FNMADD : X86ISD::FNMSUB;
15274   return DAG.getNode(Opcode, dl, VT, A, B, C);
15275 }
15276
15277 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15278                                   TargetLowering::DAGCombinerInfo &DCI,
15279                                   const X86Subtarget *Subtarget) {
15280   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15281   //           (and (i32 x86isd::setcc_carry), 1)
15282   // This eliminates the zext. This transformation is necessary because
15283   // ISD::SETCC is always legalized to i8.
15284   DebugLoc dl = N->getDebugLoc();
15285   SDValue N0 = N->getOperand(0);
15286   EVT VT = N->getValueType(0);
15287   EVT OpVT = N0.getValueType();
15288
15289   if (N0.getOpcode() == ISD::AND &&
15290       N0.hasOneUse() &&
15291       N0.getOperand(0).hasOneUse()) {
15292     SDValue N00 = N0.getOperand(0);
15293     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15294       return SDValue();
15295     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15296     if (!C || C->getZExtValue() != 1)
15297       return SDValue();
15298     return DAG.getNode(ISD::AND, dl, VT,
15299                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15300                                    N00.getOperand(0), N00.getOperand(1)),
15301                        DAG.getConstant(1, VT));
15302   }
15303
15304   // Optimize vectors in AVX mode:
15305   //
15306   //   v8i16 -> v8i32
15307   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15308   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15309   //   Concat upper and lower parts.
15310   //
15311   //   v4i32 -> v4i64
15312   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15313   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15314   //   Concat upper and lower parts.
15315   //
15316   if (!DCI.isBeforeLegalizeOps())
15317     return SDValue();
15318
15319   if (!Subtarget->hasAVX())
15320     return SDValue();
15321
15322   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15323       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15324
15325     if (Subtarget->hasAVX2())
15326       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15327
15328     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15329     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15330     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15331
15332     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15333                                VT.getVectorNumElements()/2);
15334
15335     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15336     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15337
15338     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15339   }
15340
15341   return SDValue();
15342 }
15343
15344 // Optimize x == -y --> x+y == 0
15345 //          x != -y --> x+y != 0
15346 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15347   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15348   SDValue LHS = N->getOperand(0);
15349   SDValue RHS = N->getOperand(1);
15350
15351   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15352     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15353       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15354         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15355                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15356         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15357                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15358       }
15359   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15360     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15361       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15362         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15363                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15364         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15365                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15366       }
15367   return SDValue();
15368 }
15369
15370 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15371 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15372   DebugLoc DL = N->getDebugLoc();
15373   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15374   SDValue EFLAGS = N->getOperand(1);
15375
15376   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15377   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15378   // cases.
15379   if (CC == X86::COND_B)
15380     return DAG.getNode(ISD::AND, DL, MVT::i8,
15381                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15382                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
15383                        DAG.getConstant(1, MVT::i8));
15384
15385   SDValue Flags;
15386
15387   Flags = BoolTestSetCCCombine(EFLAGS, CC);
15388   if (Flags.getNode()) {
15389     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15390     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15391   }
15392
15393   return SDValue();
15394 }
15395
15396 // Optimize branch condition evaluation.
15397 //
15398 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15399                                     TargetLowering::DAGCombinerInfo &DCI,
15400                                     const X86Subtarget *Subtarget) {
15401   DebugLoc DL = N->getDebugLoc();
15402   SDValue Chain = N->getOperand(0);
15403   SDValue Dest = N->getOperand(1);
15404   SDValue EFLAGS = N->getOperand(3);
15405   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15406
15407   SDValue Flags;
15408
15409   Flags = BoolTestSetCCCombine(EFLAGS, CC);
15410   if (Flags.getNode()) {
15411     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15412     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15413                        Flags);
15414   }
15415
15416   return SDValue();
15417 }
15418
15419 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15420   SDValue Op0 = N->getOperand(0);
15421   EVT InVT = Op0->getValueType(0);
15422
15423   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15424   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15425     DebugLoc dl = N->getDebugLoc();
15426     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15427     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15428     // Notice that we use SINT_TO_FP because we know that the high bits
15429     // are zero and SINT_TO_FP is better supported by the hardware.
15430     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15431   }
15432
15433   return SDValue();
15434 }
15435
15436 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15437                                         const X86TargetLowering *XTLI) {
15438   SDValue Op0 = N->getOperand(0);
15439   EVT InVT = Op0->getValueType(0);
15440
15441   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15442   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15443     DebugLoc dl = N->getDebugLoc();
15444     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15445     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15446     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15447   }
15448
15449   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15450   // a 32-bit target where SSE doesn't support i64->FP operations.
15451   if (Op0.getOpcode() == ISD::LOAD) {
15452     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15453     EVT VT = Ld->getValueType(0);
15454     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15455         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15456         !XTLI->getSubtarget()->is64Bit() &&
15457         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15458       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15459                                           Ld->getChain(), Op0, DAG);
15460       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15461       return FILDChain;
15462     }
15463   }
15464   return SDValue();
15465 }
15466
15467 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15468   EVT VT = N->getValueType(0);
15469
15470   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15471   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15472     DebugLoc dl = N->getDebugLoc();
15473     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15474     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15475     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15476   }
15477
15478   return SDValue();
15479 }
15480
15481 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15482 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15483                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15484   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15485   // the result is either zero or one (depending on the input carry bit).
15486   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15487   if (X86::isZeroNode(N->getOperand(0)) &&
15488       X86::isZeroNode(N->getOperand(1)) &&
15489       // We don't have a good way to replace an EFLAGS use, so only do this when
15490       // dead right now.
15491       SDValue(N, 1).use_empty()) {
15492     DebugLoc DL = N->getDebugLoc();
15493     EVT VT = N->getValueType(0);
15494     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15495     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15496                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15497                                            DAG.getConstant(X86::COND_B,MVT::i8),
15498                                            N->getOperand(2)),
15499                                DAG.getConstant(1, VT));
15500     return DCI.CombineTo(N, Res1, CarryOut);
15501   }
15502
15503   return SDValue();
15504 }
15505
15506 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15507 //      (add Y, (setne X, 0)) -> sbb -1, Y
15508 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15509 //      (sub (setne X, 0), Y) -> adc -1, Y
15510 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15511   DebugLoc DL = N->getDebugLoc();
15512
15513   // Look through ZExts.
15514   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15515   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15516     return SDValue();
15517
15518   SDValue SetCC = Ext.getOperand(0);
15519   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15520     return SDValue();
15521
15522   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15523   if (CC != X86::COND_E && CC != X86::COND_NE)
15524     return SDValue();
15525
15526   SDValue Cmp = SetCC.getOperand(1);
15527   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15528       !X86::isZeroNode(Cmp.getOperand(1)) ||
15529       !Cmp.getOperand(0).getValueType().isInteger())
15530     return SDValue();
15531
15532   SDValue CmpOp0 = Cmp.getOperand(0);
15533   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15534                                DAG.getConstant(1, CmpOp0.getValueType()));
15535
15536   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15537   if (CC == X86::COND_NE)
15538     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15539                        DL, OtherVal.getValueType(), OtherVal,
15540                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15541   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15542                      DL, OtherVal.getValueType(), OtherVal,
15543                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15544 }
15545
15546 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15547 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15548                                  const X86Subtarget *Subtarget) {
15549   EVT VT = N->getValueType(0);
15550   SDValue Op0 = N->getOperand(0);
15551   SDValue Op1 = N->getOperand(1);
15552
15553   // Try to synthesize horizontal adds from adds of shuffles.
15554   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15555        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15556       isHorizontalBinOp(Op0, Op1, true))
15557     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15558
15559   return OptimizeConditionalInDecrement(N, DAG);
15560 }
15561
15562 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15563                                  const X86Subtarget *Subtarget) {
15564   SDValue Op0 = N->getOperand(0);
15565   SDValue Op1 = N->getOperand(1);
15566
15567   // X86 can't encode an immediate LHS of a sub. See if we can push the
15568   // negation into a preceding instruction.
15569   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15570     // If the RHS of the sub is a XOR with one use and a constant, invert the
15571     // immediate. Then add one to the LHS of the sub so we can turn
15572     // X-Y -> X+~Y+1, saving one register.
15573     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15574         isa<ConstantSDNode>(Op1.getOperand(1))) {
15575       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15576       EVT VT = Op0.getValueType();
15577       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15578                                    Op1.getOperand(0),
15579                                    DAG.getConstant(~XorC, VT));
15580       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15581                          DAG.getConstant(C->getAPIntValue()+1, VT));
15582     }
15583   }
15584
15585   // Try to synthesize horizontal adds from adds of shuffles.
15586   EVT VT = N->getValueType(0);
15587   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15588        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15589       isHorizontalBinOp(Op0, Op1, true))
15590     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15591
15592   return OptimizeConditionalInDecrement(N, DAG);
15593 }
15594
15595 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15596                                              DAGCombinerInfo &DCI) const {
15597   SelectionDAG &DAG = DCI.DAG;
15598   switch (N->getOpcode()) {
15599   default: break;
15600   case ISD::EXTRACT_VECTOR_ELT:
15601     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15602   case ISD::VSELECT:
15603   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15604   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
15605   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
15606   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
15607   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
15608   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
15609   case ISD::SHL:
15610   case ISD::SRA:
15611   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
15612   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
15613   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
15614   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
15615   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
15616   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
15617   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
15618   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
15619   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
15620   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
15621   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
15622   case X86ISD::FXOR:
15623   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
15624   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
15625   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
15626   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
15627   case ISD::ANY_EXTEND:
15628   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
15629   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
15630   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
15631   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
15632   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
15633   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
15634   case X86ISD::SHUFP:       // Handle all target specific shuffles
15635   case X86ISD::PALIGN:
15636   case X86ISD::UNPCKH:
15637   case X86ISD::UNPCKL:
15638   case X86ISD::MOVHLPS:
15639   case X86ISD::MOVLHPS:
15640   case X86ISD::PSHUFD:
15641   case X86ISD::PSHUFHW:
15642   case X86ISD::PSHUFLW:
15643   case X86ISD::MOVSS:
15644   case X86ISD::MOVSD:
15645   case X86ISD::VPERMILP:
15646   case X86ISD::VPERM2X128:
15647   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
15648   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
15649   }
15650
15651   return SDValue();
15652 }
15653
15654 /// isTypeDesirableForOp - Return true if the target has native support for
15655 /// the specified value type and it is 'desirable' to use the type for the
15656 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
15657 /// instruction encodings are longer and some i16 instructions are slow.
15658 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
15659   if (!isTypeLegal(VT))
15660     return false;
15661   if (VT != MVT::i16)
15662     return true;
15663
15664   switch (Opc) {
15665   default:
15666     return true;
15667   case ISD::LOAD:
15668   case ISD::SIGN_EXTEND:
15669   case ISD::ZERO_EXTEND:
15670   case ISD::ANY_EXTEND:
15671   case ISD::SHL:
15672   case ISD::SRL:
15673   case ISD::SUB:
15674   case ISD::ADD:
15675   case ISD::MUL:
15676   case ISD::AND:
15677   case ISD::OR:
15678   case ISD::XOR:
15679     return false;
15680   }
15681 }
15682
15683 /// IsDesirableToPromoteOp - This method query the target whether it is
15684 /// beneficial for dag combiner to promote the specified node. If true, it
15685 /// should return the desired promotion type by reference.
15686 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
15687   EVT VT = Op.getValueType();
15688   if (VT != MVT::i16)
15689     return false;
15690
15691   bool Promote = false;
15692   bool Commute = false;
15693   switch (Op.getOpcode()) {
15694   default: break;
15695   case ISD::LOAD: {
15696     LoadSDNode *LD = cast<LoadSDNode>(Op);
15697     // If the non-extending load has a single use and it's not live out, then it
15698     // might be folded.
15699     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
15700                                                      Op.hasOneUse()*/) {
15701       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15702              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
15703         // The only case where we'd want to promote LOAD (rather then it being
15704         // promoted as an operand is when it's only use is liveout.
15705         if (UI->getOpcode() != ISD::CopyToReg)
15706           return false;
15707       }
15708     }
15709     Promote = true;
15710     break;
15711   }
15712   case ISD::SIGN_EXTEND:
15713   case ISD::ZERO_EXTEND:
15714   case ISD::ANY_EXTEND:
15715     Promote = true;
15716     break;
15717   case ISD::SHL:
15718   case ISD::SRL: {
15719     SDValue N0 = Op.getOperand(0);
15720     // Look out for (store (shl (load), x)).
15721     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15722       return false;
15723     Promote = true;
15724     break;
15725   }
15726   case ISD::ADD:
15727   case ISD::MUL:
15728   case ISD::AND:
15729   case ISD::OR:
15730   case ISD::XOR:
15731     Commute = true;
15732     // fallthrough
15733   case ISD::SUB: {
15734     SDValue N0 = Op.getOperand(0);
15735     SDValue N1 = Op.getOperand(1);
15736     if (!Commute && MayFoldLoad(N1))
15737       return false;
15738     // Avoid disabling potential load folding opportunities.
15739     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15740       return false;
15741     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15742       return false;
15743     Promote = true;
15744   }
15745   }
15746
15747   PVT = MVT::i32;
15748   return Promote;
15749 }
15750
15751 //===----------------------------------------------------------------------===//
15752 //                           X86 Inline Assembly Support
15753 //===----------------------------------------------------------------------===//
15754
15755 namespace {
15756   // Helper to match a string separated by whitespace.
15757   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15758     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15759
15760     for (unsigned i = 0, e = args.size(); i != e; ++i) {
15761       StringRef piece(*args[i]);
15762       if (!s.startswith(piece)) // Check if the piece matches.
15763         return false;
15764
15765       s = s.substr(piece.size());
15766       StringRef::size_type pos = s.find_first_not_of(" \t");
15767       if (pos == 0) // We matched a prefix.
15768         return false;
15769
15770       s = s.substr(pos);
15771     }
15772
15773     return s.empty();
15774   }
15775   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15776 }
15777
15778 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15779   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15780
15781   std::string AsmStr = IA->getAsmString();
15782
15783   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15784   if (!Ty || Ty->getBitWidth() % 16 != 0)
15785     return false;
15786
15787   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15788   SmallVector<StringRef, 4> AsmPieces;
15789   SplitString(AsmStr, AsmPieces, ";\n");
15790
15791   switch (AsmPieces.size()) {
15792   default: return false;
15793   case 1:
15794     // FIXME: this should verify that we are targeting a 486 or better.  If not,
15795     // we will turn this bswap into something that will be lowered to logical
15796     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
15797     // lower so don't worry about this.
15798     // bswap $0
15799     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15800         matchAsm(AsmPieces[0], "bswapl", "$0") ||
15801         matchAsm(AsmPieces[0], "bswapq", "$0") ||
15802         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15803         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15804         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15805       // No need to check constraints, nothing other than the equivalent of
15806       // "=r,0" would be valid here.
15807       return IntrinsicLowering::LowerToByteSwap(CI);
15808     }
15809
15810     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15811     if (CI->getType()->isIntegerTy(16) &&
15812         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15813         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15814          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15815       AsmPieces.clear();
15816       const std::string &ConstraintsStr = IA->getConstraintString();
15817       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15818       std::sort(AsmPieces.begin(), AsmPieces.end());
15819       if (AsmPieces.size() == 4 &&
15820           AsmPieces[0] == "~{cc}" &&
15821           AsmPieces[1] == "~{dirflag}" &&
15822           AsmPieces[2] == "~{flags}" &&
15823           AsmPieces[3] == "~{fpsr}")
15824       return IntrinsicLowering::LowerToByteSwap(CI);
15825     }
15826     break;
15827   case 3:
15828     if (CI->getType()->isIntegerTy(32) &&
15829         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15830         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15831         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15832         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15833       AsmPieces.clear();
15834       const std::string &ConstraintsStr = IA->getConstraintString();
15835       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15836       std::sort(AsmPieces.begin(), AsmPieces.end());
15837       if (AsmPieces.size() == 4 &&
15838           AsmPieces[0] == "~{cc}" &&
15839           AsmPieces[1] == "~{dirflag}" &&
15840           AsmPieces[2] == "~{flags}" &&
15841           AsmPieces[3] == "~{fpsr}")
15842         return IntrinsicLowering::LowerToByteSwap(CI);
15843     }
15844
15845     if (CI->getType()->isIntegerTy(64)) {
15846       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15847       if (Constraints.size() >= 2 &&
15848           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15849           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15850         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15851         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15852             matchAsm(AsmPieces[1], "bswap", "%edx") &&
15853             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15854           return IntrinsicLowering::LowerToByteSwap(CI);
15855       }
15856     }
15857     break;
15858   }
15859   return false;
15860 }
15861
15862
15863
15864 /// getConstraintType - Given a constraint letter, return the type of
15865 /// constraint it is for this target.
15866 X86TargetLowering::ConstraintType
15867 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15868   if (Constraint.size() == 1) {
15869     switch (Constraint[0]) {
15870     case 'R':
15871     case 'q':
15872     case 'Q':
15873     case 'f':
15874     case 't':
15875     case 'u':
15876     case 'y':
15877     case 'x':
15878     case 'Y':
15879     case 'l':
15880       return C_RegisterClass;
15881     case 'a':
15882     case 'b':
15883     case 'c':
15884     case 'd':
15885     case 'S':
15886     case 'D':
15887     case 'A':
15888       return C_Register;
15889     case 'I':
15890     case 'J':
15891     case 'K':
15892     case 'L':
15893     case 'M':
15894     case 'N':
15895     case 'G':
15896     case 'C':
15897     case 'e':
15898     case 'Z':
15899       return C_Other;
15900     default:
15901       break;
15902     }
15903   }
15904   return TargetLowering::getConstraintType(Constraint);
15905 }
15906
15907 /// Examine constraint type and operand type and determine a weight value.
15908 /// This object must already have been set up with the operand type
15909 /// and the current alternative constraint selected.
15910 TargetLowering::ConstraintWeight
15911   X86TargetLowering::getSingleConstraintMatchWeight(
15912     AsmOperandInfo &info, const char *constraint) const {
15913   ConstraintWeight weight = CW_Invalid;
15914   Value *CallOperandVal = info.CallOperandVal;
15915     // If we don't have a value, we can't do a match,
15916     // but allow it at the lowest weight.
15917   if (CallOperandVal == NULL)
15918     return CW_Default;
15919   Type *type = CallOperandVal->getType();
15920   // Look at the constraint type.
15921   switch (*constraint) {
15922   default:
15923     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15924   case 'R':
15925   case 'q':
15926   case 'Q':
15927   case 'a':
15928   case 'b':
15929   case 'c':
15930   case 'd':
15931   case 'S':
15932   case 'D':
15933   case 'A':
15934     if (CallOperandVal->getType()->isIntegerTy())
15935       weight = CW_SpecificReg;
15936     break;
15937   case 'f':
15938   case 't':
15939   case 'u':
15940       if (type->isFloatingPointTy())
15941         weight = CW_SpecificReg;
15942       break;
15943   case 'y':
15944       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15945         weight = CW_SpecificReg;
15946       break;
15947   case 'x':
15948   case 'Y':
15949     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15950         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15951       weight = CW_Register;
15952     break;
15953   case 'I':
15954     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15955       if (C->getZExtValue() <= 31)
15956         weight = CW_Constant;
15957     }
15958     break;
15959   case 'J':
15960     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15961       if (C->getZExtValue() <= 63)
15962         weight = CW_Constant;
15963     }
15964     break;
15965   case 'K':
15966     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15967       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15968         weight = CW_Constant;
15969     }
15970     break;
15971   case 'L':
15972     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15973       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15974         weight = CW_Constant;
15975     }
15976     break;
15977   case 'M':
15978     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15979       if (C->getZExtValue() <= 3)
15980         weight = CW_Constant;
15981     }
15982     break;
15983   case 'N':
15984     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15985       if (C->getZExtValue() <= 0xff)
15986         weight = CW_Constant;
15987     }
15988     break;
15989   case 'G':
15990   case 'C':
15991     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15992       weight = CW_Constant;
15993     }
15994     break;
15995   case 'e':
15996     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15997       if ((C->getSExtValue() >= -0x80000000LL) &&
15998           (C->getSExtValue() <= 0x7fffffffLL))
15999         weight = CW_Constant;
16000     }
16001     break;
16002   case 'Z':
16003     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16004       if (C->getZExtValue() <= 0xffffffff)
16005         weight = CW_Constant;
16006     }
16007     break;
16008   }
16009   return weight;
16010 }
16011
16012 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16013 /// with another that has more specific requirements based on the type of the
16014 /// corresponding operand.
16015 const char *X86TargetLowering::
16016 LowerXConstraint(EVT ConstraintVT) const {
16017   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16018   // 'f' like normal targets.
16019   if (ConstraintVT.isFloatingPoint()) {
16020     if (Subtarget->hasSSE2())
16021       return "Y";
16022     if (Subtarget->hasSSE1())
16023       return "x";
16024   }
16025
16026   return TargetLowering::LowerXConstraint(ConstraintVT);
16027 }
16028
16029 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16030 /// vector.  If it is invalid, don't add anything to Ops.
16031 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16032                                                      std::string &Constraint,
16033                                                      std::vector<SDValue>&Ops,
16034                                                      SelectionDAG &DAG) const {
16035   SDValue Result(0, 0);
16036
16037   // Only support length 1 constraints for now.
16038   if (Constraint.length() > 1) return;
16039
16040   char ConstraintLetter = Constraint[0];
16041   switch (ConstraintLetter) {
16042   default: break;
16043   case 'I':
16044     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16045       if (C->getZExtValue() <= 31) {
16046         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16047         break;
16048       }
16049     }
16050     return;
16051   case 'J':
16052     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16053       if (C->getZExtValue() <= 63) {
16054         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16055         break;
16056       }
16057     }
16058     return;
16059   case 'K':
16060     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16061       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16062         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16063         break;
16064       }
16065     }
16066     return;
16067   case 'N':
16068     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16069       if (C->getZExtValue() <= 255) {
16070         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16071         break;
16072       }
16073     }
16074     return;
16075   case 'e': {
16076     // 32-bit signed value
16077     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16078       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16079                                            C->getSExtValue())) {
16080         // Widen to 64 bits here to get it sign extended.
16081         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16082         break;
16083       }
16084     // FIXME gcc accepts some relocatable values here too, but only in certain
16085     // memory models; it's complicated.
16086     }
16087     return;
16088   }
16089   case 'Z': {
16090     // 32-bit unsigned value
16091     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16092       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16093                                            C->getZExtValue())) {
16094         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16095         break;
16096       }
16097     }
16098     // FIXME gcc accepts some relocatable values here too, but only in certain
16099     // memory models; it's complicated.
16100     return;
16101   }
16102   case 'i': {
16103     // Literal immediates are always ok.
16104     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16105       // Widen to 64 bits here to get it sign extended.
16106       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16107       break;
16108     }
16109
16110     // In any sort of PIC mode addresses need to be computed at runtime by
16111     // adding in a register or some sort of table lookup.  These can't
16112     // be used as immediates.
16113     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16114       return;
16115
16116     // If we are in non-pic codegen mode, we allow the address of a global (with
16117     // an optional displacement) to be used with 'i'.
16118     GlobalAddressSDNode *GA = 0;
16119     int64_t Offset = 0;
16120
16121     // Match either (GA), (GA+C), (GA+C1+C2), etc.
16122     while (1) {
16123       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16124         Offset += GA->getOffset();
16125         break;
16126       } else if (Op.getOpcode() == ISD::ADD) {
16127         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16128           Offset += C->getZExtValue();
16129           Op = Op.getOperand(0);
16130           continue;
16131         }
16132       } else if (Op.getOpcode() == ISD::SUB) {
16133         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16134           Offset += -C->getZExtValue();
16135           Op = Op.getOperand(0);
16136           continue;
16137         }
16138       }
16139
16140       // Otherwise, this isn't something we can handle, reject it.
16141       return;
16142     }
16143
16144     const GlobalValue *GV = GA->getGlobal();
16145     // If we require an extra load to get this address, as in PIC mode, we
16146     // can't accept it.
16147     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16148                                                         getTargetMachine())))
16149       return;
16150
16151     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16152                                         GA->getValueType(0), Offset);
16153     break;
16154   }
16155   }
16156
16157   if (Result.getNode()) {
16158     Ops.push_back(Result);
16159     return;
16160   }
16161   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16162 }
16163
16164 std::pair<unsigned, const TargetRegisterClass*>
16165 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16166                                                 EVT VT) const {
16167   // First, see if this is a constraint that directly corresponds to an LLVM
16168   // register class.
16169   if (Constraint.size() == 1) {
16170     // GCC Constraint Letters
16171     switch (Constraint[0]) {
16172     default: break;
16173       // TODO: Slight differences here in allocation order and leaving
16174       // RIP in the class. Do they matter any more here than they do
16175       // in the normal allocation?
16176     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16177       if (Subtarget->is64Bit()) {
16178         if (VT == MVT::i32 || VT == MVT::f32)
16179           return std::make_pair(0U, &X86::GR32RegClass);
16180         if (VT == MVT::i16)
16181           return std::make_pair(0U, &X86::GR16RegClass);
16182         if (VT == MVT::i8 || VT == MVT::i1)
16183           return std::make_pair(0U, &X86::GR8RegClass);
16184         if (VT == MVT::i64 || VT == MVT::f64)
16185           return std::make_pair(0U, &X86::GR64RegClass);
16186         break;
16187       }
16188       // 32-bit fallthrough
16189     case 'Q':   // Q_REGS
16190       if (VT == MVT::i32 || VT == MVT::f32)
16191         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16192       if (VT == MVT::i16)
16193         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16194       if (VT == MVT::i8 || VT == MVT::i1)
16195         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16196       if (VT == MVT::i64)
16197         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16198       break;
16199     case 'r':   // GENERAL_REGS
16200     case 'l':   // INDEX_REGS
16201       if (VT == MVT::i8 || VT == MVT::i1)
16202         return std::make_pair(0U, &X86::GR8RegClass);
16203       if (VT == MVT::i16)
16204         return std::make_pair(0U, &X86::GR16RegClass);
16205       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16206         return std::make_pair(0U, &X86::GR32RegClass);
16207       return std::make_pair(0U, &X86::GR64RegClass);
16208     case 'R':   // LEGACY_REGS
16209       if (VT == MVT::i8 || VT == MVT::i1)
16210         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16211       if (VT == MVT::i16)
16212         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16213       if (VT == MVT::i32 || !Subtarget->is64Bit())
16214         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16215       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16216     case 'f':  // FP Stack registers.
16217       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16218       // value to the correct fpstack register class.
16219       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16220         return std::make_pair(0U, &X86::RFP32RegClass);
16221       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16222         return std::make_pair(0U, &X86::RFP64RegClass);
16223       return std::make_pair(0U, &X86::RFP80RegClass);
16224     case 'y':   // MMX_REGS if MMX allowed.
16225       if (!Subtarget->hasMMX()) break;
16226       return std::make_pair(0U, &X86::VR64RegClass);
16227     case 'Y':   // SSE_REGS if SSE2 allowed
16228       if (!Subtarget->hasSSE2()) break;
16229       // FALL THROUGH.
16230     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16231       if (!Subtarget->hasSSE1()) break;
16232
16233       switch (VT.getSimpleVT().SimpleTy) {
16234       default: break;
16235       // Scalar SSE types.
16236       case MVT::f32:
16237       case MVT::i32:
16238         return std::make_pair(0U, &X86::FR32RegClass);
16239       case MVT::f64:
16240       case MVT::i64:
16241         return std::make_pair(0U, &X86::FR64RegClass);
16242       // Vector types.
16243       case MVT::v16i8:
16244       case MVT::v8i16:
16245       case MVT::v4i32:
16246       case MVT::v2i64:
16247       case MVT::v4f32:
16248       case MVT::v2f64:
16249         return std::make_pair(0U, &X86::VR128RegClass);
16250       // AVX types.
16251       case MVT::v32i8:
16252       case MVT::v16i16:
16253       case MVT::v8i32:
16254       case MVT::v4i64:
16255       case MVT::v8f32:
16256       case MVT::v4f64:
16257         return std::make_pair(0U, &X86::VR256RegClass);
16258       }
16259       break;
16260     }
16261   }
16262
16263   // Use the default implementation in TargetLowering to convert the register
16264   // constraint into a member of a register class.
16265   std::pair<unsigned, const TargetRegisterClass*> Res;
16266   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16267
16268   // Not found as a standard register?
16269   if (Res.second == 0) {
16270     // Map st(0) -> st(7) -> ST0
16271     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16272         tolower(Constraint[1]) == 's' &&
16273         tolower(Constraint[2]) == 't' &&
16274         Constraint[3] == '(' &&
16275         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16276         Constraint[5] == ')' &&
16277         Constraint[6] == '}') {
16278
16279       Res.first = X86::ST0+Constraint[4]-'0';
16280       Res.second = &X86::RFP80RegClass;
16281       return Res;
16282     }
16283
16284     // GCC allows "st(0)" to be called just plain "st".
16285     if (StringRef("{st}").equals_lower(Constraint)) {
16286       Res.first = X86::ST0;
16287       Res.second = &X86::RFP80RegClass;
16288       return Res;
16289     }
16290
16291     // flags -> EFLAGS
16292     if (StringRef("{flags}").equals_lower(Constraint)) {
16293       Res.first = X86::EFLAGS;
16294       Res.second = &X86::CCRRegClass;
16295       return Res;
16296     }
16297
16298     // 'A' means EAX + EDX.
16299     if (Constraint == "A") {
16300       Res.first = X86::EAX;
16301       Res.second = &X86::GR32_ADRegClass;
16302       return Res;
16303     }
16304     return Res;
16305   }
16306
16307   // Otherwise, check to see if this is a register class of the wrong value
16308   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16309   // turn into {ax},{dx}.
16310   if (Res.second->hasType(VT))
16311     return Res;   // Correct type already, nothing to do.
16312
16313   // All of the single-register GCC register classes map their values onto
16314   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16315   // really want an 8-bit or 32-bit register, map to the appropriate register
16316   // class and return the appropriate register.
16317   if (Res.second == &X86::GR16RegClass) {
16318     if (VT == MVT::i8) {
16319       unsigned DestReg = 0;
16320       switch (Res.first) {
16321       default: break;
16322       case X86::AX: DestReg = X86::AL; break;
16323       case X86::DX: DestReg = X86::DL; break;
16324       case X86::CX: DestReg = X86::CL; break;
16325       case X86::BX: DestReg = X86::BL; break;
16326       }
16327       if (DestReg) {
16328         Res.first = DestReg;
16329         Res.second = &X86::GR8RegClass;
16330       }
16331     } else if (VT == MVT::i32) {
16332       unsigned DestReg = 0;
16333       switch (Res.first) {
16334       default: break;
16335       case X86::AX: DestReg = X86::EAX; break;
16336       case X86::DX: DestReg = X86::EDX; break;
16337       case X86::CX: DestReg = X86::ECX; break;
16338       case X86::BX: DestReg = X86::EBX; break;
16339       case X86::SI: DestReg = X86::ESI; break;
16340       case X86::DI: DestReg = X86::EDI; break;
16341       case X86::BP: DestReg = X86::EBP; break;
16342       case X86::SP: DestReg = X86::ESP; break;
16343       }
16344       if (DestReg) {
16345         Res.first = DestReg;
16346         Res.second = &X86::GR32RegClass;
16347       }
16348     } else if (VT == MVT::i64) {
16349       unsigned DestReg = 0;
16350       switch (Res.first) {
16351       default: break;
16352       case X86::AX: DestReg = X86::RAX; break;
16353       case X86::DX: DestReg = X86::RDX; break;
16354       case X86::CX: DestReg = X86::RCX; break;
16355       case X86::BX: DestReg = X86::RBX; break;
16356       case X86::SI: DestReg = X86::RSI; break;
16357       case X86::DI: DestReg = X86::RDI; break;
16358       case X86::BP: DestReg = X86::RBP; break;
16359       case X86::SP: DestReg = X86::RSP; break;
16360       }
16361       if (DestReg) {
16362         Res.first = DestReg;
16363         Res.second = &X86::GR64RegClass;
16364       }
16365     }
16366   } else if (Res.second == &X86::FR32RegClass ||
16367              Res.second == &X86::FR64RegClass ||
16368              Res.second == &X86::VR128RegClass) {
16369     // Handle references to XMM physical registers that got mapped into the
16370     // wrong class.  This can happen with constraints like {xmm0} where the
16371     // target independent register mapper will just pick the first match it can
16372     // find, ignoring the required type.
16373
16374     if (VT == MVT::f32 || VT == MVT::i32)
16375       Res.second = &X86::FR32RegClass;
16376     else if (VT == MVT::f64 || VT == MVT::i64)
16377       Res.second = &X86::FR64RegClass;
16378     else if (X86::VR128RegClass.hasType(VT))
16379       Res.second = &X86::VR128RegClass;
16380     else if (X86::VR256RegClass.hasType(VT))
16381       Res.second = &X86::VR256RegClass;
16382   }
16383
16384   return Res;
16385 }