029b8003b8ca342d96efde8dd474b44ab85ae288
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "X86.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 using namespace llvm;
53
54 STATISTIC(NumTailCalls, "Number of tail calls");
55
56 // Forward declarations.
57 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
58                        SDValue V2);
59
60 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
61 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
62 /// simple subregister reference.  Idx is an index in the 128 bits we
63 /// want.  It need not be aligned to a 128-bit bounday.  That makes
64 /// lowering EXTRACT_VECTOR_ELT operations easier.
65 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
66                                    SelectionDAG &DAG, DebugLoc dl) {
67   EVT VT = Vec.getValueType();
68   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
69   EVT ElVT = VT.getVectorElementType();
70   unsigned Factor = VT.getSizeInBits()/128;
71   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72                                   VT.getVectorNumElements()/Factor);
73
74   // Extract from UNDEF is UNDEF.
75   if (Vec.getOpcode() == ISD::UNDEF)
76     return DAG.getUNDEF(ResultVT);
77
78   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
79   // we can match to VEXTRACTF128.
80   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
81
82   // This is the index of the first element of the 128-bit chunk
83   // we want.
84   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
85                                * ElemsPerChunk);
86
87   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
88   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
89                                VecIdx);
90
91   return Result;
92 }
93
94 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
95 /// sets things up to match to an AVX VINSERTF128 instruction or a
96 /// simple superregister reference.  Idx is an index in the 128 bits
97 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
98 /// lowering INSERT_VECTOR_ELT operations easier.
99 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
100                                   unsigned IdxVal, SelectionDAG &DAG,
101                                   DebugLoc dl) {
102   EVT VT = Vec.getValueType();
103   assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
104
105   EVT ElVT = VT.getVectorElementType();
106   EVT ResultVT = Result.getValueType();
107
108   // Insert the relevant 128 bits.
109   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
110
111   // This is the index of the first element of the 128-bit chunk
112   // we want.
113   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
114                                * ElemsPerChunk);
115
116   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
117   Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
118                        VecIdx);
119   return Result;
120 }
121
122 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
123 /// instructions. This is used because creating CONCAT_VECTOR nodes of
124 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
125 /// large BUILD_VECTORS.
126 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
127                                    unsigned NumElems, SelectionDAG &DAG,
128                                    DebugLoc dl) {
129   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
130   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
131 }
132
133 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
134   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
135   bool is64Bit = Subtarget->is64Bit();
136
137   if (Subtarget->isTargetEnvMacho()) {
138     if (is64Bit)
139       return new X8664_MachoTargetObjectFile();
140     return new TargetLoweringObjectFileMachO();
141   }
142
143   if (Subtarget->isTargetELF())
144     return new TargetLoweringObjectFileELF();
145   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
146     return new TargetLoweringObjectFileCOFF();
147   llvm_unreachable("unknown subtarget type");
148 }
149
150 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
151   : TargetLowering(TM, createTLOF(TM)) {
152   Subtarget = &TM.getSubtarget<X86Subtarget>();
153   X86ScalarSSEf64 = Subtarget->hasSSE2();
154   X86ScalarSSEf32 = Subtarget->hasSSE1();
155   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
156
157   RegInfo = TM.getRegisterInfo();
158   TD = getTargetData();
159
160   // Set up the TargetLowering object.
161   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
162
163   // X86 is weird, it always uses i8 for shift amounts and setcc results.
164   setBooleanContents(ZeroOrOneBooleanContent);
165   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
166   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
167
168   // For 64-bit since we have so many registers use the ILP scheduler, for
169   // 32-bit code use the register pressure specific scheduling.
170   // For Atom, always use ILP scheduling.
171   if (Subtarget->isAtom()) 
172     setSchedulingPreference(Sched::ILP);
173   else if (Subtarget->is64Bit())
174     setSchedulingPreference(Sched::ILP);
175   else
176     setSchedulingPreference(Sched::RegPressure);
177   setStackPointerRegisterToSaveRestore(X86StackPtr);
178
179   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
180     // Setup Windows compiler runtime calls.
181     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
182     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
183     setLibcallName(RTLIB::SREM_I64, "_allrem");
184     setLibcallName(RTLIB::UREM_I64, "_aullrem");
185     setLibcallName(RTLIB::MUL_I64, "_allmul");
186     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
187     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
188     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
189     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
190     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
191
192     // The _ftol2 runtime function has an unusual calling conv, which
193     // is modeled by a special pseudo-instruction.
194     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
195     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
196     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
197     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
198   }
199
200   if (Subtarget->isTargetDarwin()) {
201     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
202     setUseUnderscoreSetJmp(false);
203     setUseUnderscoreLongJmp(false);
204   } else if (Subtarget->isTargetMingw()) {
205     // MS runtime is weird: it exports _setjmp, but longjmp!
206     setUseUnderscoreSetJmp(true);
207     setUseUnderscoreLongJmp(false);
208   } else {
209     setUseUnderscoreSetJmp(true);
210     setUseUnderscoreLongJmp(true);
211   }
212
213   // Set up the register classes.
214   addRegisterClass(MVT::i8, &X86::GR8RegClass);
215   addRegisterClass(MVT::i16, &X86::GR16RegClass);
216   addRegisterClass(MVT::i32, &X86::GR32RegClass);
217   if (Subtarget->is64Bit())
218     addRegisterClass(MVT::i64, &X86::GR64RegClass);
219
220   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
221
222   // We don't accept any truncstore of integer registers.
223   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
224   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
225   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
226   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
227   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
228   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
229
230   // SETOEQ and SETUNE require checking two conditions.
231   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
232   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
233   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
234   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
235   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
236   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
237
238   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
239   // operation.
240   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
241   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
242   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
243
244   if (Subtarget->is64Bit()) {
245     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
246     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
247   } else if (!TM.Options.UseSoftFloat) {
248     // We have an algorithm for SSE2->double, and we turn this into a
249     // 64-bit FILD followed by conditional FADD for other targets.
250     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
251     // We have an algorithm for SSE2, and we turn this into a 64-bit
252     // FILD for other targets.
253     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
254   }
255
256   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
257   // this operation.
258   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
259   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
260
261   if (!TM.Options.UseSoftFloat) {
262     // SSE has no i16 to fp conversion, only i32
263     if (X86ScalarSSEf32) {
264       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
265       // f32 and f64 cases are Legal, f80 case is not
266       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
267     } else {
268       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
269       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
270     }
271   } else {
272     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
273     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
274   }
275
276   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
277   // are Legal, f80 is custom lowered.
278   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
279   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
280
281   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
282   // this operation.
283   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
284   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
285
286   if (X86ScalarSSEf32) {
287     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
288     // f32 and f64 cases are Legal, f80 case is not
289     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
290   } else {
291     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
292     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
293   }
294
295   // Handle FP_TO_UINT by promoting the destination to a larger signed
296   // conversion.
297   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
298   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
299   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
300
301   if (Subtarget->is64Bit()) {
302     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
303     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
304   } else if (!TM.Options.UseSoftFloat) {
305     // Since AVX is a superset of SSE3, only check for SSE here.
306     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
307       // Expand FP_TO_UINT into a select.
308       // FIXME: We would like to use a Custom expander here eventually to do
309       // the optimal thing for SSE vs. the default expansion in the legalizer.
310       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
311     else
312       // With SSE3 we can use fisttpll to convert to a signed i64; without
313       // SSE, we're stuck with a fistpll.
314       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
315   }
316
317   if (isTargetFTOL()) {
318     // Use the _ftol2 runtime function, which has a pseudo-instruction
319     // to handle its weird calling convention.
320     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
321   }
322
323   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
324   if (!X86ScalarSSEf64) {
325     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
326     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
327     if (Subtarget->is64Bit()) {
328       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
329       // Without SSE, i64->f64 goes through memory.
330       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
331     }
332   }
333
334   // Scalar integer divide and remainder are lowered to use operations that
335   // produce two results, to match the available instructions. This exposes
336   // the two-result form to trivial CSE, which is able to combine x/y and x%y
337   // into a single instruction.
338   //
339   // Scalar integer multiply-high is also lowered to use two-result
340   // operations, to match the available instructions. However, plain multiply
341   // (low) operations are left as Legal, as there are single-result
342   // instructions for this in x86. Using the two-result multiply instructions
343   // when both high and low results are needed must be arranged by dagcombine.
344   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
345     MVT VT = IntVTs[i];
346     setOperationAction(ISD::MULHS, VT, Expand);
347     setOperationAction(ISD::MULHU, VT, Expand);
348     setOperationAction(ISD::SDIV, VT, Expand);
349     setOperationAction(ISD::UDIV, VT, Expand);
350     setOperationAction(ISD::SREM, VT, Expand);
351     setOperationAction(ISD::UREM, VT, Expand);
352
353     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
354     setOperationAction(ISD::ADDC, VT, Custom);
355     setOperationAction(ISD::ADDE, VT, Custom);
356     setOperationAction(ISD::SUBC, VT, Custom);
357     setOperationAction(ISD::SUBE, VT, Custom);
358   }
359
360   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
361   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
362   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
363   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
364   if (Subtarget->is64Bit())
365     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
366   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
367   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
368   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
369   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
370   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
371   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
372   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
373   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
374
375   // Promote the i8 variants and force them on up to i32 which has a shorter
376   // encoding.
377   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
378   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
379   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
380   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
381   if (Subtarget->hasBMI()) {
382     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
383     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
384     if (Subtarget->is64Bit())
385       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
386   } else {
387     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
388     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
391   }
392
393   if (Subtarget->hasLZCNT()) {
394     // When promoting the i8 variants, force them to i32 for a shorter
395     // encoding.
396     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
397     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
398     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
399     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
400     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
401     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
402     if (Subtarget->is64Bit())
403       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
404   } else {
405     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
406     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
407     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
408     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
409     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
410     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
411     if (Subtarget->is64Bit()) {
412       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
413       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
414     }
415   }
416
417   if (Subtarget->hasPOPCNT()) {
418     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
419   } else {
420     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
421     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
422     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
423     if (Subtarget->is64Bit())
424       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
425   }
426
427   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
428   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
429
430   // These should be promoted to a larger select which is supported.
431   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
432   // X86 wants to expand cmov itself.
433   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
434   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
435   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
436   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
437   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
438   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
439   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
440   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
441   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
442   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
443   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
444   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
445   if (Subtarget->is64Bit()) {
446     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
447     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
448   }
449   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
450
451   // Darwin ABI issue.
452   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
453   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
454   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
455   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
456   if (Subtarget->is64Bit())
457     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
458   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
459   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
460   if (Subtarget->is64Bit()) {
461     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
462     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
463     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
464     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
465     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
466   }
467   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
468   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
469   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
470   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
471   if (Subtarget->is64Bit()) {
472     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
473     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
474     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
475   }
476
477   if (Subtarget->hasSSE1())
478     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
479
480   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
481   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
482
483   // On X86 and X86-64, atomic operations are lowered to locked instructions.
484   // Locked instructions, in turn, have implicit fence semantics (all memory
485   // operations are flushed before issuing the locked instruction, and they
486   // are not buffered), so we can fold away the common pattern of
487   // fence-atomic-fence.
488   setShouldFoldAtomicFences(true);
489
490   // Expand certain atomics
491   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
492     MVT VT = IntVTs[i];
493     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
494     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
495     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
496   }
497
498   if (!Subtarget->is64Bit()) {
499     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
500     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
501     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
503     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
504     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
505     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
507   }
508
509   if (Subtarget->hasCmpxchg16b()) {
510     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
511   }
512
513   // FIXME - use subtarget debug flags
514   if (!Subtarget->isTargetDarwin() &&
515       !Subtarget->isTargetELF() &&
516       !Subtarget->isTargetCygMing()) {
517     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
518   }
519
520   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
521   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
522   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
523   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
524   if (Subtarget->is64Bit()) {
525     setExceptionPointerRegister(X86::RAX);
526     setExceptionSelectorRegister(X86::RDX);
527   } else {
528     setExceptionPointerRegister(X86::EAX);
529     setExceptionSelectorRegister(X86::EDX);
530   }
531   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
532   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
533
534   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
535   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
536
537   setOperationAction(ISD::TRAP, MVT::Other, Legal);
538
539   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
540   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
541   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
542   if (Subtarget->is64Bit()) {
543     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
544     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
545   } else {
546     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
547     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
548   }
549
550   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
551   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
552
553   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
554     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
555                        MVT::i64 : MVT::i32, Custom);
556   else if (TM.Options.EnableSegmentedStacks)
557     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
558                        MVT::i64 : MVT::i32, Custom);
559   else
560     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
561                        MVT::i64 : MVT::i32, Expand);
562
563   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
564     // f32 and f64 use SSE.
565     // Set up the FP register classes.
566     addRegisterClass(MVT::f32, &X86::FR32RegClass);
567     addRegisterClass(MVT::f64, &X86::FR64RegClass);
568
569     // Use ANDPD to simulate FABS.
570     setOperationAction(ISD::FABS , MVT::f64, Custom);
571     setOperationAction(ISD::FABS , MVT::f32, Custom);
572
573     // Use XORP to simulate FNEG.
574     setOperationAction(ISD::FNEG , MVT::f64, Custom);
575     setOperationAction(ISD::FNEG , MVT::f32, Custom);
576
577     // Use ANDPD and ORPD to simulate FCOPYSIGN.
578     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
579     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
580
581     // Lower this to FGETSIGNx86 plus an AND.
582     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
583     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
584
585     // We don't support sin/cos/fmod
586     setOperationAction(ISD::FSIN , MVT::f64, Expand);
587     setOperationAction(ISD::FCOS , MVT::f64, Expand);
588     setOperationAction(ISD::FSIN , MVT::f32, Expand);
589     setOperationAction(ISD::FCOS , MVT::f32, Expand);
590
591     // Expand FP immediates into loads from the stack, except for the special
592     // cases we handle.
593     addLegalFPImmediate(APFloat(+0.0)); // xorpd
594     addLegalFPImmediate(APFloat(+0.0f)); // xorps
595   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
596     // Use SSE for f32, x87 for f64.
597     // Set up the FP register classes.
598     addRegisterClass(MVT::f32, &X86::FR32RegClass);
599     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
600
601     // Use ANDPS to simulate FABS.
602     setOperationAction(ISD::FABS , MVT::f32, Custom);
603
604     // Use XORP to simulate FNEG.
605     setOperationAction(ISD::FNEG , MVT::f32, Custom);
606
607     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
608
609     // Use ANDPS and ORPS to simulate FCOPYSIGN.
610     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
611     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
612
613     // We don't support sin/cos/fmod
614     setOperationAction(ISD::FSIN , MVT::f32, Expand);
615     setOperationAction(ISD::FCOS , MVT::f32, Expand);
616
617     // Special cases we handle for FP constants.
618     addLegalFPImmediate(APFloat(+0.0f)); // xorps
619     addLegalFPImmediate(APFloat(+0.0)); // FLD0
620     addLegalFPImmediate(APFloat(+1.0)); // FLD1
621     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
622     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
623
624     if (!TM.Options.UnsafeFPMath) {
625       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
626       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
627     }
628   } else if (!TM.Options.UseSoftFloat) {
629     // f32 and f64 in x87.
630     // Set up the FP register classes.
631     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
632     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
633
634     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
635     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
636     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
637     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
638
639     if (!TM.Options.UnsafeFPMath) {
640       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
641       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
642     }
643     addLegalFPImmediate(APFloat(+0.0)); // FLD0
644     addLegalFPImmediate(APFloat(+1.0)); // FLD1
645     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
646     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
647     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
648     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
649     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
650     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
651   }
652
653   // We don't support FMA.
654   setOperationAction(ISD::FMA, MVT::f64, Expand);
655   setOperationAction(ISD::FMA, MVT::f32, Expand);
656
657   // Long double always uses X87.
658   if (!TM.Options.UseSoftFloat) {
659     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
660     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
661     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
662     {
663       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
664       addLegalFPImmediate(TmpFlt);  // FLD0
665       TmpFlt.changeSign();
666       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
667
668       bool ignored;
669       APFloat TmpFlt2(+1.0);
670       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
671                       &ignored);
672       addLegalFPImmediate(TmpFlt2);  // FLD1
673       TmpFlt2.changeSign();
674       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
675     }
676
677     if (!TM.Options.UnsafeFPMath) {
678       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
679       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
680     }
681
682     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
683     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
684     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
685     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
686     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
687     setOperationAction(ISD::FMA, MVT::f80, Expand);
688   }
689
690   // Always use a library call for pow.
691   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
692   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
693   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
694
695   setOperationAction(ISD::FLOG, MVT::f80, Expand);
696   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
697   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
698   setOperationAction(ISD::FEXP, MVT::f80, Expand);
699   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
700
701   // First set operation action for all vector types to either promote
702   // (for widening) or expand (for scalarization). Then we will selectively
703   // turn on ones that can be effectively codegen'd.
704   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
705            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
706     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
721     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
723     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
724     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
758     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
763     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
764              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
765       setTruncStoreAction((MVT::SimpleValueType)VT,
766                           (MVT::SimpleValueType)InnerVT, Expand);
767     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
768     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
769     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
770   }
771
772   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
773   // with -msoft-float, disable use of MMX as well.
774   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
775     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
776     // No operations on x86mmx supported, everything uses intrinsics.
777   }
778
779   // MMX-sized vectors (other than x86mmx) are expected to be expanded
780   // into smaller operations.
781   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
782   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
783   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
784   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
785   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
786   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
787   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
788   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
789   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
790   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
791   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
792   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
793   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
794   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
795   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
796   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
797   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
798   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
799   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
800   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
801   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
802   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
803   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
804   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
805   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
806   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
807   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
808   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
809   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
810
811   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
812     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
813
814     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
815     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
816     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
817     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
818     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
819     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
820     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
821     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
822     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
823     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
824     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
825     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
826   }
827
828   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
829     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
830
831     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
832     // registers cannot be used even for integer operations.
833     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
834     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
835     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
836     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
837
838     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
839     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
840     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
841     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
842     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
843     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
844     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
845     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
846     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
847     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
848     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
849     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
850     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
851     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
852     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
853     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
854
855     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
856     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
857     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
858     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
859
860     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
861     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
862     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
863     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
864     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
865
866     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
867     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
868     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
869     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
870     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
871
872     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
873     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
874       EVT VT = (MVT::SimpleValueType)i;
875       // Do not attempt to custom lower non-power-of-2 vectors
876       if (!isPowerOf2_32(VT.getVectorNumElements()))
877         continue;
878       // Do not attempt to custom lower non-128-bit vectors
879       if (!VT.is128BitVector())
880         continue;
881       setOperationAction(ISD::BUILD_VECTOR,
882                          VT.getSimpleVT().SimpleTy, Custom);
883       setOperationAction(ISD::VECTOR_SHUFFLE,
884                          VT.getSimpleVT().SimpleTy, Custom);
885       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
886                          VT.getSimpleVT().SimpleTy, Custom);
887     }
888
889     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
890     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
891     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
892     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
893     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
894     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
895
896     if (Subtarget->is64Bit()) {
897       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
898       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
899     }
900
901     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
902     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
903       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
904       EVT VT = SVT;
905
906       // Do not attempt to promote non-128-bit vectors
907       if (!VT.is128BitVector())
908         continue;
909
910       setOperationAction(ISD::AND,    SVT, Promote);
911       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
912       setOperationAction(ISD::OR,     SVT, Promote);
913       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
914       setOperationAction(ISD::XOR,    SVT, Promote);
915       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
916       setOperationAction(ISD::LOAD,   SVT, Promote);
917       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
918       setOperationAction(ISD::SELECT, SVT, Promote);
919       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
920     }
921
922     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
923
924     // Custom lower v2i64 and v2f64 selects.
925     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
926     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
927     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
928     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
929
930     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
931     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
932   }
933
934   if (Subtarget->hasSSE41()) {
935     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
936     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
937     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
938     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
939     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
940     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
941     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
942     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
943     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
944     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
945
946     // FIXME: Do we need to handle scalar-to-vector here?
947     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
948
949     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
950     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
951     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
952     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
953     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
954
955     // i8 and i16 vectors are custom , because the source register and source
956     // source memory operand types are not the same width.  f32 vectors are
957     // custom since the immediate controlling the insert encodes additional
958     // information.
959     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
960     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
961     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
962     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
963
964     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
965     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
966     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
967     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
968
969     // FIXME: these should be Legal but thats only for the case where
970     // the index is constant.  For now custom expand to deal with that.
971     if (Subtarget->is64Bit()) {
972       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
973       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
974     }
975   }
976
977   if (Subtarget->hasSSE2()) {
978     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
979     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
980
981     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
982     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
983
984     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
985     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
986
987     if (Subtarget->hasAVX2()) {
988       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
989       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
990
991       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
992       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
993
994       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
995     } else {
996       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
997       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
998
999       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1000       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1001
1002       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1003     }
1004   }
1005
1006   if (Subtarget->hasSSE42())
1007     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
1008
1009   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1010     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1011     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1012     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1013     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1014     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1015     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1016
1017     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1018     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1019     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1020
1021     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1022     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1023     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1024     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1025     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1026     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1027
1028     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1029     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1030     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1031     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1032     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1033     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1034
1035     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1036     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1037     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1038
1039     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1040     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1041     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1042     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1043     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1044     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1045
1046     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1047     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1048
1049     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1050     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1051
1052     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1053     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1054
1055     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1056     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1057     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1058     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1059
1060     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1061     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1062     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1063
1064     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1065     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1066     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1067     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1068
1069     if (Subtarget->hasAVX2()) {
1070       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1071       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1072       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1073       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1074
1075       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1076       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1077       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1078       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1079
1080       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1081       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1082       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1083       // Don't lower v32i8 because there is no 128-bit byte mul
1084
1085       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1086
1087       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1088       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1089
1090       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1091       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1092
1093       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1094     } else {
1095       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1096       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1097       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1098       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1099
1100       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1101       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1102       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1103       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1104
1105       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1106       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1107       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1108       // Don't lower v32i8 because there is no 128-bit byte mul
1109
1110       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1111       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1112
1113       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1114       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1115
1116       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1117     }
1118
1119     // Custom lower several nodes for 256-bit types.
1120     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1121              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1122       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1123       EVT VT = SVT;
1124
1125       // Extract subvector is special because the value type
1126       // (result) is 128-bit but the source is 256-bit wide.
1127       if (VT.is128BitVector())
1128         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1129
1130       // Do not attempt to custom lower other non-256-bit vectors
1131       if (!VT.is256BitVector())
1132         continue;
1133
1134       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1135       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1136       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1137       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1138       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1139       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1140     }
1141
1142     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1143     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1144       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1145       EVT VT = SVT;
1146
1147       // Do not attempt to promote non-256-bit vectors
1148       if (!VT.is256BitVector())
1149         continue;
1150
1151       setOperationAction(ISD::AND,    SVT, Promote);
1152       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1153       setOperationAction(ISD::OR,     SVT, Promote);
1154       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1155       setOperationAction(ISD::XOR,    SVT, Promote);
1156       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1157       setOperationAction(ISD::LOAD,   SVT, Promote);
1158       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1159       setOperationAction(ISD::SELECT, SVT, Promote);
1160       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1161     }
1162   }
1163
1164   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1165   // of this type with custom code.
1166   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1167            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1168     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1169                        Custom);
1170   }
1171
1172   // We want to custom lower some of our intrinsics.
1173   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1174
1175
1176   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1177   // handle type legalization for these operations here.
1178   //
1179   // FIXME: We really should do custom legalization for addition and
1180   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1181   // than generic legalization for 64-bit multiplication-with-overflow, though.
1182   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1183     // Add/Sub/Mul with overflow operations are custom lowered.
1184     MVT VT = IntVTs[i];
1185     setOperationAction(ISD::SADDO, VT, Custom);
1186     setOperationAction(ISD::UADDO, VT, Custom);
1187     setOperationAction(ISD::SSUBO, VT, Custom);
1188     setOperationAction(ISD::USUBO, VT, Custom);
1189     setOperationAction(ISD::SMULO, VT, Custom);
1190     setOperationAction(ISD::UMULO, VT, Custom);
1191   }
1192
1193   // There are no 8-bit 3-address imul/mul instructions
1194   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1195   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1196
1197   if (!Subtarget->is64Bit()) {
1198     // These libcalls are not available in 32-bit.
1199     setLibcallName(RTLIB::SHL_I128, 0);
1200     setLibcallName(RTLIB::SRL_I128, 0);
1201     setLibcallName(RTLIB::SRA_I128, 0);
1202   }
1203
1204   // We have target-specific dag combine patterns for the following nodes:
1205   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1206   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1207   setTargetDAGCombine(ISD::VSELECT);
1208   setTargetDAGCombine(ISD::SELECT);
1209   setTargetDAGCombine(ISD::SHL);
1210   setTargetDAGCombine(ISD::SRA);
1211   setTargetDAGCombine(ISD::SRL);
1212   setTargetDAGCombine(ISD::OR);
1213   setTargetDAGCombine(ISD::AND);
1214   setTargetDAGCombine(ISD::ADD);
1215   setTargetDAGCombine(ISD::FADD);
1216   setTargetDAGCombine(ISD::FSUB);
1217   setTargetDAGCombine(ISD::SUB);
1218   setTargetDAGCombine(ISD::LOAD);
1219   setTargetDAGCombine(ISD::STORE);
1220   setTargetDAGCombine(ISD::ZERO_EXTEND);
1221   setTargetDAGCombine(ISD::ANY_EXTEND);
1222   setTargetDAGCombine(ISD::SIGN_EXTEND);
1223   setTargetDAGCombine(ISD::TRUNCATE);
1224   setTargetDAGCombine(ISD::UINT_TO_FP);
1225   setTargetDAGCombine(ISD::SINT_TO_FP);
1226   setTargetDAGCombine(ISD::SETCC);
1227   setTargetDAGCombine(ISD::FP_TO_SINT);
1228   if (Subtarget->is64Bit())
1229     setTargetDAGCombine(ISD::MUL);
1230   if (Subtarget->hasBMI())
1231     setTargetDAGCombine(ISD::XOR);
1232
1233   computeRegisterProperties();
1234
1235   // On Darwin, -Os means optimize for size without hurting performance,
1236   // do not reduce the limit.
1237   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1238   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1239   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1240   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1241   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1242   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1243   setPrefLoopAlignment(4); // 2^4 bytes.
1244   benefitFromCodePlacementOpt = true;
1245
1246   // Predictable cmov don't hurt on atom because it's in-order.
1247   predictableSelectIsExpensive = !Subtarget->isAtom();
1248
1249   setPrefFunctionAlignment(4); // 2^4 bytes.
1250 }
1251
1252
1253 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1254   if (!VT.isVector()) return MVT::i8;
1255   return VT.changeVectorElementTypeToInteger();
1256 }
1257
1258
1259 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1260 /// the desired ByVal argument alignment.
1261 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1262   if (MaxAlign == 16)
1263     return;
1264   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1265     if (VTy->getBitWidth() == 128)
1266       MaxAlign = 16;
1267   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1268     unsigned EltAlign = 0;
1269     getMaxByValAlign(ATy->getElementType(), EltAlign);
1270     if (EltAlign > MaxAlign)
1271       MaxAlign = EltAlign;
1272   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1273     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1274       unsigned EltAlign = 0;
1275       getMaxByValAlign(STy->getElementType(i), EltAlign);
1276       if (EltAlign > MaxAlign)
1277         MaxAlign = EltAlign;
1278       if (MaxAlign == 16)
1279         break;
1280     }
1281   }
1282 }
1283
1284 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1285 /// function arguments in the caller parameter area. For X86, aggregates
1286 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1287 /// are at 4-byte boundaries.
1288 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1289   if (Subtarget->is64Bit()) {
1290     // Max of 8 and alignment of type.
1291     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1292     if (TyAlign > 8)
1293       return TyAlign;
1294     return 8;
1295   }
1296
1297   unsigned Align = 4;
1298   if (Subtarget->hasSSE1())
1299     getMaxByValAlign(Ty, Align);
1300   return Align;
1301 }
1302
1303 /// getOptimalMemOpType - Returns the target specific optimal type for load
1304 /// and store operations as a result of memset, memcpy, and memmove
1305 /// lowering. If DstAlign is zero that means it's safe to destination
1306 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1307 /// means there isn't a need to check it against alignment requirement,
1308 /// probably because the source does not need to be loaded. If
1309 /// 'IsZeroVal' is true, that means it's safe to return a
1310 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1311 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1312 /// constant so it does not need to be loaded.
1313 /// It returns EVT::Other if the type should be determined using generic
1314 /// target-independent logic.
1315 EVT
1316 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1317                                        unsigned DstAlign, unsigned SrcAlign,
1318                                        bool IsZeroVal,
1319                                        bool MemcpyStrSrc,
1320                                        MachineFunction &MF) const {
1321   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1322   // linux.  This is because the stack realignment code can't handle certain
1323   // cases like PR2962.  This should be removed when PR2962 is fixed.
1324   const Function *F = MF.getFunction();
1325   if (IsZeroVal &&
1326       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1327     if (Size >= 16 &&
1328         (Subtarget->isUnalignedMemAccessFast() ||
1329          ((DstAlign == 0 || DstAlign >= 16) &&
1330           (SrcAlign == 0 || SrcAlign >= 16))) &&
1331         Subtarget->getStackAlignment() >= 16) {
1332       if (Subtarget->getStackAlignment() >= 32) {
1333         if (Subtarget->hasAVX2())
1334           return MVT::v8i32;
1335         if (Subtarget->hasAVX())
1336           return MVT::v8f32;
1337       }
1338       if (Subtarget->hasSSE2())
1339         return MVT::v4i32;
1340       if (Subtarget->hasSSE1())
1341         return MVT::v4f32;
1342     } else if (!MemcpyStrSrc && Size >= 8 &&
1343                !Subtarget->is64Bit() &&
1344                Subtarget->getStackAlignment() >= 8 &&
1345                Subtarget->hasSSE2()) {
1346       // Do not use f64 to lower memcpy if source is string constant. It's
1347       // better to use i32 to avoid the loads.
1348       return MVT::f64;
1349     }
1350   }
1351   if (Subtarget->is64Bit() && Size >= 8)
1352     return MVT::i64;
1353   return MVT::i32;
1354 }
1355
1356 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1357 /// current function.  The returned value is a member of the
1358 /// MachineJumpTableInfo::JTEntryKind enum.
1359 unsigned X86TargetLowering::getJumpTableEncoding() const {
1360   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1361   // symbol.
1362   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1363       Subtarget->isPICStyleGOT())
1364     return MachineJumpTableInfo::EK_Custom32;
1365
1366   // Otherwise, use the normal jump table encoding heuristics.
1367   return TargetLowering::getJumpTableEncoding();
1368 }
1369
1370 const MCExpr *
1371 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1372                                              const MachineBasicBlock *MBB,
1373                                              unsigned uid,MCContext &Ctx) const{
1374   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1375          Subtarget->isPICStyleGOT());
1376   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1377   // entries.
1378   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1379                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1380 }
1381
1382 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1383 /// jumptable.
1384 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1385                                                     SelectionDAG &DAG) const {
1386   if (!Subtarget->is64Bit())
1387     // This doesn't have DebugLoc associated with it, but is not really the
1388     // same as a Register.
1389     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1390   return Table;
1391 }
1392
1393 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1394 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1395 /// MCExpr.
1396 const MCExpr *X86TargetLowering::
1397 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1398                              MCContext &Ctx) const {
1399   // X86-64 uses RIP relative addressing based on the jump table label.
1400   if (Subtarget->isPICStyleRIPRel())
1401     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1402
1403   // Otherwise, the reference is relative to the PIC base.
1404   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1405 }
1406
1407 // FIXME: Why this routine is here? Move to RegInfo!
1408 std::pair<const TargetRegisterClass*, uint8_t>
1409 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1410   const TargetRegisterClass *RRC = 0;
1411   uint8_t Cost = 1;
1412   switch (VT.getSimpleVT().SimpleTy) {
1413   default:
1414     return TargetLowering::findRepresentativeClass(VT);
1415   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1416     RRC = Subtarget->is64Bit() ?
1417       (const TargetRegisterClass*)&X86::GR64RegClass :
1418       (const TargetRegisterClass*)&X86::GR32RegClass;
1419     break;
1420   case MVT::x86mmx:
1421     RRC = &X86::VR64RegClass;
1422     break;
1423   case MVT::f32: case MVT::f64:
1424   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1425   case MVT::v4f32: case MVT::v2f64:
1426   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1427   case MVT::v4f64:
1428     RRC = &X86::VR128RegClass;
1429     break;
1430   }
1431   return std::make_pair(RRC, Cost);
1432 }
1433
1434 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1435                                                unsigned &Offset) const {
1436   if (!Subtarget->isTargetLinux())
1437     return false;
1438
1439   if (Subtarget->is64Bit()) {
1440     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1441     Offset = 0x28;
1442     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1443       AddressSpace = 256;
1444     else
1445       AddressSpace = 257;
1446   } else {
1447     // %gs:0x14 on i386
1448     Offset = 0x14;
1449     AddressSpace = 256;
1450   }
1451   return true;
1452 }
1453
1454
1455 //===----------------------------------------------------------------------===//
1456 //               Return Value Calling Convention Implementation
1457 //===----------------------------------------------------------------------===//
1458
1459 #include "X86GenCallingConv.inc"
1460
1461 bool
1462 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1463                                   MachineFunction &MF, bool isVarArg,
1464                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1465                         LLVMContext &Context) const {
1466   SmallVector<CCValAssign, 16> RVLocs;
1467   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1468                  RVLocs, Context);
1469   return CCInfo.CheckReturn(Outs, RetCC_X86);
1470 }
1471
1472 SDValue
1473 X86TargetLowering::LowerReturn(SDValue Chain,
1474                                CallingConv::ID CallConv, bool isVarArg,
1475                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1476                                const SmallVectorImpl<SDValue> &OutVals,
1477                                DebugLoc dl, SelectionDAG &DAG) const {
1478   MachineFunction &MF = DAG.getMachineFunction();
1479   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1480
1481   SmallVector<CCValAssign, 16> RVLocs;
1482   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1483                  RVLocs, *DAG.getContext());
1484   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1485
1486   // Add the regs to the liveout set for the function.
1487   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1488   for (unsigned i = 0; i != RVLocs.size(); ++i)
1489     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1490       MRI.addLiveOut(RVLocs[i].getLocReg());
1491
1492   SDValue Flag;
1493
1494   SmallVector<SDValue, 6> RetOps;
1495   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1496   // Operand #1 = Bytes To Pop
1497   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1498                    MVT::i16));
1499
1500   // Copy the result values into the output registers.
1501   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1502     CCValAssign &VA = RVLocs[i];
1503     assert(VA.isRegLoc() && "Can only return in registers!");
1504     SDValue ValToCopy = OutVals[i];
1505     EVT ValVT = ValToCopy.getValueType();
1506
1507     // Promote values to the appropriate types
1508     if (VA.getLocInfo() == CCValAssign::SExt)
1509       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1510     else if (VA.getLocInfo() == CCValAssign::ZExt)
1511       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1512     else if (VA.getLocInfo() == CCValAssign::AExt)
1513       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1514     else if (VA.getLocInfo() == CCValAssign::BCvt)
1515       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1516
1517     // If this is x86-64, and we disabled SSE, we can't return FP values,
1518     // or SSE or MMX vectors.
1519     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1520          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1521           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1522       report_fatal_error("SSE register return with SSE disabled");
1523     }
1524     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1525     // llvm-gcc has never done it right and no one has noticed, so this
1526     // should be OK for now.
1527     if (ValVT == MVT::f64 &&
1528         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1529       report_fatal_error("SSE2 register return with SSE2 disabled");
1530
1531     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1532     // the RET instruction and handled by the FP Stackifier.
1533     if (VA.getLocReg() == X86::ST0 ||
1534         VA.getLocReg() == X86::ST1) {
1535       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1536       // change the value to the FP stack register class.
1537       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1538         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1539       RetOps.push_back(ValToCopy);
1540       // Don't emit a copytoreg.
1541       continue;
1542     }
1543
1544     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1545     // which is returned in RAX / RDX.
1546     if (Subtarget->is64Bit()) {
1547       if (ValVT == MVT::x86mmx) {
1548         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1549           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1550           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1551                                   ValToCopy);
1552           // If we don't have SSE2 available, convert to v4f32 so the generated
1553           // register is legal.
1554           if (!Subtarget->hasSSE2())
1555             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1556         }
1557       }
1558     }
1559
1560     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1561     Flag = Chain.getValue(1);
1562   }
1563
1564   // The x86-64 ABI for returning structs by value requires that we copy
1565   // the sret argument into %rax for the return. We saved the argument into
1566   // a virtual register in the entry block, so now we copy the value out
1567   // and into %rax.
1568   if (Subtarget->is64Bit() &&
1569       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1570     MachineFunction &MF = DAG.getMachineFunction();
1571     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1572     unsigned Reg = FuncInfo->getSRetReturnReg();
1573     assert(Reg &&
1574            "SRetReturnReg should have been set in LowerFormalArguments().");
1575     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1576
1577     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1578     Flag = Chain.getValue(1);
1579
1580     // RAX now acts like a return value.
1581     MRI.addLiveOut(X86::RAX);
1582   }
1583
1584   RetOps[0] = Chain;  // Update chain.
1585
1586   // Add the flag if we have it.
1587   if (Flag.getNode())
1588     RetOps.push_back(Flag);
1589
1590   return DAG.getNode(X86ISD::RET_FLAG, dl,
1591                      MVT::Other, &RetOps[0], RetOps.size());
1592 }
1593
1594 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1595   if (N->getNumValues() != 1)
1596     return false;
1597   if (!N->hasNUsesOfValue(1, 0))
1598     return false;
1599
1600   SDValue TCChain = Chain;
1601   SDNode *Copy = *N->use_begin();
1602   if (Copy->getOpcode() == ISD::CopyToReg) {
1603     // If the copy has a glue operand, we conservatively assume it isn't safe to
1604     // perform a tail call.
1605     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1606       return false;
1607     TCChain = Copy->getOperand(0);
1608   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1609     return false;
1610
1611   bool HasRet = false;
1612   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1613        UI != UE; ++UI) {
1614     if (UI->getOpcode() != X86ISD::RET_FLAG)
1615       return false;
1616     HasRet = true;
1617   }
1618
1619   if (!HasRet)
1620     return false;
1621
1622   Chain = TCChain;
1623   return true;
1624 }
1625
1626 EVT
1627 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1628                                             ISD::NodeType ExtendKind) const {
1629   MVT ReturnMVT;
1630   // TODO: Is this also valid on 32-bit?
1631   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1632     ReturnMVT = MVT::i8;
1633   else
1634     ReturnMVT = MVT::i32;
1635
1636   EVT MinVT = getRegisterType(Context, ReturnMVT);
1637   return VT.bitsLT(MinVT) ? MinVT : VT;
1638 }
1639
1640 /// LowerCallResult - Lower the result values of a call into the
1641 /// appropriate copies out of appropriate physical registers.
1642 ///
1643 SDValue
1644 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1645                                    CallingConv::ID CallConv, bool isVarArg,
1646                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1647                                    DebugLoc dl, SelectionDAG &DAG,
1648                                    SmallVectorImpl<SDValue> &InVals) const {
1649
1650   // Assign locations to each value returned by this call.
1651   SmallVector<CCValAssign, 16> RVLocs;
1652   bool Is64Bit = Subtarget->is64Bit();
1653   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1654                  getTargetMachine(), RVLocs, *DAG.getContext());
1655   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1656
1657   // Copy all of the result registers out of their specified physreg.
1658   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1659     CCValAssign &VA = RVLocs[i];
1660     EVT CopyVT = VA.getValVT();
1661
1662     // If this is x86-64, and we disabled SSE, we can't return FP values
1663     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1664         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1665       report_fatal_error("SSE register return with SSE disabled");
1666     }
1667
1668     SDValue Val;
1669
1670     // If this is a call to a function that returns an fp value on the floating
1671     // point stack, we must guarantee the the value is popped from the stack, so
1672     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1673     // if the return value is not used. We use the FpPOP_RETVAL instruction
1674     // instead.
1675     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1676       // If we prefer to use the value in xmm registers, copy it out as f80 and
1677       // use a truncate to move it from fp stack reg to xmm reg.
1678       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1679       SDValue Ops[] = { Chain, InFlag };
1680       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1681                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1682       Val = Chain.getValue(0);
1683
1684       // Round the f80 to the right size, which also moves it to the appropriate
1685       // xmm register.
1686       if (CopyVT != VA.getValVT())
1687         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1688                           // This truncation won't change the value.
1689                           DAG.getIntPtrConstant(1));
1690     } else {
1691       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1692                                  CopyVT, InFlag).getValue(1);
1693       Val = Chain.getValue(0);
1694     }
1695     InFlag = Chain.getValue(2);
1696     InVals.push_back(Val);
1697   }
1698
1699   return Chain;
1700 }
1701
1702
1703 //===----------------------------------------------------------------------===//
1704 //                C & StdCall & Fast Calling Convention implementation
1705 //===----------------------------------------------------------------------===//
1706 //  StdCall calling convention seems to be standard for many Windows' API
1707 //  routines and around. It differs from C calling convention just a little:
1708 //  callee should clean up the stack, not caller. Symbols should be also
1709 //  decorated in some fancy way :) It doesn't support any vector arguments.
1710 //  For info on fast calling convention see Fast Calling Convention (tail call)
1711 //  implementation LowerX86_32FastCCCallTo.
1712
1713 /// CallIsStructReturn - Determines whether a call uses struct return
1714 /// semantics.
1715 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1716   if (Outs.empty())
1717     return false;
1718
1719   return Outs[0].Flags.isSRet();
1720 }
1721
1722 /// ArgsAreStructReturn - Determines whether a function uses struct
1723 /// return semantics.
1724 static bool
1725 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1726   if (Ins.empty())
1727     return false;
1728
1729   return Ins[0].Flags.isSRet();
1730 }
1731
1732 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1733 /// by "Src" to address "Dst" with size and alignment information specified by
1734 /// the specific parameter attribute. The copy will be passed as a byval
1735 /// function parameter.
1736 static SDValue
1737 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1738                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1739                           DebugLoc dl) {
1740   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1741
1742   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1743                        /*isVolatile*/false, /*AlwaysInline=*/true,
1744                        MachinePointerInfo(), MachinePointerInfo());
1745 }
1746
1747 /// IsTailCallConvention - Return true if the calling convention is one that
1748 /// supports tail call optimization.
1749 static bool IsTailCallConvention(CallingConv::ID CC) {
1750   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1751 }
1752
1753 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1754   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1755     return false;
1756
1757   CallSite CS(CI);
1758   CallingConv::ID CalleeCC = CS.getCallingConv();
1759   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1760     return false;
1761
1762   return true;
1763 }
1764
1765 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1766 /// a tailcall target by changing its ABI.
1767 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1768                                    bool GuaranteedTailCallOpt) {
1769   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1770 }
1771
1772 SDValue
1773 X86TargetLowering::LowerMemArgument(SDValue Chain,
1774                                     CallingConv::ID CallConv,
1775                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1776                                     DebugLoc dl, SelectionDAG &DAG,
1777                                     const CCValAssign &VA,
1778                                     MachineFrameInfo *MFI,
1779                                     unsigned i) const {
1780   // Create the nodes corresponding to a load from this parameter slot.
1781   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1782   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1783                               getTargetMachine().Options.GuaranteedTailCallOpt);
1784   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1785   EVT ValVT;
1786
1787   // If value is passed by pointer we have address passed instead of the value
1788   // itself.
1789   if (VA.getLocInfo() == CCValAssign::Indirect)
1790     ValVT = VA.getLocVT();
1791   else
1792     ValVT = VA.getValVT();
1793
1794   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1795   // changed with more analysis.
1796   // In case of tail call optimization mark all arguments mutable. Since they
1797   // could be overwritten by lowering of arguments in case of a tail call.
1798   if (Flags.isByVal()) {
1799     unsigned Bytes = Flags.getByValSize();
1800     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1801     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1802     return DAG.getFrameIndex(FI, getPointerTy());
1803   } else {
1804     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1805                                     VA.getLocMemOffset(), isImmutable);
1806     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1807     return DAG.getLoad(ValVT, dl, Chain, FIN,
1808                        MachinePointerInfo::getFixedStack(FI),
1809                        false, false, false, 0);
1810   }
1811 }
1812
1813 SDValue
1814 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1815                                         CallingConv::ID CallConv,
1816                                         bool isVarArg,
1817                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1818                                         DebugLoc dl,
1819                                         SelectionDAG &DAG,
1820                                         SmallVectorImpl<SDValue> &InVals)
1821                                           const {
1822   MachineFunction &MF = DAG.getMachineFunction();
1823   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1824
1825   const Function* Fn = MF.getFunction();
1826   if (Fn->hasExternalLinkage() &&
1827       Subtarget->isTargetCygMing() &&
1828       Fn->getName() == "main")
1829     FuncInfo->setForceFramePointer(true);
1830
1831   MachineFrameInfo *MFI = MF.getFrameInfo();
1832   bool Is64Bit = Subtarget->is64Bit();
1833   bool IsWindows = Subtarget->isTargetWindows();
1834   bool IsWin64 = Subtarget->isTargetWin64();
1835
1836   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1837          "Var args not supported with calling convention fastcc or ghc");
1838
1839   // Assign locations to all of the incoming arguments.
1840   SmallVector<CCValAssign, 16> ArgLocs;
1841   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1842                  ArgLocs, *DAG.getContext());
1843
1844   // Allocate shadow area for Win64
1845   if (IsWin64) {
1846     CCInfo.AllocateStack(32, 8);
1847   }
1848
1849   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1850
1851   unsigned LastVal = ~0U;
1852   SDValue ArgValue;
1853   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1854     CCValAssign &VA = ArgLocs[i];
1855     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1856     // places.
1857     assert(VA.getValNo() != LastVal &&
1858            "Don't support value assigned to multiple locs yet");
1859     (void)LastVal;
1860     LastVal = VA.getValNo();
1861
1862     if (VA.isRegLoc()) {
1863       EVT RegVT = VA.getLocVT();
1864       const TargetRegisterClass *RC;
1865       if (RegVT == MVT::i32)
1866         RC = &X86::GR32RegClass;
1867       else if (Is64Bit && RegVT == MVT::i64)
1868         RC = &X86::GR64RegClass;
1869       else if (RegVT == MVT::f32)
1870         RC = &X86::FR32RegClass;
1871       else if (RegVT == MVT::f64)
1872         RC = &X86::FR64RegClass;
1873       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1874         RC = &X86::VR256RegClass;
1875       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1876         RC = &X86::VR128RegClass;
1877       else if (RegVT == MVT::x86mmx)
1878         RC = &X86::VR64RegClass;
1879       else
1880         llvm_unreachable("Unknown argument type!");
1881
1882       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1883       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1884
1885       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1886       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1887       // right size.
1888       if (VA.getLocInfo() == CCValAssign::SExt)
1889         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1890                                DAG.getValueType(VA.getValVT()));
1891       else if (VA.getLocInfo() == CCValAssign::ZExt)
1892         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1893                                DAG.getValueType(VA.getValVT()));
1894       else if (VA.getLocInfo() == CCValAssign::BCvt)
1895         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1896
1897       if (VA.isExtInLoc()) {
1898         // Handle MMX values passed in XMM regs.
1899         if (RegVT.isVector()) {
1900           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1901                                  ArgValue);
1902         } else
1903           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1904       }
1905     } else {
1906       assert(VA.isMemLoc());
1907       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1908     }
1909
1910     // If value is passed via pointer - do a load.
1911     if (VA.getLocInfo() == CCValAssign::Indirect)
1912       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1913                              MachinePointerInfo(), false, false, false, 0);
1914
1915     InVals.push_back(ArgValue);
1916   }
1917
1918   // The x86-64 ABI for returning structs by value requires that we copy
1919   // the sret argument into %rax for the return. Save the argument into
1920   // a virtual register so that we can access it from the return points.
1921   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1922     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1923     unsigned Reg = FuncInfo->getSRetReturnReg();
1924     if (!Reg) {
1925       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1926       FuncInfo->setSRetReturnReg(Reg);
1927     }
1928     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1929     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1930   }
1931
1932   unsigned StackSize = CCInfo.getNextStackOffset();
1933   // Align stack specially for tail calls.
1934   if (FuncIsMadeTailCallSafe(CallConv,
1935                              MF.getTarget().Options.GuaranteedTailCallOpt))
1936     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1937
1938   // If the function takes variable number of arguments, make a frame index for
1939   // the start of the first vararg value... for expansion of llvm.va_start.
1940   if (isVarArg) {
1941     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1942                     CallConv != CallingConv::X86_ThisCall)) {
1943       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1944     }
1945     if (Is64Bit) {
1946       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1947
1948       // FIXME: We should really autogenerate these arrays
1949       static const uint16_t GPR64ArgRegsWin64[] = {
1950         X86::RCX, X86::RDX, X86::R8,  X86::R9
1951       };
1952       static const uint16_t GPR64ArgRegs64Bit[] = {
1953         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1954       };
1955       static const uint16_t XMMArgRegs64Bit[] = {
1956         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1957         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1958       };
1959       const uint16_t *GPR64ArgRegs;
1960       unsigned NumXMMRegs = 0;
1961
1962       if (IsWin64) {
1963         // The XMM registers which might contain var arg parameters are shadowed
1964         // in their paired GPR.  So we only need to save the GPR to their home
1965         // slots.
1966         TotalNumIntRegs = 4;
1967         GPR64ArgRegs = GPR64ArgRegsWin64;
1968       } else {
1969         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1970         GPR64ArgRegs = GPR64ArgRegs64Bit;
1971
1972         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1973                                                 TotalNumXMMRegs);
1974       }
1975       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1976                                                        TotalNumIntRegs);
1977
1978       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1979       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1980              "SSE register cannot be used when SSE is disabled!");
1981       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1982                NoImplicitFloatOps) &&
1983              "SSE register cannot be used when SSE is disabled!");
1984       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1985           !Subtarget->hasSSE1())
1986         // Kernel mode asks for SSE to be disabled, so don't push them
1987         // on the stack.
1988         TotalNumXMMRegs = 0;
1989
1990       if (IsWin64) {
1991         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1992         // Get to the caller-allocated home save location.  Add 8 to account
1993         // for the return address.
1994         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1995         FuncInfo->setRegSaveFrameIndex(
1996           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1997         // Fixup to set vararg frame on shadow area (4 x i64).
1998         if (NumIntRegs < 4)
1999           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2000       } else {
2001         // For X86-64, if there are vararg parameters that are passed via
2002         // registers, then we must store them to their spots on the stack so
2003         // they may be loaded by deferencing the result of va_next.
2004         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2005         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2006         FuncInfo->setRegSaveFrameIndex(
2007           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2008                                false));
2009       }
2010
2011       // Store the integer parameter registers.
2012       SmallVector<SDValue, 8> MemOps;
2013       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2014                                         getPointerTy());
2015       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2016       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2017         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2018                                   DAG.getIntPtrConstant(Offset));
2019         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2020                                      &X86::GR64RegClass);
2021         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2022         SDValue Store =
2023           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2024                        MachinePointerInfo::getFixedStack(
2025                          FuncInfo->getRegSaveFrameIndex(), Offset),
2026                        false, false, 0);
2027         MemOps.push_back(Store);
2028         Offset += 8;
2029       }
2030
2031       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2032         // Now store the XMM (fp + vector) parameter registers.
2033         SmallVector<SDValue, 11> SaveXMMOps;
2034         SaveXMMOps.push_back(Chain);
2035
2036         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2037         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2038         SaveXMMOps.push_back(ALVal);
2039
2040         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2041                                FuncInfo->getRegSaveFrameIndex()));
2042         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2043                                FuncInfo->getVarArgsFPOffset()));
2044
2045         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2046           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2047                                        &X86::VR128RegClass);
2048           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2049           SaveXMMOps.push_back(Val);
2050         }
2051         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2052                                      MVT::Other,
2053                                      &SaveXMMOps[0], SaveXMMOps.size()));
2054       }
2055
2056       if (!MemOps.empty())
2057         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2058                             &MemOps[0], MemOps.size());
2059     }
2060   }
2061
2062   // Some CCs need callee pop.
2063   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2064                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2065     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2066   } else {
2067     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2068     // If this is an sret function, the return should pop the hidden pointer.
2069     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2070         ArgsAreStructReturn(Ins))
2071       FuncInfo->setBytesToPopOnReturn(4);
2072   }
2073
2074   if (!Is64Bit) {
2075     // RegSaveFrameIndex is X86-64 only.
2076     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2077     if (CallConv == CallingConv::X86_FastCall ||
2078         CallConv == CallingConv::X86_ThisCall)
2079       // fastcc functions can't have varargs.
2080       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2081   }
2082
2083   FuncInfo->setArgumentStackSize(StackSize);
2084
2085   return Chain;
2086 }
2087
2088 SDValue
2089 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2090                                     SDValue StackPtr, SDValue Arg,
2091                                     DebugLoc dl, SelectionDAG &DAG,
2092                                     const CCValAssign &VA,
2093                                     ISD::ArgFlagsTy Flags) const {
2094   unsigned LocMemOffset = VA.getLocMemOffset();
2095   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2096   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2097   if (Flags.isByVal())
2098     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2099
2100   return DAG.getStore(Chain, dl, Arg, PtrOff,
2101                       MachinePointerInfo::getStack(LocMemOffset),
2102                       false, false, 0);
2103 }
2104
2105 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2106 /// optimization is performed and it is required.
2107 SDValue
2108 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2109                                            SDValue &OutRetAddr, SDValue Chain,
2110                                            bool IsTailCall, bool Is64Bit,
2111                                            int FPDiff, DebugLoc dl) const {
2112   // Adjust the Return address stack slot.
2113   EVT VT = getPointerTy();
2114   OutRetAddr = getReturnAddressFrameIndex(DAG);
2115
2116   // Load the "old" Return address.
2117   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2118                            false, false, false, 0);
2119   return SDValue(OutRetAddr.getNode(), 1);
2120 }
2121
2122 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2123 /// optimization is performed and it is required (FPDiff!=0).
2124 static SDValue
2125 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2126                          SDValue Chain, SDValue RetAddrFrIdx,
2127                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2128   // Store the return address to the appropriate stack slot.
2129   if (!FPDiff) return Chain;
2130   // Calculate the new stack slot for the return address.
2131   int SlotSize = Is64Bit ? 8 : 4;
2132   int NewReturnAddrFI =
2133     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2134   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2135   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2136   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2137                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2138                        false, false, 0);
2139   return Chain;
2140 }
2141
2142 SDValue
2143 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2144                              SmallVectorImpl<SDValue> &InVals) const {
2145   SelectionDAG &DAG                     = CLI.DAG;
2146   DebugLoc &dl                          = CLI.DL;
2147   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2148   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2149   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2150   SDValue Chain                         = CLI.Chain;
2151   SDValue Callee                        = CLI.Callee;
2152   CallingConv::ID CallConv              = CLI.CallConv;
2153   bool &isTailCall                      = CLI.IsTailCall;
2154   bool isVarArg                         = CLI.IsVarArg;
2155
2156   MachineFunction &MF = DAG.getMachineFunction();
2157   bool Is64Bit        = Subtarget->is64Bit();
2158   bool IsWin64        = Subtarget->isTargetWin64();
2159   bool IsWindows      = Subtarget->isTargetWindows();
2160   bool IsStructRet    = CallIsStructReturn(Outs);
2161   bool IsSibcall      = false;
2162
2163   if (MF.getTarget().Options.DisableTailCalls)
2164     isTailCall = false;
2165
2166   if (isTailCall) {
2167     // Check if it's really possible to do a tail call.
2168     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2169                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2170                                                    Outs, OutVals, Ins, DAG);
2171
2172     // Sibcalls are automatically detected tailcalls which do not require
2173     // ABI changes.
2174     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2175       IsSibcall = true;
2176
2177     if (isTailCall)
2178       ++NumTailCalls;
2179   }
2180
2181   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2182          "Var args not supported with calling convention fastcc or ghc");
2183
2184   // Analyze operands of the call, assigning locations to each operand.
2185   SmallVector<CCValAssign, 16> ArgLocs;
2186   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2187                  ArgLocs, *DAG.getContext());
2188
2189   // Allocate shadow area for Win64
2190   if (IsWin64) {
2191     CCInfo.AllocateStack(32, 8);
2192   }
2193
2194   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2195
2196   // Get a count of how many bytes are to be pushed on the stack.
2197   unsigned NumBytes = CCInfo.getNextStackOffset();
2198   if (IsSibcall)
2199     // This is a sibcall. The memory operands are available in caller's
2200     // own caller's stack.
2201     NumBytes = 0;
2202   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2203            IsTailCallConvention(CallConv))
2204     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2205
2206   int FPDiff = 0;
2207   if (isTailCall && !IsSibcall) {
2208     // Lower arguments at fp - stackoffset + fpdiff.
2209     unsigned NumBytesCallerPushed =
2210       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2211     FPDiff = NumBytesCallerPushed - NumBytes;
2212
2213     // Set the delta of movement of the returnaddr stackslot.
2214     // But only set if delta is greater than previous delta.
2215     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2216       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2217   }
2218
2219   if (!IsSibcall)
2220     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2221
2222   SDValue RetAddrFrIdx;
2223   // Load return address for tail calls.
2224   if (isTailCall && FPDiff)
2225     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2226                                     Is64Bit, FPDiff, dl);
2227
2228   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2229   SmallVector<SDValue, 8> MemOpChains;
2230   SDValue StackPtr;
2231
2232   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2233   // of tail call optimization arguments are handle later.
2234   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2235     CCValAssign &VA = ArgLocs[i];
2236     EVT RegVT = VA.getLocVT();
2237     SDValue Arg = OutVals[i];
2238     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2239     bool isByVal = Flags.isByVal();
2240
2241     // Promote the value if needed.
2242     switch (VA.getLocInfo()) {
2243     default: llvm_unreachable("Unknown loc info!");
2244     case CCValAssign::Full: break;
2245     case CCValAssign::SExt:
2246       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2247       break;
2248     case CCValAssign::ZExt:
2249       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2250       break;
2251     case CCValAssign::AExt:
2252       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2253         // Special case: passing MMX values in XMM registers.
2254         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2255         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2256         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2257       } else
2258         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2259       break;
2260     case CCValAssign::BCvt:
2261       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2262       break;
2263     case CCValAssign::Indirect: {
2264       // Store the argument.
2265       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2266       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2267       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2268                            MachinePointerInfo::getFixedStack(FI),
2269                            false, false, 0);
2270       Arg = SpillSlot;
2271       break;
2272     }
2273     }
2274
2275     if (VA.isRegLoc()) {
2276       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2277       if (isVarArg && IsWin64) {
2278         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2279         // shadow reg if callee is a varargs function.
2280         unsigned ShadowReg = 0;
2281         switch (VA.getLocReg()) {
2282         case X86::XMM0: ShadowReg = X86::RCX; break;
2283         case X86::XMM1: ShadowReg = X86::RDX; break;
2284         case X86::XMM2: ShadowReg = X86::R8; break;
2285         case X86::XMM3: ShadowReg = X86::R9; break;
2286         }
2287         if (ShadowReg)
2288           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2289       }
2290     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2291       assert(VA.isMemLoc());
2292       if (StackPtr.getNode() == 0)
2293         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2294       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2295                                              dl, DAG, VA, Flags));
2296     }
2297   }
2298
2299   if (!MemOpChains.empty())
2300     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2301                         &MemOpChains[0], MemOpChains.size());
2302
2303   // Build a sequence of copy-to-reg nodes chained together with token chain
2304   // and flag operands which copy the outgoing args into registers.
2305   SDValue InFlag;
2306   // Tail call byval lowering might overwrite argument registers so in case of
2307   // tail call optimization the copies to registers are lowered later.
2308   if (!isTailCall)
2309     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2310       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2311                                RegsToPass[i].second, InFlag);
2312       InFlag = Chain.getValue(1);
2313     }
2314
2315   if (Subtarget->isPICStyleGOT()) {
2316     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2317     // GOT pointer.
2318     if (!isTailCall) {
2319       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2320                                DAG.getNode(X86ISD::GlobalBaseReg,
2321                                            DebugLoc(), getPointerTy()),
2322                                InFlag);
2323       InFlag = Chain.getValue(1);
2324     } else {
2325       // If we are tail calling and generating PIC/GOT style code load the
2326       // address of the callee into ECX. The value in ecx is used as target of
2327       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2328       // for tail calls on PIC/GOT architectures. Normally we would just put the
2329       // address of GOT into ebx and then call target@PLT. But for tail calls
2330       // ebx would be restored (since ebx is callee saved) before jumping to the
2331       // target@PLT.
2332
2333       // Note: The actual moving to ECX is done further down.
2334       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2335       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2336           !G->getGlobal()->hasProtectedVisibility())
2337         Callee = LowerGlobalAddress(Callee, DAG);
2338       else if (isa<ExternalSymbolSDNode>(Callee))
2339         Callee = LowerExternalSymbol(Callee, DAG);
2340     }
2341   }
2342
2343   if (Is64Bit && isVarArg && !IsWin64) {
2344     // From AMD64 ABI document:
2345     // For calls that may call functions that use varargs or stdargs
2346     // (prototype-less calls or calls to functions containing ellipsis (...) in
2347     // the declaration) %al is used as hidden argument to specify the number
2348     // of SSE registers used. The contents of %al do not need to match exactly
2349     // the number of registers, but must be an ubound on the number of SSE
2350     // registers used and is in the range 0 - 8 inclusive.
2351
2352     // Count the number of XMM registers allocated.
2353     static const uint16_t XMMArgRegs[] = {
2354       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2355       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2356     };
2357     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2358     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2359            && "SSE registers cannot be used when SSE is disabled");
2360
2361     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2362                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2363     InFlag = Chain.getValue(1);
2364   }
2365
2366
2367   // For tail calls lower the arguments to the 'real' stack slot.
2368   if (isTailCall) {
2369     // Force all the incoming stack arguments to be loaded from the stack
2370     // before any new outgoing arguments are stored to the stack, because the
2371     // outgoing stack slots may alias the incoming argument stack slots, and
2372     // the alias isn't otherwise explicit. This is slightly more conservative
2373     // than necessary, because it means that each store effectively depends
2374     // on every argument instead of just those arguments it would clobber.
2375     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2376
2377     SmallVector<SDValue, 8> MemOpChains2;
2378     SDValue FIN;
2379     int FI = 0;
2380     // Do not flag preceding copytoreg stuff together with the following stuff.
2381     InFlag = SDValue();
2382     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2383       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2384         CCValAssign &VA = ArgLocs[i];
2385         if (VA.isRegLoc())
2386           continue;
2387         assert(VA.isMemLoc());
2388         SDValue Arg = OutVals[i];
2389         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2390         // Create frame index.
2391         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2392         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2393         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2394         FIN = DAG.getFrameIndex(FI, getPointerTy());
2395
2396         if (Flags.isByVal()) {
2397           // Copy relative to framepointer.
2398           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2399           if (StackPtr.getNode() == 0)
2400             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2401                                           getPointerTy());
2402           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2403
2404           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2405                                                            ArgChain,
2406                                                            Flags, DAG, dl));
2407         } else {
2408           // Store relative to framepointer.
2409           MemOpChains2.push_back(
2410             DAG.getStore(ArgChain, dl, Arg, FIN,
2411                          MachinePointerInfo::getFixedStack(FI),
2412                          false, false, 0));
2413         }
2414       }
2415     }
2416
2417     if (!MemOpChains2.empty())
2418       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2419                           &MemOpChains2[0], MemOpChains2.size());
2420
2421     // Copy arguments to their registers.
2422     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2423       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2424                                RegsToPass[i].second, InFlag);
2425       InFlag = Chain.getValue(1);
2426     }
2427     InFlag =SDValue();
2428
2429     // Store the return address to the appropriate stack slot.
2430     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2431                                      FPDiff, dl);
2432   }
2433
2434   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2435     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2436     // In the 64-bit large code model, we have to make all calls
2437     // through a register, since the call instruction's 32-bit
2438     // pc-relative offset may not be large enough to hold the whole
2439     // address.
2440   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2441     // If the callee is a GlobalAddress node (quite common, every direct call
2442     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2443     // it.
2444
2445     // We should use extra load for direct calls to dllimported functions in
2446     // non-JIT mode.
2447     const GlobalValue *GV = G->getGlobal();
2448     if (!GV->hasDLLImportLinkage()) {
2449       unsigned char OpFlags = 0;
2450       bool ExtraLoad = false;
2451       unsigned WrapperKind = ISD::DELETED_NODE;
2452
2453       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2454       // external symbols most go through the PLT in PIC mode.  If the symbol
2455       // has hidden or protected visibility, or if it is static or local, then
2456       // we don't need to use the PLT - we can directly call it.
2457       if (Subtarget->isTargetELF() &&
2458           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2459           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2460         OpFlags = X86II::MO_PLT;
2461       } else if (Subtarget->isPICStyleStubAny() &&
2462                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2463                  (!Subtarget->getTargetTriple().isMacOSX() ||
2464                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2465         // PC-relative references to external symbols should go through $stub,
2466         // unless we're building with the leopard linker or later, which
2467         // automatically synthesizes these stubs.
2468         OpFlags = X86II::MO_DARWIN_STUB;
2469       } else if (Subtarget->isPICStyleRIPRel() &&
2470                  isa<Function>(GV) &&
2471                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2472         // If the function is marked as non-lazy, generate an indirect call
2473         // which loads from the GOT directly. This avoids runtime overhead
2474         // at the cost of eager binding (and one extra byte of encoding).
2475         OpFlags = X86II::MO_GOTPCREL;
2476         WrapperKind = X86ISD::WrapperRIP;
2477         ExtraLoad = true;
2478       }
2479
2480       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2481                                           G->getOffset(), OpFlags);
2482
2483       // Add a wrapper if needed.
2484       if (WrapperKind != ISD::DELETED_NODE)
2485         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2486       // Add extra indirection if needed.
2487       if (ExtraLoad)
2488         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2489                              MachinePointerInfo::getGOT(),
2490                              false, false, false, 0);
2491     }
2492   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2493     unsigned char OpFlags = 0;
2494
2495     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2496     // external symbols should go through the PLT.
2497     if (Subtarget->isTargetELF() &&
2498         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2499       OpFlags = X86II::MO_PLT;
2500     } else if (Subtarget->isPICStyleStubAny() &&
2501                (!Subtarget->getTargetTriple().isMacOSX() ||
2502                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2503       // PC-relative references to external symbols should go through $stub,
2504       // unless we're building with the leopard linker or later, which
2505       // automatically synthesizes these stubs.
2506       OpFlags = X86II::MO_DARWIN_STUB;
2507     }
2508
2509     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2510                                          OpFlags);
2511   }
2512
2513   // Returns a chain & a flag for retval copy to use.
2514   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2515   SmallVector<SDValue, 8> Ops;
2516
2517   if (!IsSibcall && isTailCall) {
2518     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2519                            DAG.getIntPtrConstant(0, true), InFlag);
2520     InFlag = Chain.getValue(1);
2521   }
2522
2523   Ops.push_back(Chain);
2524   Ops.push_back(Callee);
2525
2526   if (isTailCall)
2527     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2528
2529   // Add argument registers to the end of the list so that they are known live
2530   // into the call.
2531   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2532     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2533                                   RegsToPass[i].second.getValueType()));
2534
2535   // Add an implicit use GOT pointer in EBX.
2536   if (!isTailCall && Subtarget->isPICStyleGOT())
2537     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2538
2539   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2540   if (Is64Bit && isVarArg && !IsWin64)
2541     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2542
2543   // Add a register mask operand representing the call-preserved registers.
2544   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2545   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2546   assert(Mask && "Missing call preserved mask for calling convention");
2547   Ops.push_back(DAG.getRegisterMask(Mask));
2548
2549   if (InFlag.getNode())
2550     Ops.push_back(InFlag);
2551
2552   if (isTailCall) {
2553     // We used to do:
2554     //// If this is the first return lowered for this function, add the regs
2555     //// to the liveout set for the function.
2556     // This isn't right, although it's probably harmless on x86; liveouts
2557     // should be computed from returns not tail calls.  Consider a void
2558     // function making a tail call to a function returning int.
2559     return DAG.getNode(X86ISD::TC_RETURN, dl,
2560                        NodeTys, &Ops[0], Ops.size());
2561   }
2562
2563   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2564   InFlag = Chain.getValue(1);
2565
2566   // Create the CALLSEQ_END node.
2567   unsigned NumBytesForCalleeToPush;
2568   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2569                        getTargetMachine().Options.GuaranteedTailCallOpt))
2570     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2571   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2572            IsStructRet)
2573     // If this is a call to a struct-return function, the callee
2574     // pops the hidden struct pointer, so we have to push it back.
2575     // This is common for Darwin/X86, Linux & Mingw32 targets.
2576     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2577     NumBytesForCalleeToPush = 4;
2578   else
2579     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2580
2581   // Returns a flag for retval copy to use.
2582   if (!IsSibcall) {
2583     Chain = DAG.getCALLSEQ_END(Chain,
2584                                DAG.getIntPtrConstant(NumBytes, true),
2585                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2586                                                      true),
2587                                InFlag);
2588     InFlag = Chain.getValue(1);
2589   }
2590
2591   // Handle result values, copying them out of physregs into vregs that we
2592   // return.
2593   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2594                          Ins, dl, DAG, InVals);
2595 }
2596
2597
2598 //===----------------------------------------------------------------------===//
2599 //                Fast Calling Convention (tail call) implementation
2600 //===----------------------------------------------------------------------===//
2601
2602 //  Like std call, callee cleans arguments, convention except that ECX is
2603 //  reserved for storing the tail called function address. Only 2 registers are
2604 //  free for argument passing (inreg). Tail call optimization is performed
2605 //  provided:
2606 //                * tailcallopt is enabled
2607 //                * caller/callee are fastcc
2608 //  On X86_64 architecture with GOT-style position independent code only local
2609 //  (within module) calls are supported at the moment.
2610 //  To keep the stack aligned according to platform abi the function
2611 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2612 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2613 //  If a tail called function callee has more arguments than the caller the
2614 //  caller needs to make sure that there is room to move the RETADDR to. This is
2615 //  achieved by reserving an area the size of the argument delta right after the
2616 //  original REtADDR, but before the saved framepointer or the spilled registers
2617 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2618 //  stack layout:
2619 //    arg1
2620 //    arg2
2621 //    RETADDR
2622 //    [ new RETADDR
2623 //      move area ]
2624 //    (possible EBP)
2625 //    ESI
2626 //    EDI
2627 //    local1 ..
2628
2629 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2630 /// for a 16 byte align requirement.
2631 unsigned
2632 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2633                                                SelectionDAG& DAG) const {
2634   MachineFunction &MF = DAG.getMachineFunction();
2635   const TargetMachine &TM = MF.getTarget();
2636   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2637   unsigned StackAlignment = TFI.getStackAlignment();
2638   uint64_t AlignMask = StackAlignment - 1;
2639   int64_t Offset = StackSize;
2640   uint64_t SlotSize = TD->getPointerSize();
2641   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2642     // Number smaller than 12 so just add the difference.
2643     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2644   } else {
2645     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2646     Offset = ((~AlignMask) & Offset) + StackAlignment +
2647       (StackAlignment-SlotSize);
2648   }
2649   return Offset;
2650 }
2651
2652 /// MatchingStackOffset - Return true if the given stack call argument is
2653 /// already available in the same position (relatively) of the caller's
2654 /// incoming argument stack.
2655 static
2656 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2657                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2658                          const X86InstrInfo *TII) {
2659   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2660   int FI = INT_MAX;
2661   if (Arg.getOpcode() == ISD::CopyFromReg) {
2662     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2663     if (!TargetRegisterInfo::isVirtualRegister(VR))
2664       return false;
2665     MachineInstr *Def = MRI->getVRegDef(VR);
2666     if (!Def)
2667       return false;
2668     if (!Flags.isByVal()) {
2669       if (!TII->isLoadFromStackSlot(Def, FI))
2670         return false;
2671     } else {
2672       unsigned Opcode = Def->getOpcode();
2673       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2674           Def->getOperand(1).isFI()) {
2675         FI = Def->getOperand(1).getIndex();
2676         Bytes = Flags.getByValSize();
2677       } else
2678         return false;
2679     }
2680   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2681     if (Flags.isByVal())
2682       // ByVal argument is passed in as a pointer but it's now being
2683       // dereferenced. e.g.
2684       // define @foo(%struct.X* %A) {
2685       //   tail call @bar(%struct.X* byval %A)
2686       // }
2687       return false;
2688     SDValue Ptr = Ld->getBasePtr();
2689     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2690     if (!FINode)
2691       return false;
2692     FI = FINode->getIndex();
2693   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2694     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2695     FI = FINode->getIndex();
2696     Bytes = Flags.getByValSize();
2697   } else
2698     return false;
2699
2700   assert(FI != INT_MAX);
2701   if (!MFI->isFixedObjectIndex(FI))
2702     return false;
2703   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2704 }
2705
2706 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2707 /// for tail call optimization. Targets which want to do tail call
2708 /// optimization should implement this function.
2709 bool
2710 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2711                                                      CallingConv::ID CalleeCC,
2712                                                      bool isVarArg,
2713                                                      bool isCalleeStructRet,
2714                                                      bool isCallerStructRet,
2715                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2716                                     const SmallVectorImpl<SDValue> &OutVals,
2717                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2718                                                      SelectionDAG& DAG) const {
2719   if (!IsTailCallConvention(CalleeCC) &&
2720       CalleeCC != CallingConv::C)
2721     return false;
2722
2723   // If -tailcallopt is specified, make fastcc functions tail-callable.
2724   const MachineFunction &MF = DAG.getMachineFunction();
2725   const Function *CallerF = DAG.getMachineFunction().getFunction();
2726   CallingConv::ID CallerCC = CallerF->getCallingConv();
2727   bool CCMatch = CallerCC == CalleeCC;
2728
2729   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2730     if (IsTailCallConvention(CalleeCC) && CCMatch)
2731       return true;
2732     return false;
2733   }
2734
2735   // Look for obvious safe cases to perform tail call optimization that do not
2736   // require ABI changes. This is what gcc calls sibcall.
2737
2738   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2739   // emit a special epilogue.
2740   if (RegInfo->needsStackRealignment(MF))
2741     return false;
2742
2743   // Also avoid sibcall optimization if either caller or callee uses struct
2744   // return semantics.
2745   if (isCalleeStructRet || isCallerStructRet)
2746     return false;
2747
2748   // An stdcall caller is expected to clean up its arguments; the callee
2749   // isn't going to do that.
2750   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2751     return false;
2752
2753   // Do not sibcall optimize vararg calls unless all arguments are passed via
2754   // registers.
2755   if (isVarArg && !Outs.empty()) {
2756
2757     // Optimizing for varargs on Win64 is unlikely to be safe without
2758     // additional testing.
2759     if (Subtarget->isTargetWin64())
2760       return false;
2761
2762     SmallVector<CCValAssign, 16> ArgLocs;
2763     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2764                    getTargetMachine(), ArgLocs, *DAG.getContext());
2765
2766     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2767     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2768       if (!ArgLocs[i].isRegLoc())
2769         return false;
2770   }
2771
2772   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2773   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2774   // this into a sibcall.
2775   bool Unused = false;
2776   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2777     if (!Ins[i].Used) {
2778       Unused = true;
2779       break;
2780     }
2781   }
2782   if (Unused) {
2783     SmallVector<CCValAssign, 16> RVLocs;
2784     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2785                    getTargetMachine(), RVLocs, *DAG.getContext());
2786     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2787     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2788       CCValAssign &VA = RVLocs[i];
2789       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2790         return false;
2791     }
2792   }
2793
2794   // If the calling conventions do not match, then we'd better make sure the
2795   // results are returned in the same way as what the caller expects.
2796   if (!CCMatch) {
2797     SmallVector<CCValAssign, 16> RVLocs1;
2798     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2799                     getTargetMachine(), RVLocs1, *DAG.getContext());
2800     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2801
2802     SmallVector<CCValAssign, 16> RVLocs2;
2803     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2804                     getTargetMachine(), RVLocs2, *DAG.getContext());
2805     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2806
2807     if (RVLocs1.size() != RVLocs2.size())
2808       return false;
2809     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2810       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2811         return false;
2812       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2813         return false;
2814       if (RVLocs1[i].isRegLoc()) {
2815         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2816           return false;
2817       } else {
2818         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2819           return false;
2820       }
2821     }
2822   }
2823
2824   // If the callee takes no arguments then go on to check the results of the
2825   // call.
2826   if (!Outs.empty()) {
2827     // Check if stack adjustment is needed. For now, do not do this if any
2828     // argument is passed on the stack.
2829     SmallVector<CCValAssign, 16> ArgLocs;
2830     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2831                    getTargetMachine(), ArgLocs, *DAG.getContext());
2832
2833     // Allocate shadow area for Win64
2834     if (Subtarget->isTargetWin64()) {
2835       CCInfo.AllocateStack(32, 8);
2836     }
2837
2838     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2839     if (CCInfo.getNextStackOffset()) {
2840       MachineFunction &MF = DAG.getMachineFunction();
2841       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2842         return false;
2843
2844       // Check if the arguments are already laid out in the right way as
2845       // the caller's fixed stack objects.
2846       MachineFrameInfo *MFI = MF.getFrameInfo();
2847       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2848       const X86InstrInfo *TII =
2849         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2850       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2851         CCValAssign &VA = ArgLocs[i];
2852         SDValue Arg = OutVals[i];
2853         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2854         if (VA.getLocInfo() == CCValAssign::Indirect)
2855           return false;
2856         if (!VA.isRegLoc()) {
2857           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2858                                    MFI, MRI, TII))
2859             return false;
2860         }
2861       }
2862     }
2863
2864     // If the tailcall address may be in a register, then make sure it's
2865     // possible to register allocate for it. In 32-bit, the call address can
2866     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2867     // callee-saved registers are restored. These happen to be the same
2868     // registers used to pass 'inreg' arguments so watch out for those.
2869     if (!Subtarget->is64Bit() &&
2870         !isa<GlobalAddressSDNode>(Callee) &&
2871         !isa<ExternalSymbolSDNode>(Callee)) {
2872       unsigned NumInRegs = 0;
2873       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2874         CCValAssign &VA = ArgLocs[i];
2875         if (!VA.isRegLoc())
2876           continue;
2877         unsigned Reg = VA.getLocReg();
2878         switch (Reg) {
2879         default: break;
2880         case X86::EAX: case X86::EDX: case X86::ECX:
2881           if (++NumInRegs == 3)
2882             return false;
2883           break;
2884         }
2885       }
2886     }
2887   }
2888
2889   return true;
2890 }
2891
2892 FastISel *
2893 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2894   return X86::createFastISel(funcInfo);
2895 }
2896
2897
2898 //===----------------------------------------------------------------------===//
2899 //                           Other Lowering Hooks
2900 //===----------------------------------------------------------------------===//
2901
2902 static bool MayFoldLoad(SDValue Op) {
2903   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2904 }
2905
2906 static bool MayFoldIntoStore(SDValue Op) {
2907   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2908 }
2909
2910 static bool isTargetShuffle(unsigned Opcode) {
2911   switch(Opcode) {
2912   default: return false;
2913   case X86ISD::PSHUFD:
2914   case X86ISD::PSHUFHW:
2915   case X86ISD::PSHUFLW:
2916   case X86ISD::SHUFP:
2917   case X86ISD::PALIGN:
2918   case X86ISD::MOVLHPS:
2919   case X86ISD::MOVLHPD:
2920   case X86ISD::MOVHLPS:
2921   case X86ISD::MOVLPS:
2922   case X86ISD::MOVLPD:
2923   case X86ISD::MOVSHDUP:
2924   case X86ISD::MOVSLDUP:
2925   case X86ISD::MOVDDUP:
2926   case X86ISD::MOVSS:
2927   case X86ISD::MOVSD:
2928   case X86ISD::UNPCKL:
2929   case X86ISD::UNPCKH:
2930   case X86ISD::VPERMILP:
2931   case X86ISD::VPERM2X128:
2932   case X86ISD::VPERMI:
2933     return true;
2934   }
2935 }
2936
2937 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2938                                     SDValue V1, SelectionDAG &DAG) {
2939   switch(Opc) {
2940   default: llvm_unreachable("Unknown x86 shuffle node");
2941   case X86ISD::MOVSHDUP:
2942   case X86ISD::MOVSLDUP:
2943   case X86ISD::MOVDDUP:
2944     return DAG.getNode(Opc, dl, VT, V1);
2945   }
2946 }
2947
2948 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2949                                     SDValue V1, unsigned TargetMask,
2950                                     SelectionDAG &DAG) {
2951   switch(Opc) {
2952   default: llvm_unreachable("Unknown x86 shuffle node");
2953   case X86ISD::PSHUFD:
2954   case X86ISD::PSHUFHW:
2955   case X86ISD::PSHUFLW:
2956   case X86ISD::VPERMILP:
2957   case X86ISD::VPERMI:
2958     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2959   }
2960 }
2961
2962 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2963                                     SDValue V1, SDValue V2, unsigned TargetMask,
2964                                     SelectionDAG &DAG) {
2965   switch(Opc) {
2966   default: llvm_unreachable("Unknown x86 shuffle node");
2967   case X86ISD::PALIGN:
2968   case X86ISD::SHUFP:
2969   case X86ISD::VPERM2X128:
2970     return DAG.getNode(Opc, dl, VT, V1, V2,
2971                        DAG.getConstant(TargetMask, MVT::i8));
2972   }
2973 }
2974
2975 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2976                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2977   switch(Opc) {
2978   default: llvm_unreachable("Unknown x86 shuffle node");
2979   case X86ISD::MOVLHPS:
2980   case X86ISD::MOVLHPD:
2981   case X86ISD::MOVHLPS:
2982   case X86ISD::MOVLPS:
2983   case X86ISD::MOVLPD:
2984   case X86ISD::MOVSS:
2985   case X86ISD::MOVSD:
2986   case X86ISD::UNPCKL:
2987   case X86ISD::UNPCKH:
2988     return DAG.getNode(Opc, dl, VT, V1, V2);
2989   }
2990 }
2991
2992 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2993   MachineFunction &MF = DAG.getMachineFunction();
2994   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2995   int ReturnAddrIndex = FuncInfo->getRAIndex();
2996
2997   if (ReturnAddrIndex == 0) {
2998     // Set up a frame object for the return address.
2999     uint64_t SlotSize = TD->getPointerSize();
3000     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3001                                                            false);
3002     FuncInfo->setRAIndex(ReturnAddrIndex);
3003   }
3004
3005   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3006 }
3007
3008
3009 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3010                                        bool hasSymbolicDisplacement) {
3011   // Offset should fit into 32 bit immediate field.
3012   if (!isInt<32>(Offset))
3013     return false;
3014
3015   // If we don't have a symbolic displacement - we don't have any extra
3016   // restrictions.
3017   if (!hasSymbolicDisplacement)
3018     return true;
3019
3020   // FIXME: Some tweaks might be needed for medium code model.
3021   if (M != CodeModel::Small && M != CodeModel::Kernel)
3022     return false;
3023
3024   // For small code model we assume that latest object is 16MB before end of 31
3025   // bits boundary. We may also accept pretty large negative constants knowing
3026   // that all objects are in the positive half of address space.
3027   if (M == CodeModel::Small && Offset < 16*1024*1024)
3028     return true;
3029
3030   // For kernel code model we know that all object resist in the negative half
3031   // of 32bits address space. We may not accept negative offsets, since they may
3032   // be just off and we may accept pretty large positive ones.
3033   if (M == CodeModel::Kernel && Offset > 0)
3034     return true;
3035
3036   return false;
3037 }
3038
3039 /// isCalleePop - Determines whether the callee is required to pop its
3040 /// own arguments. Callee pop is necessary to support tail calls.
3041 bool X86::isCalleePop(CallingConv::ID CallingConv,
3042                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3043   if (IsVarArg)
3044     return false;
3045
3046   switch (CallingConv) {
3047   default:
3048     return false;
3049   case CallingConv::X86_StdCall:
3050     return !is64Bit;
3051   case CallingConv::X86_FastCall:
3052     return !is64Bit;
3053   case CallingConv::X86_ThisCall:
3054     return !is64Bit;
3055   case CallingConv::Fast:
3056     return TailCallOpt;
3057   case CallingConv::GHC:
3058     return TailCallOpt;
3059   }
3060 }
3061
3062 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3063 /// specific condition code, returning the condition code and the LHS/RHS of the
3064 /// comparison to make.
3065 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3066                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3067   if (!isFP) {
3068     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3069       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3070         // X > -1   -> X == 0, jump !sign.
3071         RHS = DAG.getConstant(0, RHS.getValueType());
3072         return X86::COND_NS;
3073       }
3074       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3075         // X < 0   -> X == 0, jump on sign.
3076         return X86::COND_S;
3077       }
3078       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3079         // X < 1   -> X <= 0
3080         RHS = DAG.getConstant(0, RHS.getValueType());
3081         return X86::COND_LE;
3082       }
3083     }
3084
3085     switch (SetCCOpcode) {
3086     default: llvm_unreachable("Invalid integer condition!");
3087     case ISD::SETEQ:  return X86::COND_E;
3088     case ISD::SETGT:  return X86::COND_G;
3089     case ISD::SETGE:  return X86::COND_GE;
3090     case ISD::SETLT:  return X86::COND_L;
3091     case ISD::SETLE:  return X86::COND_LE;
3092     case ISD::SETNE:  return X86::COND_NE;
3093     case ISD::SETULT: return X86::COND_B;
3094     case ISD::SETUGT: return X86::COND_A;
3095     case ISD::SETULE: return X86::COND_BE;
3096     case ISD::SETUGE: return X86::COND_AE;
3097     }
3098   }
3099
3100   // First determine if it is required or is profitable to flip the operands.
3101
3102   // If LHS is a foldable load, but RHS is not, flip the condition.
3103   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3104       !ISD::isNON_EXTLoad(RHS.getNode())) {
3105     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3106     std::swap(LHS, RHS);
3107   }
3108
3109   switch (SetCCOpcode) {
3110   default: break;
3111   case ISD::SETOLT:
3112   case ISD::SETOLE:
3113   case ISD::SETUGT:
3114   case ISD::SETUGE:
3115     std::swap(LHS, RHS);
3116     break;
3117   }
3118
3119   // On a floating point condition, the flags are set as follows:
3120   // ZF  PF  CF   op
3121   //  0 | 0 | 0 | X > Y
3122   //  0 | 0 | 1 | X < Y
3123   //  1 | 0 | 0 | X == Y
3124   //  1 | 1 | 1 | unordered
3125   switch (SetCCOpcode) {
3126   default: llvm_unreachable("Condcode should be pre-legalized away");
3127   case ISD::SETUEQ:
3128   case ISD::SETEQ:   return X86::COND_E;
3129   case ISD::SETOLT:              // flipped
3130   case ISD::SETOGT:
3131   case ISD::SETGT:   return X86::COND_A;
3132   case ISD::SETOLE:              // flipped
3133   case ISD::SETOGE:
3134   case ISD::SETGE:   return X86::COND_AE;
3135   case ISD::SETUGT:              // flipped
3136   case ISD::SETULT:
3137   case ISD::SETLT:   return X86::COND_B;
3138   case ISD::SETUGE:              // flipped
3139   case ISD::SETULE:
3140   case ISD::SETLE:   return X86::COND_BE;
3141   case ISD::SETONE:
3142   case ISD::SETNE:   return X86::COND_NE;
3143   case ISD::SETUO:   return X86::COND_P;
3144   case ISD::SETO:    return X86::COND_NP;
3145   case ISD::SETOEQ:
3146   case ISD::SETUNE:  return X86::COND_INVALID;
3147   }
3148 }
3149
3150 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3151 /// code. Current x86 isa includes the following FP cmov instructions:
3152 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3153 static bool hasFPCMov(unsigned X86CC) {
3154   switch (X86CC) {
3155   default:
3156     return false;
3157   case X86::COND_B:
3158   case X86::COND_BE:
3159   case X86::COND_E:
3160   case X86::COND_P:
3161   case X86::COND_A:
3162   case X86::COND_AE:
3163   case X86::COND_NE:
3164   case X86::COND_NP:
3165     return true;
3166   }
3167 }
3168
3169 /// isFPImmLegal - Returns true if the target can instruction select the
3170 /// specified FP immediate natively. If false, the legalizer will
3171 /// materialize the FP immediate as a load from a constant pool.
3172 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3173   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3174     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3175       return true;
3176   }
3177   return false;
3178 }
3179
3180 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3181 /// the specified range (L, H].
3182 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3183   return (Val < 0) || (Val >= Low && Val < Hi);
3184 }
3185
3186 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3187 /// specified value.
3188 static bool isUndefOrEqual(int Val, int CmpVal) {
3189   if (Val < 0 || Val == CmpVal)
3190     return true;
3191   return false;
3192 }
3193
3194 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3195 /// from position Pos and ending in Pos+Size, falls within the specified
3196 /// sequential range (L, L+Pos]. or is undef.
3197 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3198                                        unsigned Pos, unsigned Size, int Low) {
3199   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3200     if (!isUndefOrEqual(Mask[i], Low))
3201       return false;
3202   return true;
3203 }
3204
3205 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3206 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3207 /// the second operand.
3208 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3209   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3210     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3211   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3212     return (Mask[0] < 2 && Mask[1] < 2);
3213   return false;
3214 }
3215
3216 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3217 /// is suitable for input to PSHUFHW.
3218 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3219   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3220     return false;
3221
3222   // Lower quadword copied in order or undef.
3223   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3224     return false;
3225
3226   // Upper quadword shuffled.
3227   for (unsigned i = 4; i != 8; ++i)
3228     if (!isUndefOrInRange(Mask[i], 4, 8))
3229       return false;
3230
3231   if (VT == MVT::v16i16) {
3232     // Lower quadword copied in order or undef.
3233     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3234       return false;
3235
3236     // Upper quadword shuffled.
3237     for (unsigned i = 12; i != 16; ++i)
3238       if (!isUndefOrInRange(Mask[i], 12, 16))
3239         return false;
3240   }
3241
3242   return true;
3243 }
3244
3245 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3246 /// is suitable for input to PSHUFLW.
3247 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3248   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3249     return false;
3250
3251   // Upper quadword copied in order.
3252   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3253     return false;
3254
3255   // Lower quadword shuffled.
3256   for (unsigned i = 0; i != 4; ++i)
3257     if (!isUndefOrInRange(Mask[i], 0, 4))
3258       return false;
3259
3260   if (VT == MVT::v16i16) {
3261     // Upper quadword copied in order.
3262     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3263       return false;
3264
3265     // Lower quadword shuffled.
3266     for (unsigned i = 8; i != 12; ++i)
3267       if (!isUndefOrInRange(Mask[i], 8, 12))
3268         return false;
3269   }
3270
3271   return true;
3272 }
3273
3274 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3275 /// is suitable for input to PALIGNR.
3276 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3277                           const X86Subtarget *Subtarget) {
3278   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3279       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3280     return false;
3281
3282   unsigned NumElts = VT.getVectorNumElements();
3283   unsigned NumLanes = VT.getSizeInBits()/128;
3284   unsigned NumLaneElts = NumElts/NumLanes;
3285
3286   // Do not handle 64-bit element shuffles with palignr.
3287   if (NumLaneElts == 2)
3288     return false;
3289
3290   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3291     unsigned i;
3292     for (i = 0; i != NumLaneElts; ++i) {
3293       if (Mask[i+l] >= 0)
3294         break;
3295     }
3296
3297     // Lane is all undef, go to next lane
3298     if (i == NumLaneElts)
3299       continue;
3300
3301     int Start = Mask[i+l];
3302
3303     // Make sure its in this lane in one of the sources
3304     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3305         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3306       return false;
3307
3308     // If not lane 0, then we must match lane 0
3309     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3310       return false;
3311
3312     // Correct second source to be contiguous with first source
3313     if (Start >= (int)NumElts)
3314       Start -= NumElts - NumLaneElts;
3315
3316     // Make sure we're shifting in the right direction.
3317     if (Start <= (int)(i+l))
3318       return false;
3319
3320     Start -= i;
3321
3322     // Check the rest of the elements to see if they are consecutive.
3323     for (++i; i != NumLaneElts; ++i) {
3324       int Idx = Mask[i+l];
3325
3326       // Make sure its in this lane
3327       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3328           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3329         return false;
3330
3331       // If not lane 0, then we must match lane 0
3332       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3333         return false;
3334
3335       if (Idx >= (int)NumElts)
3336         Idx -= NumElts - NumLaneElts;
3337
3338       if (!isUndefOrEqual(Idx, Start+i))
3339         return false;
3340
3341     }
3342   }
3343
3344   return true;
3345 }
3346
3347 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3348 /// the two vector operands have swapped position.
3349 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3350                                      unsigned NumElems) {
3351   for (unsigned i = 0; i != NumElems; ++i) {
3352     int idx = Mask[i];
3353     if (idx < 0)
3354       continue;
3355     else if (idx < (int)NumElems)
3356       Mask[i] = idx + NumElems;
3357     else
3358       Mask[i] = idx - NumElems;
3359   }
3360 }
3361
3362 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3363 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3364 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3365 /// reverse of what x86 shuffles want.
3366 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3367                         bool Commuted = false) {
3368   if (!HasAVX && VT.getSizeInBits() == 256)
3369     return false;
3370
3371   unsigned NumElems = VT.getVectorNumElements();
3372   unsigned NumLanes = VT.getSizeInBits()/128;
3373   unsigned NumLaneElems = NumElems/NumLanes;
3374
3375   if (NumLaneElems != 2 && NumLaneElems != 4)
3376     return false;
3377
3378   // VSHUFPSY divides the resulting vector into 4 chunks.
3379   // The sources are also splitted into 4 chunks, and each destination
3380   // chunk must come from a different source chunk.
3381   //
3382   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3383   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3384   //
3385   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3386   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3387   //
3388   // VSHUFPDY divides the resulting vector into 4 chunks.
3389   // The sources are also splitted into 4 chunks, and each destination
3390   // chunk must come from a different source chunk.
3391   //
3392   //  SRC1 =>      X3       X2       X1       X0
3393   //  SRC2 =>      Y3       Y2       Y1       Y0
3394   //
3395   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3396   //
3397   unsigned HalfLaneElems = NumLaneElems/2;
3398   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3399     for (unsigned i = 0; i != NumLaneElems; ++i) {
3400       int Idx = Mask[i+l];
3401       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3402       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3403         return false;
3404       // For VSHUFPSY, the mask of the second half must be the same as the
3405       // first but with the appropriate offsets. This works in the same way as
3406       // VPERMILPS works with masks.
3407       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3408         continue;
3409       if (!isUndefOrEqual(Idx, Mask[i]+l))
3410         return false;
3411     }
3412   }
3413
3414   return true;
3415 }
3416
3417 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3418 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3419 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3420   unsigned NumElems = VT.getVectorNumElements();
3421
3422   if (VT.getSizeInBits() != 128)
3423     return false;
3424
3425   if (NumElems != 4)
3426     return false;
3427
3428   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3429   return isUndefOrEqual(Mask[0], 6) &&
3430          isUndefOrEqual(Mask[1], 7) &&
3431          isUndefOrEqual(Mask[2], 2) &&
3432          isUndefOrEqual(Mask[3], 3);
3433 }
3434
3435 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3436 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3437 /// <2, 3, 2, 3>
3438 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3439   unsigned NumElems = VT.getVectorNumElements();
3440
3441   if (VT.getSizeInBits() != 128)
3442     return false;
3443
3444   if (NumElems != 4)
3445     return false;
3446
3447   return isUndefOrEqual(Mask[0], 2) &&
3448          isUndefOrEqual(Mask[1], 3) &&
3449          isUndefOrEqual(Mask[2], 2) &&
3450          isUndefOrEqual(Mask[3], 3);
3451 }
3452
3453 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3454 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3455 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3456   if (VT.getSizeInBits() != 128)
3457     return false;
3458
3459   unsigned NumElems = VT.getVectorNumElements();
3460
3461   if (NumElems != 2 && NumElems != 4)
3462     return false;
3463
3464   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3465     if (!isUndefOrEqual(Mask[i], i + NumElems))
3466       return false;
3467
3468   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3469     if (!isUndefOrEqual(Mask[i], i))
3470       return false;
3471
3472   return true;
3473 }
3474
3475 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3476 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3477 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3478   unsigned NumElems = VT.getVectorNumElements();
3479
3480   if ((NumElems != 2 && NumElems != 4)
3481       || VT.getSizeInBits() > 128)
3482     return false;
3483
3484   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3485     if (!isUndefOrEqual(Mask[i], i))
3486       return false;
3487
3488   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3489     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3490       return false;
3491
3492   return true;
3493 }
3494
3495 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3496 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3497 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3498                          bool HasAVX2, bool V2IsSplat = false) {
3499   unsigned NumElts = VT.getVectorNumElements();
3500
3501   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3502          "Unsupported vector type for unpckh");
3503
3504   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3505       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3506     return false;
3507
3508   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3509   // independently on 128-bit lanes.
3510   unsigned NumLanes = VT.getSizeInBits()/128;
3511   unsigned NumLaneElts = NumElts/NumLanes;
3512
3513   for (unsigned l = 0; l != NumLanes; ++l) {
3514     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3515          i != (l+1)*NumLaneElts;
3516          i += 2, ++j) {
3517       int BitI  = Mask[i];
3518       int BitI1 = Mask[i+1];
3519       if (!isUndefOrEqual(BitI, j))
3520         return false;
3521       if (V2IsSplat) {
3522         if (!isUndefOrEqual(BitI1, NumElts))
3523           return false;
3524       } else {
3525         if (!isUndefOrEqual(BitI1, j + NumElts))
3526           return false;
3527       }
3528     }
3529   }
3530
3531   return true;
3532 }
3533
3534 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3535 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3536 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3537                          bool HasAVX2, bool V2IsSplat = false) {
3538   unsigned NumElts = VT.getVectorNumElements();
3539
3540   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3541          "Unsupported vector type for unpckh");
3542
3543   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3544       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3545     return false;
3546
3547   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3548   // independently on 128-bit lanes.
3549   unsigned NumLanes = VT.getSizeInBits()/128;
3550   unsigned NumLaneElts = NumElts/NumLanes;
3551
3552   for (unsigned l = 0; l != NumLanes; ++l) {
3553     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3554          i != (l+1)*NumLaneElts; i += 2, ++j) {
3555       int BitI  = Mask[i];
3556       int BitI1 = Mask[i+1];
3557       if (!isUndefOrEqual(BitI, j))
3558         return false;
3559       if (V2IsSplat) {
3560         if (isUndefOrEqual(BitI1, NumElts))
3561           return false;
3562       } else {
3563         if (!isUndefOrEqual(BitI1, j+NumElts))
3564           return false;
3565       }
3566     }
3567   }
3568   return true;
3569 }
3570
3571 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3572 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3573 /// <0, 0, 1, 1>
3574 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3575                                   bool HasAVX2) {
3576   unsigned NumElts = VT.getVectorNumElements();
3577
3578   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3579          "Unsupported vector type for unpckh");
3580
3581   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3582       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3583     return false;
3584
3585   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3586   // FIXME: Need a better way to get rid of this, there's no latency difference
3587   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3588   // the former later. We should also remove the "_undef" special mask.
3589   if (NumElts == 4 && VT.getSizeInBits() == 256)
3590     return false;
3591
3592   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3593   // independently on 128-bit lanes.
3594   unsigned NumLanes = VT.getSizeInBits()/128;
3595   unsigned NumLaneElts = NumElts/NumLanes;
3596
3597   for (unsigned l = 0; l != NumLanes; ++l) {
3598     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3599          i != (l+1)*NumLaneElts;
3600          i += 2, ++j) {
3601       int BitI  = Mask[i];
3602       int BitI1 = Mask[i+1];
3603
3604       if (!isUndefOrEqual(BitI, j))
3605         return false;
3606       if (!isUndefOrEqual(BitI1, j))
3607         return false;
3608     }
3609   }
3610
3611   return true;
3612 }
3613
3614 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3615 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3616 /// <2, 2, 3, 3>
3617 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3618   unsigned NumElts = VT.getVectorNumElements();
3619
3620   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3621          "Unsupported vector type for unpckh");
3622
3623   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3624       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3625     return false;
3626
3627   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3628   // independently on 128-bit lanes.
3629   unsigned NumLanes = VT.getSizeInBits()/128;
3630   unsigned NumLaneElts = NumElts/NumLanes;
3631
3632   for (unsigned l = 0; l != NumLanes; ++l) {
3633     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3634          i != (l+1)*NumLaneElts; i += 2, ++j) {
3635       int BitI  = Mask[i];
3636       int BitI1 = Mask[i+1];
3637       if (!isUndefOrEqual(BitI, j))
3638         return false;
3639       if (!isUndefOrEqual(BitI1, j))
3640         return false;
3641     }
3642   }
3643   return true;
3644 }
3645
3646 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3647 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3648 /// MOVSD, and MOVD, i.e. setting the lowest element.
3649 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3650   if (VT.getVectorElementType().getSizeInBits() < 32)
3651     return false;
3652   if (VT.getSizeInBits() == 256)
3653     return false;
3654
3655   unsigned NumElts = VT.getVectorNumElements();
3656
3657   if (!isUndefOrEqual(Mask[0], NumElts))
3658     return false;
3659
3660   for (unsigned i = 1; i != NumElts; ++i)
3661     if (!isUndefOrEqual(Mask[i], i))
3662       return false;
3663
3664   return true;
3665 }
3666
3667 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3668 /// as permutations between 128-bit chunks or halves. As an example: this
3669 /// shuffle bellow:
3670 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3671 /// The first half comes from the second half of V1 and the second half from the
3672 /// the second half of V2.
3673 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3674   if (!HasAVX || VT.getSizeInBits() != 256)
3675     return false;
3676
3677   // The shuffle result is divided into half A and half B. In total the two
3678   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3679   // B must come from C, D, E or F.
3680   unsigned HalfSize = VT.getVectorNumElements()/2;
3681   bool MatchA = false, MatchB = false;
3682
3683   // Check if A comes from one of C, D, E, F.
3684   for (unsigned Half = 0; Half != 4; ++Half) {
3685     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3686       MatchA = true;
3687       break;
3688     }
3689   }
3690
3691   // Check if B comes from one of C, D, E, F.
3692   for (unsigned Half = 0; Half != 4; ++Half) {
3693     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3694       MatchB = true;
3695       break;
3696     }
3697   }
3698
3699   return MatchA && MatchB;
3700 }
3701
3702 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3703 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3704 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3705   EVT VT = SVOp->getValueType(0);
3706
3707   unsigned HalfSize = VT.getVectorNumElements()/2;
3708
3709   unsigned FstHalf = 0, SndHalf = 0;
3710   for (unsigned i = 0; i < HalfSize; ++i) {
3711     if (SVOp->getMaskElt(i) > 0) {
3712       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3713       break;
3714     }
3715   }
3716   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3717     if (SVOp->getMaskElt(i) > 0) {
3718       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3719       break;
3720     }
3721   }
3722
3723   return (FstHalf | (SndHalf << 4));
3724 }
3725
3726 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3727 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3728 /// Note that VPERMIL mask matching is different depending whether theunderlying
3729 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3730 /// to the same elements of the low, but to the higher half of the source.
3731 /// In VPERMILPD the two lanes could be shuffled independently of each other
3732 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3733 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3734   if (!HasAVX)
3735     return false;
3736
3737   unsigned NumElts = VT.getVectorNumElements();
3738   // Only match 256-bit with 32/64-bit types
3739   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3740     return false;
3741
3742   unsigned NumLanes = VT.getSizeInBits()/128;
3743   unsigned LaneSize = NumElts/NumLanes;
3744   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3745     for (unsigned i = 0; i != LaneSize; ++i) {
3746       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3747         return false;
3748       if (NumElts != 8 || l == 0)
3749         continue;
3750       // VPERMILPS handling
3751       if (Mask[i] < 0)
3752         continue;
3753       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3754         return false;
3755     }
3756   }
3757
3758   return true;
3759 }
3760
3761 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3762 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3763 /// element of vector 2 and the other elements to come from vector 1 in order.
3764 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3765                                bool V2IsSplat = false, bool V2IsUndef = false) {
3766   unsigned NumOps = VT.getVectorNumElements();
3767   if (VT.getSizeInBits() == 256)
3768     return false;
3769   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3770     return false;
3771
3772   if (!isUndefOrEqual(Mask[0], 0))
3773     return false;
3774
3775   for (unsigned i = 1; i != NumOps; ++i)
3776     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3777           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3778           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3779       return false;
3780
3781   return true;
3782 }
3783
3784 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3785 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3786 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3787 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3788                            const X86Subtarget *Subtarget) {
3789   if (!Subtarget->hasSSE3())
3790     return false;
3791
3792   unsigned NumElems = VT.getVectorNumElements();
3793
3794   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3795       (VT.getSizeInBits() == 256 && NumElems != 8))
3796     return false;
3797
3798   // "i+1" is the value the indexed mask element must have
3799   for (unsigned i = 0; i != NumElems; i += 2)
3800     if (!isUndefOrEqual(Mask[i], i+1) ||
3801         !isUndefOrEqual(Mask[i+1], i+1))
3802       return false;
3803
3804   return true;
3805 }
3806
3807 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3808 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3809 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3810 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3811                            const X86Subtarget *Subtarget) {
3812   if (!Subtarget->hasSSE3())
3813     return false;
3814
3815   unsigned NumElems = VT.getVectorNumElements();
3816
3817   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3818       (VT.getSizeInBits() == 256 && NumElems != 8))
3819     return false;
3820
3821   // "i" is the value the indexed mask element must have
3822   for (unsigned i = 0; i != NumElems; i += 2)
3823     if (!isUndefOrEqual(Mask[i], i) ||
3824         !isUndefOrEqual(Mask[i+1], i))
3825       return false;
3826
3827   return true;
3828 }
3829
3830 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3831 /// specifies a shuffle of elements that is suitable for input to 256-bit
3832 /// version of MOVDDUP.
3833 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3834   unsigned NumElts = VT.getVectorNumElements();
3835
3836   if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3837     return false;
3838
3839   for (unsigned i = 0; i != NumElts/2; ++i)
3840     if (!isUndefOrEqual(Mask[i], 0))
3841       return false;
3842   for (unsigned i = NumElts/2; i != NumElts; ++i)
3843     if (!isUndefOrEqual(Mask[i], NumElts/2))
3844       return false;
3845   return true;
3846 }
3847
3848 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3849 /// specifies a shuffle of elements that is suitable for input to 128-bit
3850 /// version of MOVDDUP.
3851 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3852   if (VT.getSizeInBits() != 128)
3853     return false;
3854
3855   unsigned e = VT.getVectorNumElements() / 2;
3856   for (unsigned i = 0; i != e; ++i)
3857     if (!isUndefOrEqual(Mask[i], i))
3858       return false;
3859   for (unsigned i = 0; i != e; ++i)
3860     if (!isUndefOrEqual(Mask[e+i], i))
3861       return false;
3862   return true;
3863 }
3864
3865 /// isVEXTRACTF128Index - Return true if the specified
3866 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3867 /// suitable for input to VEXTRACTF128.
3868 bool X86::isVEXTRACTF128Index(SDNode *N) {
3869   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3870     return false;
3871
3872   // The index should be aligned on a 128-bit boundary.
3873   uint64_t Index =
3874     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3875
3876   unsigned VL = N->getValueType(0).getVectorNumElements();
3877   unsigned VBits = N->getValueType(0).getSizeInBits();
3878   unsigned ElSize = VBits / VL;
3879   bool Result = (Index * ElSize) % 128 == 0;
3880
3881   return Result;
3882 }
3883
3884 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3885 /// operand specifies a subvector insert that is suitable for input to
3886 /// VINSERTF128.
3887 bool X86::isVINSERTF128Index(SDNode *N) {
3888   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3889     return false;
3890
3891   // The index should be aligned on a 128-bit boundary.
3892   uint64_t Index =
3893     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3894
3895   unsigned VL = N->getValueType(0).getVectorNumElements();
3896   unsigned VBits = N->getValueType(0).getSizeInBits();
3897   unsigned ElSize = VBits / VL;
3898   bool Result = (Index * ElSize) % 128 == 0;
3899
3900   return Result;
3901 }
3902
3903 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3904 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3905 /// Handles 128-bit and 256-bit.
3906 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3907   EVT VT = N->getValueType(0);
3908
3909   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3910          "Unsupported vector type for PSHUF/SHUFP");
3911
3912   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3913   // independently on 128-bit lanes.
3914   unsigned NumElts = VT.getVectorNumElements();
3915   unsigned NumLanes = VT.getSizeInBits()/128;
3916   unsigned NumLaneElts = NumElts/NumLanes;
3917
3918   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3919          "Only supports 2 or 4 elements per lane");
3920
3921   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3922   unsigned Mask = 0;
3923   for (unsigned i = 0; i != NumElts; ++i) {
3924     int Elt = N->getMaskElt(i);
3925     if (Elt < 0) continue;
3926     Elt &= NumLaneElts - 1;
3927     unsigned ShAmt = (i << Shift) % 8;
3928     Mask |= Elt << ShAmt;
3929   }
3930
3931   return Mask;
3932 }
3933
3934 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3935 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3936 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3937   EVT VT = N->getValueType(0);
3938
3939   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3940          "Unsupported vector type for PSHUFHW");
3941
3942   unsigned NumElts = VT.getVectorNumElements();
3943
3944   unsigned Mask = 0;
3945   for (unsigned l = 0; l != NumElts; l += 8) {
3946     // 8 nodes per lane, but we only care about the last 4.
3947     for (unsigned i = 0; i < 4; ++i) {
3948       int Elt = N->getMaskElt(l+i+4);
3949       if (Elt < 0) continue;
3950       Elt &= 0x3; // only 2-bits.
3951       Mask |= Elt << (i * 2);
3952     }
3953   }
3954
3955   return Mask;
3956 }
3957
3958 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3959 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3960 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
3961   EVT VT = N->getValueType(0);
3962
3963   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3964          "Unsupported vector type for PSHUFHW");
3965
3966   unsigned NumElts = VT.getVectorNumElements();
3967
3968   unsigned Mask = 0;
3969   for (unsigned l = 0; l != NumElts; l += 8) {
3970     // 8 nodes per lane, but we only care about the first 4.
3971     for (unsigned i = 0; i < 4; ++i) {
3972       int Elt = N->getMaskElt(l+i);
3973       if (Elt < 0) continue;
3974       Elt &= 0x3; // only 2-bits
3975       Mask |= Elt << (i * 2);
3976     }
3977   }
3978
3979   return Mask;
3980 }
3981
3982 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3983 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3984 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
3985   EVT VT = SVOp->getValueType(0);
3986   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
3987
3988   unsigned NumElts = VT.getVectorNumElements();
3989   unsigned NumLanes = VT.getSizeInBits()/128;
3990   unsigned NumLaneElts = NumElts/NumLanes;
3991
3992   int Val = 0;
3993   unsigned i;
3994   for (i = 0; i != NumElts; ++i) {
3995     Val = SVOp->getMaskElt(i);
3996     if (Val >= 0)
3997       break;
3998   }
3999   if (Val >= (int)NumElts)
4000     Val -= NumElts - NumLaneElts;
4001
4002   assert(Val - i > 0 && "PALIGNR imm should be positive");
4003   return (Val - i) * EltSize;
4004 }
4005
4006 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4007 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4008 /// instructions.
4009 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4010   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4011     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4012
4013   uint64_t Index =
4014     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4015
4016   EVT VecVT = N->getOperand(0).getValueType();
4017   EVT ElVT = VecVT.getVectorElementType();
4018
4019   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4020   return Index / NumElemsPerChunk;
4021 }
4022
4023 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4024 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4025 /// instructions.
4026 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4027   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4028     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4029
4030   uint64_t Index =
4031     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4032
4033   EVT VecVT = N->getValueType(0);
4034   EVT ElVT = VecVT.getVectorElementType();
4035
4036   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4037   return Index / NumElemsPerChunk;
4038 }
4039
4040 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4041 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4042 /// Handles 256-bit.
4043 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4044   EVT VT = N->getValueType(0);
4045
4046   unsigned NumElts = VT.getVectorNumElements();
4047
4048   assert((VT.is256BitVector() && NumElts == 4) &&
4049          "Unsupported vector type for VPERMQ/VPERMPD");
4050
4051   unsigned Mask = 0;
4052   for (unsigned i = 0; i != NumElts; ++i) {
4053     int Elt = N->getMaskElt(i);
4054     if (Elt < 0)
4055       continue;
4056     Mask |= Elt << (i*2);
4057   }
4058
4059   return Mask;
4060 }
4061 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4062 /// constant +0.0.
4063 bool X86::isZeroNode(SDValue Elt) {
4064   return ((isa<ConstantSDNode>(Elt) &&
4065            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4066           (isa<ConstantFPSDNode>(Elt) &&
4067            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4068 }
4069
4070 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4071 /// their permute mask.
4072 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4073                                     SelectionDAG &DAG) {
4074   EVT VT = SVOp->getValueType(0);
4075   unsigned NumElems = VT.getVectorNumElements();
4076   SmallVector<int, 8> MaskVec;
4077
4078   for (unsigned i = 0; i != NumElems; ++i) {
4079     int Idx = SVOp->getMaskElt(i);
4080     if (Idx >= 0) {
4081       if (Idx < (int)NumElems)
4082         Idx += NumElems;
4083       else
4084         Idx -= NumElems;
4085     }
4086     MaskVec.push_back(Idx);
4087   }
4088   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4089                               SVOp->getOperand(0), &MaskVec[0]);
4090 }
4091
4092 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4093 /// match movhlps. The lower half elements should come from upper half of
4094 /// V1 (and in order), and the upper half elements should come from the upper
4095 /// half of V2 (and in order).
4096 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4097   if (VT.getSizeInBits() != 128)
4098     return false;
4099   if (VT.getVectorNumElements() != 4)
4100     return false;
4101   for (unsigned i = 0, e = 2; i != e; ++i)
4102     if (!isUndefOrEqual(Mask[i], i+2))
4103       return false;
4104   for (unsigned i = 2; i != 4; ++i)
4105     if (!isUndefOrEqual(Mask[i], i+4))
4106       return false;
4107   return true;
4108 }
4109
4110 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4111 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4112 /// required.
4113 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4114   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4115     return false;
4116   N = N->getOperand(0).getNode();
4117   if (!ISD::isNON_EXTLoad(N))
4118     return false;
4119   if (LD)
4120     *LD = cast<LoadSDNode>(N);
4121   return true;
4122 }
4123
4124 // Test whether the given value is a vector value which will be legalized
4125 // into a load.
4126 static bool WillBeConstantPoolLoad(SDNode *N) {
4127   if (N->getOpcode() != ISD::BUILD_VECTOR)
4128     return false;
4129
4130   // Check for any non-constant elements.
4131   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4132     switch (N->getOperand(i).getNode()->getOpcode()) {
4133     case ISD::UNDEF:
4134     case ISD::ConstantFP:
4135     case ISD::Constant:
4136       break;
4137     default:
4138       return false;
4139     }
4140
4141   // Vectors of all-zeros and all-ones are materialized with special
4142   // instructions rather than being loaded.
4143   return !ISD::isBuildVectorAllZeros(N) &&
4144          !ISD::isBuildVectorAllOnes(N);
4145 }
4146
4147 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4148 /// match movlp{s|d}. The lower half elements should come from lower half of
4149 /// V1 (and in order), and the upper half elements should come from the upper
4150 /// half of V2 (and in order). And since V1 will become the source of the
4151 /// MOVLP, it must be either a vector load or a scalar load to vector.
4152 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4153                                ArrayRef<int> Mask, EVT VT) {
4154   if (VT.getSizeInBits() != 128)
4155     return false;
4156
4157   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4158     return false;
4159   // Is V2 is a vector load, don't do this transformation. We will try to use
4160   // load folding shufps op.
4161   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4162     return false;
4163
4164   unsigned NumElems = VT.getVectorNumElements();
4165
4166   if (NumElems != 2 && NumElems != 4)
4167     return false;
4168   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4169     if (!isUndefOrEqual(Mask[i], i))
4170       return false;
4171   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4172     if (!isUndefOrEqual(Mask[i], i+NumElems))
4173       return false;
4174   return true;
4175 }
4176
4177 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4178 /// all the same.
4179 static bool isSplatVector(SDNode *N) {
4180   if (N->getOpcode() != ISD::BUILD_VECTOR)
4181     return false;
4182
4183   SDValue SplatValue = N->getOperand(0);
4184   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4185     if (N->getOperand(i) != SplatValue)
4186       return false;
4187   return true;
4188 }
4189
4190 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4191 /// to an zero vector.
4192 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4193 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4194   SDValue V1 = N->getOperand(0);
4195   SDValue V2 = N->getOperand(1);
4196   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4197   for (unsigned i = 0; i != NumElems; ++i) {
4198     int Idx = N->getMaskElt(i);
4199     if (Idx >= (int)NumElems) {
4200       unsigned Opc = V2.getOpcode();
4201       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4202         continue;
4203       if (Opc != ISD::BUILD_VECTOR ||
4204           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4205         return false;
4206     } else if (Idx >= 0) {
4207       unsigned Opc = V1.getOpcode();
4208       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4209         continue;
4210       if (Opc != ISD::BUILD_VECTOR ||
4211           !X86::isZeroNode(V1.getOperand(Idx)))
4212         return false;
4213     }
4214   }
4215   return true;
4216 }
4217
4218 /// getZeroVector - Returns a vector of specified type with all zero elements.
4219 ///
4220 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4221                              SelectionDAG &DAG, DebugLoc dl) {
4222   assert(VT.isVector() && "Expected a vector type");
4223   unsigned Size = VT.getSizeInBits();
4224
4225   // Always build SSE zero vectors as <4 x i32> bitcasted
4226   // to their dest type. This ensures they get CSE'd.
4227   SDValue Vec;
4228   if (Size == 128) {  // SSE
4229     if (Subtarget->hasSSE2()) {  // SSE2
4230       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4231       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4232     } else { // SSE1
4233       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4234       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4235     }
4236   } else if (Size == 256) { // AVX
4237     if (Subtarget->hasAVX2()) { // AVX2
4238       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4239       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4240       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4241     } else {
4242       // 256-bit logic and arithmetic instructions in AVX are all
4243       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4244       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4245       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4246       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4247     }
4248   } else
4249     llvm_unreachable("Unexpected vector type");
4250
4251   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4252 }
4253
4254 /// getOnesVector - Returns a vector of specified type with all bits set.
4255 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4256 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4257 /// Then bitcast to their original type, ensuring they get CSE'd.
4258 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4259                              DebugLoc dl) {
4260   assert(VT.isVector() && "Expected a vector type");
4261   unsigned Size = VT.getSizeInBits();
4262
4263   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4264   SDValue Vec;
4265   if (Size == 256) {
4266     if (HasAVX2) { // AVX2
4267       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4268       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4269     } else { // AVX
4270       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4271       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4272     }
4273   } else if (Size == 128) {
4274     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4275   } else
4276     llvm_unreachable("Unexpected vector type");
4277
4278   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4279 }
4280
4281 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4282 /// that point to V2 points to its first element.
4283 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4284   for (unsigned i = 0; i != NumElems; ++i) {
4285     if (Mask[i] > (int)NumElems) {
4286       Mask[i] = NumElems;
4287     }
4288   }
4289 }
4290
4291 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4292 /// operation of specified width.
4293 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4294                        SDValue V2) {
4295   unsigned NumElems = VT.getVectorNumElements();
4296   SmallVector<int, 8> Mask;
4297   Mask.push_back(NumElems);
4298   for (unsigned i = 1; i != NumElems; ++i)
4299     Mask.push_back(i);
4300   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4301 }
4302
4303 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4304 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4305                           SDValue V2) {
4306   unsigned NumElems = VT.getVectorNumElements();
4307   SmallVector<int, 8> Mask;
4308   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4309     Mask.push_back(i);
4310     Mask.push_back(i + NumElems);
4311   }
4312   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4313 }
4314
4315 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4316 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4317                           SDValue V2) {
4318   unsigned NumElems = VT.getVectorNumElements();
4319   SmallVector<int, 8> Mask;
4320   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4321     Mask.push_back(i + Half);
4322     Mask.push_back(i + NumElems + Half);
4323   }
4324   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4325 }
4326
4327 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4328 // a generic shuffle instruction because the target has no such instructions.
4329 // Generate shuffles which repeat i16 and i8 several times until they can be
4330 // represented by v4f32 and then be manipulated by target suported shuffles.
4331 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4332   EVT VT = V.getValueType();
4333   int NumElems = VT.getVectorNumElements();
4334   DebugLoc dl = V.getDebugLoc();
4335
4336   while (NumElems > 4) {
4337     if (EltNo < NumElems/2) {
4338       V = getUnpackl(DAG, dl, VT, V, V);
4339     } else {
4340       V = getUnpackh(DAG, dl, VT, V, V);
4341       EltNo -= NumElems/2;
4342     }
4343     NumElems >>= 1;
4344   }
4345   return V;
4346 }
4347
4348 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4349 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4350   EVT VT = V.getValueType();
4351   DebugLoc dl = V.getDebugLoc();
4352   unsigned Size = VT.getSizeInBits();
4353
4354   if (Size == 128) {
4355     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4356     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4357     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4358                              &SplatMask[0]);
4359   } else if (Size == 256) {
4360     // To use VPERMILPS to splat scalars, the second half of indicies must
4361     // refer to the higher part, which is a duplication of the lower one,
4362     // because VPERMILPS can only handle in-lane permutations.
4363     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4364                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4365
4366     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4367     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4368                              &SplatMask[0]);
4369   } else
4370     llvm_unreachable("Vector size not supported");
4371
4372   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4373 }
4374
4375 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4376 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4377   EVT SrcVT = SV->getValueType(0);
4378   SDValue V1 = SV->getOperand(0);
4379   DebugLoc dl = SV->getDebugLoc();
4380
4381   int EltNo = SV->getSplatIndex();
4382   int NumElems = SrcVT.getVectorNumElements();
4383   unsigned Size = SrcVT.getSizeInBits();
4384
4385   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4386           "Unknown how to promote splat for type");
4387
4388   // Extract the 128-bit part containing the splat element and update
4389   // the splat element index when it refers to the higher register.
4390   if (Size == 256) {
4391     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4392     if (EltNo >= NumElems/2)
4393       EltNo -= NumElems/2;
4394   }
4395
4396   // All i16 and i8 vector types can't be used directly by a generic shuffle
4397   // instruction because the target has no such instruction. Generate shuffles
4398   // which repeat i16 and i8 several times until they fit in i32, and then can
4399   // be manipulated by target suported shuffles.
4400   EVT EltVT = SrcVT.getVectorElementType();
4401   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4402     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4403
4404   // Recreate the 256-bit vector and place the same 128-bit vector
4405   // into the low and high part. This is necessary because we want
4406   // to use VPERM* to shuffle the vectors
4407   if (Size == 256) {
4408     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4409   }
4410
4411   return getLegalSplat(DAG, V1, EltNo);
4412 }
4413
4414 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4415 /// vector of zero or undef vector.  This produces a shuffle where the low
4416 /// element of V2 is swizzled into the zero/undef vector, landing at element
4417 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4418 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4419                                            bool IsZero,
4420                                            const X86Subtarget *Subtarget,
4421                                            SelectionDAG &DAG) {
4422   EVT VT = V2.getValueType();
4423   SDValue V1 = IsZero
4424     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4425   unsigned NumElems = VT.getVectorNumElements();
4426   SmallVector<int, 16> MaskVec;
4427   for (unsigned i = 0; i != NumElems; ++i)
4428     // If this is the insertion idx, put the low elt of V2 here.
4429     MaskVec.push_back(i == Idx ? NumElems : i);
4430   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4431 }
4432
4433 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4434 /// target specific opcode. Returns true if the Mask could be calculated.
4435 /// Sets IsUnary to true if only uses one source.
4436 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4437                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4438   unsigned NumElems = VT.getVectorNumElements();
4439   SDValue ImmN;
4440
4441   IsUnary = false;
4442   switch(N->getOpcode()) {
4443   case X86ISD::SHUFP:
4444     ImmN = N->getOperand(N->getNumOperands()-1);
4445     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4446     break;
4447   case X86ISD::UNPCKH:
4448     DecodeUNPCKHMask(VT, Mask);
4449     break;
4450   case X86ISD::UNPCKL:
4451     DecodeUNPCKLMask(VT, Mask);
4452     break;
4453   case X86ISD::MOVHLPS:
4454     DecodeMOVHLPSMask(NumElems, Mask);
4455     break;
4456   case X86ISD::MOVLHPS:
4457     DecodeMOVLHPSMask(NumElems, Mask);
4458     break;
4459   case X86ISD::PSHUFD:
4460   case X86ISD::VPERMILP:
4461     ImmN = N->getOperand(N->getNumOperands()-1);
4462     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4463     IsUnary = true;
4464     break;
4465   case X86ISD::PSHUFHW:
4466     ImmN = N->getOperand(N->getNumOperands()-1);
4467     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4468     IsUnary = true;
4469     break;
4470   case X86ISD::PSHUFLW:
4471     ImmN = N->getOperand(N->getNumOperands()-1);
4472     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4473     IsUnary = true;
4474     break;
4475   case X86ISD::VPERMI:
4476     ImmN = N->getOperand(N->getNumOperands()-1);
4477     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4478     IsUnary = true;
4479     break;
4480   case X86ISD::MOVSS:
4481   case X86ISD::MOVSD: {
4482     // The index 0 always comes from the first element of the second source,
4483     // this is why MOVSS and MOVSD are used in the first place. The other
4484     // elements come from the other positions of the first source vector
4485     Mask.push_back(NumElems);
4486     for (unsigned i = 1; i != NumElems; ++i) {
4487       Mask.push_back(i);
4488     }
4489     break;
4490   }
4491   case X86ISD::VPERM2X128:
4492     ImmN = N->getOperand(N->getNumOperands()-1);
4493     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4494     if (Mask.empty()) return false;
4495     break;
4496   case X86ISD::MOVDDUP:
4497   case X86ISD::MOVLHPD:
4498   case X86ISD::MOVLPD:
4499   case X86ISD::MOVLPS:
4500   case X86ISD::MOVSHDUP:
4501   case X86ISD::MOVSLDUP:
4502   case X86ISD::PALIGN:
4503     // Not yet implemented
4504     return false;
4505   default: llvm_unreachable("unknown target shuffle node");
4506   }
4507
4508   return true;
4509 }
4510
4511 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4512 /// element of the result of the vector shuffle.
4513 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4514                                    unsigned Depth) {
4515   if (Depth == 6)
4516     return SDValue();  // Limit search depth.
4517
4518   SDValue V = SDValue(N, 0);
4519   EVT VT = V.getValueType();
4520   unsigned Opcode = V.getOpcode();
4521
4522   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4523   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4524     int Elt = SV->getMaskElt(Index);
4525
4526     if (Elt < 0)
4527       return DAG.getUNDEF(VT.getVectorElementType());
4528
4529     unsigned NumElems = VT.getVectorNumElements();
4530     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4531                                          : SV->getOperand(1);
4532     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4533   }
4534
4535   // Recurse into target specific vector shuffles to find scalars.
4536   if (isTargetShuffle(Opcode)) {
4537     MVT ShufVT = V.getValueType().getSimpleVT();
4538     unsigned NumElems = ShufVT.getVectorNumElements();
4539     SmallVector<int, 16> ShuffleMask;
4540     SDValue ImmN;
4541     bool IsUnary;
4542
4543     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4544       return SDValue();
4545
4546     int Elt = ShuffleMask[Index];
4547     if (Elt < 0)
4548       return DAG.getUNDEF(ShufVT.getVectorElementType());
4549
4550     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4551                                          : N->getOperand(1);
4552     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4553                                Depth+1);
4554   }
4555
4556   // Actual nodes that may contain scalar elements
4557   if (Opcode == ISD::BITCAST) {
4558     V = V.getOperand(0);
4559     EVT SrcVT = V.getValueType();
4560     unsigned NumElems = VT.getVectorNumElements();
4561
4562     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4563       return SDValue();
4564   }
4565
4566   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4567     return (Index == 0) ? V.getOperand(0)
4568                         : DAG.getUNDEF(VT.getVectorElementType());
4569
4570   if (V.getOpcode() == ISD::BUILD_VECTOR)
4571     return V.getOperand(Index);
4572
4573   return SDValue();
4574 }
4575
4576 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4577 /// shuffle operation which come from a consecutively from a zero. The
4578 /// search can start in two different directions, from left or right.
4579 static
4580 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4581                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4582   unsigned i;
4583   for (i = 0; i != NumElems; ++i) {
4584     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4585     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4586     if (!(Elt.getNode() &&
4587          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4588       break;
4589   }
4590
4591   return i;
4592 }
4593
4594 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4595 /// correspond consecutively to elements from one of the vector operands,
4596 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4597 static
4598 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4599                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4600                               unsigned NumElems, unsigned &OpNum) {
4601   bool SeenV1 = false;
4602   bool SeenV2 = false;
4603
4604   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4605     int Idx = SVOp->getMaskElt(i);
4606     // Ignore undef indicies
4607     if (Idx < 0)
4608       continue;
4609
4610     if (Idx < (int)NumElems)
4611       SeenV1 = true;
4612     else
4613       SeenV2 = true;
4614
4615     // Only accept consecutive elements from the same vector
4616     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4617       return false;
4618   }
4619
4620   OpNum = SeenV1 ? 0 : 1;
4621   return true;
4622 }
4623
4624 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4625 /// logical left shift of a vector.
4626 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4627                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4628   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4629   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4630               false /* check zeros from right */, DAG);
4631   unsigned OpSrc;
4632
4633   if (!NumZeros)
4634     return false;
4635
4636   // Considering the elements in the mask that are not consecutive zeros,
4637   // check if they consecutively come from only one of the source vectors.
4638   //
4639   //               V1 = {X, A, B, C}     0
4640   //                         \  \  \    /
4641   //   vector_shuffle V1, V2 <1, 2, 3, X>
4642   //
4643   if (!isShuffleMaskConsecutive(SVOp,
4644             0,                   // Mask Start Index
4645             NumElems-NumZeros,   // Mask End Index(exclusive)
4646             NumZeros,            // Where to start looking in the src vector
4647             NumElems,            // Number of elements in vector
4648             OpSrc))              // Which source operand ?
4649     return false;
4650
4651   isLeft = false;
4652   ShAmt = NumZeros;
4653   ShVal = SVOp->getOperand(OpSrc);
4654   return true;
4655 }
4656
4657 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4658 /// logical left shift of a vector.
4659 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4660                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4661   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4662   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4663               true /* check zeros from left */, DAG);
4664   unsigned OpSrc;
4665
4666   if (!NumZeros)
4667     return false;
4668
4669   // Considering the elements in the mask that are not consecutive zeros,
4670   // check if they consecutively come from only one of the source vectors.
4671   //
4672   //                           0    { A, B, X, X } = V2
4673   //                          / \    /  /
4674   //   vector_shuffle V1, V2 <X, X, 4, 5>
4675   //
4676   if (!isShuffleMaskConsecutive(SVOp,
4677             NumZeros,     // Mask Start Index
4678             NumElems,     // Mask End Index(exclusive)
4679             0,            // Where to start looking in the src vector
4680             NumElems,     // Number of elements in vector
4681             OpSrc))       // Which source operand ?
4682     return false;
4683
4684   isLeft = true;
4685   ShAmt = NumZeros;
4686   ShVal = SVOp->getOperand(OpSrc);
4687   return true;
4688 }
4689
4690 /// isVectorShift - Returns true if the shuffle can be implemented as a
4691 /// logical left or right shift of a vector.
4692 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4693                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4694   // Although the logic below support any bitwidth size, there are no
4695   // shift instructions which handle more than 128-bit vectors.
4696   if (SVOp->getValueType(0).getSizeInBits() > 128)
4697     return false;
4698
4699   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4700       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4701     return true;
4702
4703   return false;
4704 }
4705
4706 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4707 ///
4708 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4709                                        unsigned NumNonZero, unsigned NumZero,
4710                                        SelectionDAG &DAG,
4711                                        const X86Subtarget* Subtarget,
4712                                        const TargetLowering &TLI) {
4713   if (NumNonZero > 8)
4714     return SDValue();
4715
4716   DebugLoc dl = Op.getDebugLoc();
4717   SDValue V(0, 0);
4718   bool First = true;
4719   for (unsigned i = 0; i < 16; ++i) {
4720     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4721     if (ThisIsNonZero && First) {
4722       if (NumZero)
4723         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4724       else
4725         V = DAG.getUNDEF(MVT::v8i16);
4726       First = false;
4727     }
4728
4729     if ((i & 1) != 0) {
4730       SDValue ThisElt(0, 0), LastElt(0, 0);
4731       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4732       if (LastIsNonZero) {
4733         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4734                               MVT::i16, Op.getOperand(i-1));
4735       }
4736       if (ThisIsNonZero) {
4737         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4738         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4739                               ThisElt, DAG.getConstant(8, MVT::i8));
4740         if (LastIsNonZero)
4741           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4742       } else
4743         ThisElt = LastElt;
4744
4745       if (ThisElt.getNode())
4746         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4747                         DAG.getIntPtrConstant(i/2));
4748     }
4749   }
4750
4751   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4752 }
4753
4754 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4755 ///
4756 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4757                                      unsigned NumNonZero, unsigned NumZero,
4758                                      SelectionDAG &DAG,
4759                                      const X86Subtarget* Subtarget,
4760                                      const TargetLowering &TLI) {
4761   if (NumNonZero > 4)
4762     return SDValue();
4763
4764   DebugLoc dl = Op.getDebugLoc();
4765   SDValue V(0, 0);
4766   bool First = true;
4767   for (unsigned i = 0; i < 8; ++i) {
4768     bool isNonZero = (NonZeros & (1 << i)) != 0;
4769     if (isNonZero) {
4770       if (First) {
4771         if (NumZero)
4772           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4773         else
4774           V = DAG.getUNDEF(MVT::v8i16);
4775         First = false;
4776       }
4777       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4778                       MVT::v8i16, V, Op.getOperand(i),
4779                       DAG.getIntPtrConstant(i));
4780     }
4781   }
4782
4783   return V;
4784 }
4785
4786 /// getVShift - Return a vector logical shift node.
4787 ///
4788 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4789                          unsigned NumBits, SelectionDAG &DAG,
4790                          const TargetLowering &TLI, DebugLoc dl) {
4791   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4792   EVT ShVT = MVT::v2i64;
4793   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4794   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4795   return DAG.getNode(ISD::BITCAST, dl, VT,
4796                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4797                              DAG.getConstant(NumBits,
4798                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4799 }
4800
4801 SDValue
4802 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4803                                           SelectionDAG &DAG) const {
4804
4805   // Check if the scalar load can be widened into a vector load. And if
4806   // the address is "base + cst" see if the cst can be "absorbed" into
4807   // the shuffle mask.
4808   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4809     SDValue Ptr = LD->getBasePtr();
4810     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4811       return SDValue();
4812     EVT PVT = LD->getValueType(0);
4813     if (PVT != MVT::i32 && PVT != MVT::f32)
4814       return SDValue();
4815
4816     int FI = -1;
4817     int64_t Offset = 0;
4818     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4819       FI = FINode->getIndex();
4820       Offset = 0;
4821     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4822                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4823       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4824       Offset = Ptr.getConstantOperandVal(1);
4825       Ptr = Ptr.getOperand(0);
4826     } else {
4827       return SDValue();
4828     }
4829
4830     // FIXME: 256-bit vector instructions don't require a strict alignment,
4831     // improve this code to support it better.
4832     unsigned RequiredAlign = VT.getSizeInBits()/8;
4833     SDValue Chain = LD->getChain();
4834     // Make sure the stack object alignment is at least 16 or 32.
4835     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4836     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4837       if (MFI->isFixedObjectIndex(FI)) {
4838         // Can't change the alignment. FIXME: It's possible to compute
4839         // the exact stack offset and reference FI + adjust offset instead.
4840         // If someone *really* cares about this. That's the way to implement it.
4841         return SDValue();
4842       } else {
4843         MFI->setObjectAlignment(FI, RequiredAlign);
4844       }
4845     }
4846
4847     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4848     // Ptr + (Offset & ~15).
4849     if (Offset < 0)
4850       return SDValue();
4851     if ((Offset % RequiredAlign) & 3)
4852       return SDValue();
4853     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4854     if (StartOffset)
4855       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4856                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4857
4858     int EltNo = (Offset - StartOffset) >> 2;
4859     unsigned NumElems = VT.getVectorNumElements();
4860
4861     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4862     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4863                              LD->getPointerInfo().getWithOffset(StartOffset),
4864                              false, false, false, 0);
4865
4866     SmallVector<int, 8> Mask;
4867     for (unsigned i = 0; i != NumElems; ++i)
4868       Mask.push_back(EltNo);
4869
4870     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4871   }
4872
4873   return SDValue();
4874 }
4875
4876 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4877 /// vector of type 'VT', see if the elements can be replaced by a single large
4878 /// load which has the same value as a build_vector whose operands are 'elts'.
4879 ///
4880 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4881 ///
4882 /// FIXME: we'd also like to handle the case where the last elements are zero
4883 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4884 /// There's even a handy isZeroNode for that purpose.
4885 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4886                                         DebugLoc &DL, SelectionDAG &DAG) {
4887   EVT EltVT = VT.getVectorElementType();
4888   unsigned NumElems = Elts.size();
4889
4890   LoadSDNode *LDBase = NULL;
4891   unsigned LastLoadedElt = -1U;
4892
4893   // For each element in the initializer, see if we've found a load or an undef.
4894   // If we don't find an initial load element, or later load elements are
4895   // non-consecutive, bail out.
4896   for (unsigned i = 0; i < NumElems; ++i) {
4897     SDValue Elt = Elts[i];
4898
4899     if (!Elt.getNode() ||
4900         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4901       return SDValue();
4902     if (!LDBase) {
4903       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4904         return SDValue();
4905       LDBase = cast<LoadSDNode>(Elt.getNode());
4906       LastLoadedElt = i;
4907       continue;
4908     }
4909     if (Elt.getOpcode() == ISD::UNDEF)
4910       continue;
4911
4912     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4913     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4914       return SDValue();
4915     LastLoadedElt = i;
4916   }
4917
4918   // If we have found an entire vector of loads and undefs, then return a large
4919   // load of the entire vector width starting at the base pointer.  If we found
4920   // consecutive loads for the low half, generate a vzext_load node.
4921   if (LastLoadedElt == NumElems - 1) {
4922     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4923       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4924                          LDBase->getPointerInfo(),
4925                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4926                          LDBase->isInvariant(), 0);
4927     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4928                        LDBase->getPointerInfo(),
4929                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4930                        LDBase->isInvariant(), LDBase->getAlignment());
4931   }
4932   if (NumElems == 4 && LastLoadedElt == 1 &&
4933       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4934     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4935     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4936     SDValue ResNode =
4937         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4938                                 LDBase->getPointerInfo(),
4939                                 LDBase->getAlignment(),
4940                                 false/*isVolatile*/, true/*ReadMem*/,
4941                                 false/*WriteMem*/);
4942     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4943   }
4944   return SDValue();
4945 }
4946
4947 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4948 /// to generate a splat value for the following cases:
4949 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4950 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4951 /// a scalar load, or a constant.
4952 /// The VBROADCAST node is returned when a pattern is found,
4953 /// or SDValue() otherwise.
4954 SDValue
4955 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
4956   if (!Subtarget->hasAVX())
4957     return SDValue();
4958
4959   EVT VT = Op.getValueType();
4960   DebugLoc dl = Op.getDebugLoc();
4961
4962   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4963          "Unsupported vector type for broadcast.");
4964
4965   SDValue Ld;
4966   bool ConstSplatVal;
4967
4968   switch (Op.getOpcode()) {
4969     default:
4970       // Unknown pattern found.
4971       return SDValue();
4972
4973     case ISD::BUILD_VECTOR: {
4974       // The BUILD_VECTOR node must be a splat.
4975       if (!isSplatVector(Op.getNode()))
4976         return SDValue();
4977
4978       Ld = Op.getOperand(0);
4979       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4980                      Ld.getOpcode() == ISD::ConstantFP);
4981
4982       // The suspected load node has several users. Make sure that all
4983       // of its users are from the BUILD_VECTOR node.
4984       // Constants may have multiple users.
4985       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
4986         return SDValue();
4987       break;
4988     }
4989
4990     case ISD::VECTOR_SHUFFLE: {
4991       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4992
4993       // Shuffles must have a splat mask where the first element is
4994       // broadcasted.
4995       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4996         return SDValue();
4997
4998       SDValue Sc = Op.getOperand(0);
4999       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5000           Sc.getOpcode() != ISD::BUILD_VECTOR)
5001         return SDValue();
5002
5003       Ld = Sc.getOperand(0);
5004       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5005                        Ld.getOpcode() == ISD::ConstantFP);
5006
5007       // The scalar_to_vector node and the suspected
5008       // load node must have exactly one user.
5009       // Constants may have multiple users.
5010       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5011         return SDValue();
5012       break;
5013     }
5014   }
5015
5016   bool Is256 = VT.getSizeInBits() == 256;
5017
5018   // Handle the broadcasting a single constant scalar from the constant pool
5019   // into a vector. On Sandybridge it is still better to load a constant vector
5020   // from the constant pool and not to broadcast it from a scalar.
5021   if (ConstSplatVal && Subtarget->hasAVX2()) {
5022     EVT CVT = Ld.getValueType();
5023     assert(!CVT.isVector() && "Must not broadcast a vector type");
5024     unsigned ScalarSize = CVT.getSizeInBits();
5025
5026     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5027       const Constant *C = 0;
5028       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5029         C = CI->getConstantIntValue();
5030       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5031         C = CF->getConstantFPValue();
5032
5033       assert(C && "Invalid constant type");
5034
5035       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5036       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5037       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5038                        MachinePointerInfo::getConstantPool(),
5039                        false, false, false, Alignment);
5040
5041       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5042     }
5043   }
5044
5045   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5046   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5047
5048   // Handle AVX2 in-register broadcasts.
5049   if (!IsLoad && Subtarget->hasAVX2() &&
5050       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5051     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5052
5053   // The scalar source must be a normal load.
5054   if (!IsLoad)
5055     return SDValue();
5056
5057   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5058     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5059
5060   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5061   // double since there is no vbroadcastsd xmm
5062   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5063     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5064       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5065   }
5066
5067   // Unsupported broadcast.
5068   return SDValue();
5069 }
5070
5071 SDValue
5072 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5073   DebugLoc dl = Op.getDebugLoc();
5074
5075   EVT VT = Op.getValueType();
5076   EVT ExtVT = VT.getVectorElementType();
5077   unsigned NumElems = Op.getNumOperands();
5078
5079   // Vectors containing all zeros can be matched by pxor and xorps later
5080   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5081     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5082     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5083     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5084       return Op;
5085
5086     return getZeroVector(VT, Subtarget, DAG, dl);
5087   }
5088
5089   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5090   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5091   // vpcmpeqd on 256-bit vectors.
5092   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5093     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5094       return Op;
5095
5096     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5097   }
5098
5099   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5100   if (Broadcast.getNode())
5101     return Broadcast;
5102
5103   unsigned EVTBits = ExtVT.getSizeInBits();
5104
5105   unsigned NumZero  = 0;
5106   unsigned NumNonZero = 0;
5107   unsigned NonZeros = 0;
5108   bool IsAllConstants = true;
5109   SmallSet<SDValue, 8> Values;
5110   for (unsigned i = 0; i < NumElems; ++i) {
5111     SDValue Elt = Op.getOperand(i);
5112     if (Elt.getOpcode() == ISD::UNDEF)
5113       continue;
5114     Values.insert(Elt);
5115     if (Elt.getOpcode() != ISD::Constant &&
5116         Elt.getOpcode() != ISD::ConstantFP)
5117       IsAllConstants = false;
5118     if (X86::isZeroNode(Elt))
5119       NumZero++;
5120     else {
5121       NonZeros |= (1 << i);
5122       NumNonZero++;
5123     }
5124   }
5125
5126   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5127   if (NumNonZero == 0)
5128     return DAG.getUNDEF(VT);
5129
5130   // Special case for single non-zero, non-undef, element.
5131   if (NumNonZero == 1) {
5132     unsigned Idx = CountTrailingZeros_32(NonZeros);
5133     SDValue Item = Op.getOperand(Idx);
5134
5135     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5136     // the value are obviously zero, truncate the value to i32 and do the
5137     // insertion that way.  Only do this if the value is non-constant or if the
5138     // value is a constant being inserted into element 0.  It is cheaper to do
5139     // a constant pool load than it is to do a movd + shuffle.
5140     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5141         (!IsAllConstants || Idx == 0)) {
5142       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5143         // Handle SSE only.
5144         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5145         EVT VecVT = MVT::v4i32;
5146         unsigned VecElts = 4;
5147
5148         // Truncate the value (which may itself be a constant) to i32, and
5149         // convert it to a vector with movd (S2V+shuffle to zero extend).
5150         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5151         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5152         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5153
5154         // Now we have our 32-bit value zero extended in the low element of
5155         // a vector.  If Idx != 0, swizzle it into place.
5156         if (Idx != 0) {
5157           SmallVector<int, 4> Mask;
5158           Mask.push_back(Idx);
5159           for (unsigned i = 1; i != VecElts; ++i)
5160             Mask.push_back(i);
5161           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5162                                       &Mask[0]);
5163         }
5164         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5165       }
5166     }
5167
5168     // If we have a constant or non-constant insertion into the low element of
5169     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5170     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5171     // depending on what the source datatype is.
5172     if (Idx == 0) {
5173       if (NumZero == 0)
5174         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5175
5176       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5177           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5178         if (VT.getSizeInBits() == 256) {
5179           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5180           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5181                              Item, DAG.getIntPtrConstant(0));
5182         }
5183         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5184         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5185         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5186         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5187       }
5188
5189       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5190         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5191         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5192         if (VT.getSizeInBits() == 256) {
5193           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5194           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5195         } else {
5196           assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5197           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5198         }
5199         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5200       }
5201     }
5202
5203     // Is it a vector logical left shift?
5204     if (NumElems == 2 && Idx == 1 &&
5205         X86::isZeroNode(Op.getOperand(0)) &&
5206         !X86::isZeroNode(Op.getOperand(1))) {
5207       unsigned NumBits = VT.getSizeInBits();
5208       return getVShift(true, VT,
5209                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5210                                    VT, Op.getOperand(1)),
5211                        NumBits/2, DAG, *this, dl);
5212     }
5213
5214     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5215       return SDValue();
5216
5217     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5218     // is a non-constant being inserted into an element other than the low one,
5219     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5220     // movd/movss) to move this into the low element, then shuffle it into
5221     // place.
5222     if (EVTBits == 32) {
5223       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5224
5225       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5226       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5227       SmallVector<int, 8> MaskVec;
5228       for (unsigned i = 0; i != NumElems; ++i)
5229         MaskVec.push_back(i == Idx ? 0 : 1);
5230       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5231     }
5232   }
5233
5234   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5235   if (Values.size() == 1) {
5236     if (EVTBits == 32) {
5237       // Instead of a shuffle like this:
5238       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5239       // Check if it's possible to issue this instead.
5240       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5241       unsigned Idx = CountTrailingZeros_32(NonZeros);
5242       SDValue Item = Op.getOperand(Idx);
5243       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5244         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5245     }
5246     return SDValue();
5247   }
5248
5249   // A vector full of immediates; various special cases are already
5250   // handled, so this is best done with a single constant-pool load.
5251   if (IsAllConstants)
5252     return SDValue();
5253
5254   // For AVX-length vectors, build the individual 128-bit pieces and use
5255   // shuffles to put them in place.
5256   if (VT.getSizeInBits() == 256) {
5257     SmallVector<SDValue, 32> V;
5258     for (unsigned i = 0; i != NumElems; ++i)
5259       V.push_back(Op.getOperand(i));
5260
5261     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5262
5263     // Build both the lower and upper subvector.
5264     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5265     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5266                                 NumElems/2);
5267
5268     // Recreate the wider vector with the lower and upper part.
5269     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5270   }
5271
5272   // Let legalizer expand 2-wide build_vectors.
5273   if (EVTBits == 64) {
5274     if (NumNonZero == 1) {
5275       // One half is zero or undef.
5276       unsigned Idx = CountTrailingZeros_32(NonZeros);
5277       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5278                                  Op.getOperand(Idx));
5279       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5280     }
5281     return SDValue();
5282   }
5283
5284   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5285   if (EVTBits == 8 && NumElems == 16) {
5286     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5287                                         Subtarget, *this);
5288     if (V.getNode()) return V;
5289   }
5290
5291   if (EVTBits == 16 && NumElems == 8) {
5292     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5293                                       Subtarget, *this);
5294     if (V.getNode()) return V;
5295   }
5296
5297   // If element VT is == 32 bits, turn it into a number of shuffles.
5298   SmallVector<SDValue, 8> V(NumElems);
5299   if (NumElems == 4 && NumZero > 0) {
5300     for (unsigned i = 0; i < 4; ++i) {
5301       bool isZero = !(NonZeros & (1 << i));
5302       if (isZero)
5303         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5304       else
5305         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5306     }
5307
5308     for (unsigned i = 0; i < 2; ++i) {
5309       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5310         default: break;
5311         case 0:
5312           V[i] = V[i*2];  // Must be a zero vector.
5313           break;
5314         case 1:
5315           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5316           break;
5317         case 2:
5318           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5319           break;
5320         case 3:
5321           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5322           break;
5323       }
5324     }
5325
5326     bool Reverse1 = (NonZeros & 0x3) == 2;
5327     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5328     int MaskVec[] = {
5329       Reverse1 ? 1 : 0,
5330       Reverse1 ? 0 : 1,
5331       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5332       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5333     };
5334     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5335   }
5336
5337   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5338     // Check for a build vector of consecutive loads.
5339     for (unsigned i = 0; i < NumElems; ++i)
5340       V[i] = Op.getOperand(i);
5341
5342     // Check for elements which are consecutive loads.
5343     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5344     if (LD.getNode())
5345       return LD;
5346
5347     // For SSE 4.1, use insertps to put the high elements into the low element.
5348     if (getSubtarget()->hasSSE41()) {
5349       SDValue Result;
5350       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5351         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5352       else
5353         Result = DAG.getUNDEF(VT);
5354
5355       for (unsigned i = 1; i < NumElems; ++i) {
5356         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5357         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5358                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5359       }
5360       return Result;
5361     }
5362
5363     // Otherwise, expand into a number of unpckl*, start by extending each of
5364     // our (non-undef) elements to the full vector width with the element in the
5365     // bottom slot of the vector (which generates no code for SSE).
5366     for (unsigned i = 0; i < NumElems; ++i) {
5367       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5368         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5369       else
5370         V[i] = DAG.getUNDEF(VT);
5371     }
5372
5373     // Next, we iteratively mix elements, e.g. for v4f32:
5374     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5375     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5376     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5377     unsigned EltStride = NumElems >> 1;
5378     while (EltStride != 0) {
5379       for (unsigned i = 0; i < EltStride; ++i) {
5380         // If V[i+EltStride] is undef and this is the first round of mixing,
5381         // then it is safe to just drop this shuffle: V[i] is already in the
5382         // right place, the one element (since it's the first round) being
5383         // inserted as undef can be dropped.  This isn't safe for successive
5384         // rounds because they will permute elements within both vectors.
5385         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5386             EltStride == NumElems/2)
5387           continue;
5388
5389         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5390       }
5391       EltStride >>= 1;
5392     }
5393     return V[0];
5394   }
5395   return SDValue();
5396 }
5397
5398 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5399 // them in a MMX register.  This is better than doing a stack convert.
5400 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5401   DebugLoc dl = Op.getDebugLoc();
5402   EVT ResVT = Op.getValueType();
5403
5404   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5405          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5406   int Mask[2];
5407   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5408   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5409   InVec = Op.getOperand(1);
5410   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5411     unsigned NumElts = ResVT.getVectorNumElements();
5412     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5413     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5414                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5415   } else {
5416     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5417     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5418     Mask[0] = 0; Mask[1] = 2;
5419     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5420   }
5421   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5422 }
5423
5424 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5425 // to create 256-bit vectors from two other 128-bit ones.
5426 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5427   DebugLoc dl = Op.getDebugLoc();
5428   EVT ResVT = Op.getValueType();
5429
5430   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5431
5432   SDValue V1 = Op.getOperand(0);
5433   SDValue V2 = Op.getOperand(1);
5434   unsigned NumElems = ResVT.getVectorNumElements();
5435
5436   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5437 }
5438
5439 SDValue
5440 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5441   EVT ResVT = Op.getValueType();
5442
5443   assert(Op.getNumOperands() == 2);
5444   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5445          "Unsupported CONCAT_VECTORS for value type");
5446
5447   // We support concatenate two MMX registers and place them in a MMX register.
5448   // This is better than doing a stack convert.
5449   if (ResVT.is128BitVector())
5450     return LowerMMXCONCAT_VECTORS(Op, DAG);
5451
5452   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5453   // from two other 128-bit ones.
5454   return LowerAVXCONCAT_VECTORS(Op, DAG);
5455 }
5456
5457 // Try to lower a shuffle node into a simple blend instruction.
5458 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5459                                           const X86Subtarget *Subtarget,
5460                                           SelectionDAG &DAG) {
5461   SDValue V1 = SVOp->getOperand(0);
5462   SDValue V2 = SVOp->getOperand(1);
5463   DebugLoc dl = SVOp->getDebugLoc();
5464   MVT VT = SVOp->getValueType(0).getSimpleVT();
5465   unsigned NumElems = VT.getVectorNumElements();
5466
5467   if (!Subtarget->hasSSE41())
5468     return SDValue();
5469
5470   unsigned ISDNo = 0;
5471   MVT OpTy;
5472
5473   switch (VT.SimpleTy) {
5474   default: return SDValue();
5475   case MVT::v8i16:
5476     ISDNo = X86ISD::BLENDPW;
5477     OpTy = MVT::v8i16;
5478     break;
5479   case MVT::v4i32:
5480   case MVT::v4f32:
5481     ISDNo = X86ISD::BLENDPS;
5482     OpTy = MVT::v4f32;
5483     break;
5484   case MVT::v2i64:
5485   case MVT::v2f64:
5486     ISDNo = X86ISD::BLENDPD;
5487     OpTy = MVT::v2f64;
5488     break;
5489   case MVT::v8i32:
5490   case MVT::v8f32:
5491     if (!Subtarget->hasAVX())
5492       return SDValue();
5493     ISDNo = X86ISD::BLENDPS;
5494     OpTy = MVT::v8f32;
5495     break;
5496   case MVT::v4i64:
5497   case MVT::v4f64:
5498     if (!Subtarget->hasAVX())
5499       return SDValue();
5500     ISDNo = X86ISD::BLENDPD;
5501     OpTy = MVT::v4f64;
5502     break;
5503   }
5504   assert(ISDNo && "Invalid Op Number");
5505
5506   unsigned MaskVals = 0;
5507
5508   for (unsigned i = 0; i != NumElems; ++i) {
5509     int EltIdx = SVOp->getMaskElt(i);
5510     if (EltIdx == (int)i || EltIdx < 0)
5511       MaskVals |= (1<<i);
5512     else if (EltIdx == (int)(i + NumElems))
5513       continue; // Bit is set to zero;
5514     else
5515       return SDValue();
5516   }
5517
5518   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5519   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5520   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5521                              DAG.getConstant(MaskVals, MVT::i32));
5522   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5523 }
5524
5525 // v8i16 shuffles - Prefer shuffles in the following order:
5526 // 1. [all]   pshuflw, pshufhw, optional move
5527 // 2. [ssse3] 1 x pshufb
5528 // 3. [ssse3] 2 x pshufb + 1 x por
5529 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5530 SDValue
5531 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5532                                             SelectionDAG &DAG) const {
5533   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5534   SDValue V1 = SVOp->getOperand(0);
5535   SDValue V2 = SVOp->getOperand(1);
5536   DebugLoc dl = SVOp->getDebugLoc();
5537   SmallVector<int, 8> MaskVals;
5538
5539   // Determine if more than 1 of the words in each of the low and high quadwords
5540   // of the result come from the same quadword of one of the two inputs.  Undef
5541   // mask values count as coming from any quadword, for better codegen.
5542   unsigned LoQuad[] = { 0, 0, 0, 0 };
5543   unsigned HiQuad[] = { 0, 0, 0, 0 };
5544   std::bitset<4> InputQuads;
5545   for (unsigned i = 0; i < 8; ++i) {
5546     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5547     int EltIdx = SVOp->getMaskElt(i);
5548     MaskVals.push_back(EltIdx);
5549     if (EltIdx < 0) {
5550       ++Quad[0];
5551       ++Quad[1];
5552       ++Quad[2];
5553       ++Quad[3];
5554       continue;
5555     }
5556     ++Quad[EltIdx / 4];
5557     InputQuads.set(EltIdx / 4);
5558   }
5559
5560   int BestLoQuad = -1;
5561   unsigned MaxQuad = 1;
5562   for (unsigned i = 0; i < 4; ++i) {
5563     if (LoQuad[i] > MaxQuad) {
5564       BestLoQuad = i;
5565       MaxQuad = LoQuad[i];
5566     }
5567   }
5568
5569   int BestHiQuad = -1;
5570   MaxQuad = 1;
5571   for (unsigned i = 0; i < 4; ++i) {
5572     if (HiQuad[i] > MaxQuad) {
5573       BestHiQuad = i;
5574       MaxQuad = HiQuad[i];
5575     }
5576   }
5577
5578   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5579   // of the two input vectors, shuffle them into one input vector so only a
5580   // single pshufb instruction is necessary. If There are more than 2 input
5581   // quads, disable the next transformation since it does not help SSSE3.
5582   bool V1Used = InputQuads[0] || InputQuads[1];
5583   bool V2Used = InputQuads[2] || InputQuads[3];
5584   if (Subtarget->hasSSSE3()) {
5585     if (InputQuads.count() == 2 && V1Used && V2Used) {
5586       BestLoQuad = InputQuads[0] ? 0 : 1;
5587       BestHiQuad = InputQuads[2] ? 2 : 3;
5588     }
5589     if (InputQuads.count() > 2) {
5590       BestLoQuad = -1;
5591       BestHiQuad = -1;
5592     }
5593   }
5594
5595   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5596   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5597   // words from all 4 input quadwords.
5598   SDValue NewV;
5599   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5600     int MaskV[] = {
5601       BestLoQuad < 0 ? 0 : BestLoQuad,
5602       BestHiQuad < 0 ? 1 : BestHiQuad
5603     };
5604     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5605                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5606                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5607     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5608
5609     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5610     // source words for the shuffle, to aid later transformations.
5611     bool AllWordsInNewV = true;
5612     bool InOrder[2] = { true, true };
5613     for (unsigned i = 0; i != 8; ++i) {
5614       int idx = MaskVals[i];
5615       if (idx != (int)i)
5616         InOrder[i/4] = false;
5617       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5618         continue;
5619       AllWordsInNewV = false;
5620       break;
5621     }
5622
5623     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5624     if (AllWordsInNewV) {
5625       for (int i = 0; i != 8; ++i) {
5626         int idx = MaskVals[i];
5627         if (idx < 0)
5628           continue;
5629         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5630         if ((idx != i) && idx < 4)
5631           pshufhw = false;
5632         if ((idx != i) && idx > 3)
5633           pshuflw = false;
5634       }
5635       V1 = NewV;
5636       V2Used = false;
5637       BestLoQuad = 0;
5638       BestHiQuad = 1;
5639     }
5640
5641     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5642     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5643     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5644       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5645       unsigned TargetMask = 0;
5646       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5647                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5648       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5649       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5650                              getShufflePSHUFLWImmediate(SVOp);
5651       V1 = NewV.getOperand(0);
5652       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5653     }
5654   }
5655
5656   // If we have SSSE3, and all words of the result are from 1 input vector,
5657   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5658   // is present, fall back to case 4.
5659   if (Subtarget->hasSSSE3()) {
5660     SmallVector<SDValue,16> pshufbMask;
5661
5662     // If we have elements from both input vectors, set the high bit of the
5663     // shuffle mask element to zero out elements that come from V2 in the V1
5664     // mask, and elements that come from V1 in the V2 mask, so that the two
5665     // results can be OR'd together.
5666     bool TwoInputs = V1Used && V2Used;
5667     for (unsigned i = 0; i != 8; ++i) {
5668       int EltIdx = MaskVals[i] * 2;
5669       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5670       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5671       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5672       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5673     }
5674     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5675     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5676                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5677                                  MVT::v16i8, &pshufbMask[0], 16));
5678     if (!TwoInputs)
5679       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5680
5681     // Calculate the shuffle mask for the second input, shuffle it, and
5682     // OR it with the first shuffled input.
5683     pshufbMask.clear();
5684     for (unsigned i = 0; i != 8; ++i) {
5685       int EltIdx = MaskVals[i] * 2;
5686       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5687       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5688       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5689       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5690     }
5691     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5692     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5693                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5694                                  MVT::v16i8, &pshufbMask[0], 16));
5695     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5696     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5697   }
5698
5699   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5700   // and update MaskVals with new element order.
5701   std::bitset<8> InOrder;
5702   if (BestLoQuad >= 0) {
5703     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5704     for (int i = 0; i != 4; ++i) {
5705       int idx = MaskVals[i];
5706       if (idx < 0) {
5707         InOrder.set(i);
5708       } else if ((idx / 4) == BestLoQuad) {
5709         MaskV[i] = idx & 3;
5710         InOrder.set(i);
5711       }
5712     }
5713     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5714                                 &MaskV[0]);
5715
5716     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5717       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5718       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5719                                   NewV.getOperand(0),
5720                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5721     }
5722   }
5723
5724   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5725   // and update MaskVals with the new element order.
5726   if (BestHiQuad >= 0) {
5727     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5728     for (unsigned i = 4; i != 8; ++i) {
5729       int idx = MaskVals[i];
5730       if (idx < 0) {
5731         InOrder.set(i);
5732       } else if ((idx / 4) == BestHiQuad) {
5733         MaskV[i] = (idx & 3) + 4;
5734         InOrder.set(i);
5735       }
5736     }
5737     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5738                                 &MaskV[0]);
5739
5740     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5741       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5742       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5743                                   NewV.getOperand(0),
5744                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5745     }
5746   }
5747
5748   // In case BestHi & BestLo were both -1, which means each quadword has a word
5749   // from each of the four input quadwords, calculate the InOrder bitvector now
5750   // before falling through to the insert/extract cleanup.
5751   if (BestLoQuad == -1 && BestHiQuad == -1) {
5752     NewV = V1;
5753     for (int i = 0; i != 8; ++i)
5754       if (MaskVals[i] < 0 || MaskVals[i] == i)
5755         InOrder.set(i);
5756   }
5757
5758   // The other elements are put in the right place using pextrw and pinsrw.
5759   for (unsigned i = 0; i != 8; ++i) {
5760     if (InOrder[i])
5761       continue;
5762     int EltIdx = MaskVals[i];
5763     if (EltIdx < 0)
5764       continue;
5765     SDValue ExtOp = (EltIdx < 8) ?
5766       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5767                   DAG.getIntPtrConstant(EltIdx)) :
5768       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5769                   DAG.getIntPtrConstant(EltIdx - 8));
5770     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5771                        DAG.getIntPtrConstant(i));
5772   }
5773   return NewV;
5774 }
5775
5776 // v16i8 shuffles - Prefer shuffles in the following order:
5777 // 1. [ssse3] 1 x pshufb
5778 // 2. [ssse3] 2 x pshufb + 1 x por
5779 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5780 static
5781 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5782                                  SelectionDAG &DAG,
5783                                  const X86TargetLowering &TLI) {
5784   SDValue V1 = SVOp->getOperand(0);
5785   SDValue V2 = SVOp->getOperand(1);
5786   DebugLoc dl = SVOp->getDebugLoc();
5787   ArrayRef<int> MaskVals = SVOp->getMask();
5788
5789   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5790
5791   // If we have SSSE3, case 1 is generated when all result bytes come from
5792   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5793   // present, fall back to case 3.
5794
5795   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5796   if (TLI.getSubtarget()->hasSSSE3()) {
5797     SmallVector<SDValue,16> pshufbMask;
5798
5799     // If all result elements are from one input vector, then only translate
5800     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5801     //
5802     // Otherwise, we have elements from both input vectors, and must zero out
5803     // elements that come from V2 in the first mask, and V1 in the second mask
5804     // so that we can OR them together.
5805     for (unsigned i = 0; i != 16; ++i) {
5806       int EltIdx = MaskVals[i];
5807       if (EltIdx < 0 || EltIdx >= 16)
5808         EltIdx = 0x80;
5809       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5810     }
5811     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5812                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5813                                  MVT::v16i8, &pshufbMask[0], 16));
5814     if (V2IsUndef)
5815       return V1;
5816
5817     // Calculate the shuffle mask for the second input, shuffle it, and
5818     // OR it with the first shuffled input.
5819     pshufbMask.clear();
5820     for (unsigned i = 0; i != 16; ++i) {
5821       int EltIdx = MaskVals[i];
5822       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5823       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5824     }
5825     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5826                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5827                                  MVT::v16i8, &pshufbMask[0], 16));
5828     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5829   }
5830
5831   // No SSSE3 - Calculate in place words and then fix all out of place words
5832   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5833   // the 16 different words that comprise the two doublequadword input vectors.
5834   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5835   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5836   SDValue NewV = V1;
5837   for (int i = 0; i != 8; ++i) {
5838     int Elt0 = MaskVals[i*2];
5839     int Elt1 = MaskVals[i*2+1];
5840
5841     // This word of the result is all undef, skip it.
5842     if (Elt0 < 0 && Elt1 < 0)
5843       continue;
5844
5845     // This word of the result is already in the correct place, skip it.
5846     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5847       continue;
5848
5849     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5850     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5851     SDValue InsElt;
5852
5853     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5854     // using a single extract together, load it and store it.
5855     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5856       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5857                            DAG.getIntPtrConstant(Elt1 / 2));
5858       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5859                         DAG.getIntPtrConstant(i));
5860       continue;
5861     }
5862
5863     // If Elt1 is defined, extract it from the appropriate source.  If the
5864     // source byte is not also odd, shift the extracted word left 8 bits
5865     // otherwise clear the bottom 8 bits if we need to do an or.
5866     if (Elt1 >= 0) {
5867       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5868                            DAG.getIntPtrConstant(Elt1 / 2));
5869       if ((Elt1 & 1) == 0)
5870         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5871                              DAG.getConstant(8,
5872                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5873       else if (Elt0 >= 0)
5874         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5875                              DAG.getConstant(0xFF00, MVT::i16));
5876     }
5877     // If Elt0 is defined, extract it from the appropriate source.  If the
5878     // source byte is not also even, shift the extracted word right 8 bits. If
5879     // Elt1 was also defined, OR the extracted values together before
5880     // inserting them in the result.
5881     if (Elt0 >= 0) {
5882       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5883                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5884       if ((Elt0 & 1) != 0)
5885         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5886                               DAG.getConstant(8,
5887                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5888       else if (Elt1 >= 0)
5889         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5890                              DAG.getConstant(0x00FF, MVT::i16));
5891       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5892                          : InsElt0;
5893     }
5894     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5895                        DAG.getIntPtrConstant(i));
5896   }
5897   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5898 }
5899
5900 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5901 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5902 /// done when every pair / quad of shuffle mask elements point to elements in
5903 /// the right sequence. e.g.
5904 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5905 static
5906 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5907                                  SelectionDAG &DAG, DebugLoc dl) {
5908   MVT VT = SVOp->getValueType(0).getSimpleVT();
5909   unsigned NumElems = VT.getVectorNumElements();
5910   MVT NewVT;
5911   unsigned Scale;
5912   switch (VT.SimpleTy) {
5913   default: llvm_unreachable("Unexpected!");
5914   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
5915   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
5916   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
5917   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
5918   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
5919   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
5920   }
5921
5922   SmallVector<int, 8> MaskVec;
5923   for (unsigned i = 0; i != NumElems; i += Scale) {
5924     int StartIdx = -1;
5925     for (unsigned j = 0; j != Scale; ++j) {
5926       int EltIdx = SVOp->getMaskElt(i+j);
5927       if (EltIdx < 0)
5928         continue;
5929       if (StartIdx < 0)
5930         StartIdx = (EltIdx / Scale);
5931       if (EltIdx != (int)(StartIdx*Scale + j))
5932         return SDValue();
5933     }
5934     MaskVec.push_back(StartIdx);
5935   }
5936
5937   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
5938   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
5939   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5940 }
5941
5942 /// getVZextMovL - Return a zero-extending vector move low node.
5943 ///
5944 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5945                             SDValue SrcOp, SelectionDAG &DAG,
5946                             const X86Subtarget *Subtarget, DebugLoc dl) {
5947   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5948     LoadSDNode *LD = NULL;
5949     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5950       LD = dyn_cast<LoadSDNode>(SrcOp);
5951     if (!LD) {
5952       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5953       // instead.
5954       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5955       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5956           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5957           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5958           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5959         // PR2108
5960         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5961         return DAG.getNode(ISD::BITCAST, dl, VT,
5962                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5963                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5964                                                    OpVT,
5965                                                    SrcOp.getOperand(0)
5966                                                           .getOperand(0))));
5967       }
5968     }
5969   }
5970
5971   return DAG.getNode(ISD::BITCAST, dl, VT,
5972                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5973                                  DAG.getNode(ISD::BITCAST, dl,
5974                                              OpVT, SrcOp)));
5975 }
5976
5977 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5978 /// which could not be matched by any known target speficic shuffle
5979 static SDValue
5980 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5981   EVT VT = SVOp->getValueType(0);
5982
5983   unsigned NumElems = VT.getVectorNumElements();
5984   unsigned NumLaneElems = NumElems / 2;
5985
5986   DebugLoc dl = SVOp->getDebugLoc();
5987   MVT EltVT = VT.getVectorElementType().getSimpleVT();
5988   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
5989   SDValue Output[2];
5990
5991   SmallVector<int, 16> Mask;
5992   for (unsigned l = 0; l < 2; ++l) {
5993     // Build a shuffle mask for the output, discovering on the fly which
5994     // input vectors to use as shuffle operands (recorded in InputUsed).
5995     // If building a suitable shuffle vector proves too hard, then bail
5996     // out with UseBuildVector set.
5997     bool UseBuildVector = false;
5998     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
5999     unsigned LaneStart = l * NumLaneElems;
6000     for (unsigned i = 0; i != NumLaneElems; ++i) {
6001       // The mask element.  This indexes into the input.
6002       int Idx = SVOp->getMaskElt(i+LaneStart);
6003       if (Idx < 0) {
6004         // the mask element does not index into any input vector.
6005         Mask.push_back(-1);
6006         continue;
6007       }
6008
6009       // The input vector this mask element indexes into.
6010       int Input = Idx / NumLaneElems;
6011
6012       // Turn the index into an offset from the start of the input vector.
6013       Idx -= Input * NumLaneElems;
6014
6015       // Find or create a shuffle vector operand to hold this input.
6016       unsigned OpNo;
6017       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6018         if (InputUsed[OpNo] == Input)
6019           // This input vector is already an operand.
6020           break;
6021         if (InputUsed[OpNo] < 0) {
6022           // Create a new operand for this input vector.
6023           InputUsed[OpNo] = Input;
6024           break;
6025         }
6026       }
6027
6028       if (OpNo >= array_lengthof(InputUsed)) {
6029         // More than two input vectors used!  Give up on trying to create a
6030         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6031         UseBuildVector = true;
6032         break;
6033       }
6034
6035       // Add the mask index for the new shuffle vector.
6036       Mask.push_back(Idx + OpNo * NumLaneElems);
6037     }
6038
6039     if (UseBuildVector) {
6040       SmallVector<SDValue, 16> SVOps;
6041       for (unsigned i = 0; i != NumLaneElems; ++i) {
6042         // The mask element.  This indexes into the input.
6043         int Idx = SVOp->getMaskElt(i+LaneStart);
6044         if (Idx < 0) {
6045           SVOps.push_back(DAG.getUNDEF(EltVT));
6046           continue;
6047         }
6048
6049         // The input vector this mask element indexes into.
6050         int Input = Idx / NumElems;
6051
6052         // Turn the index into an offset from the start of the input vector.
6053         Idx -= Input * NumElems;
6054
6055         // Extract the vector element by hand.
6056         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6057                                     SVOp->getOperand(Input),
6058                                     DAG.getIntPtrConstant(Idx)));
6059       }
6060
6061       // Construct the output using a BUILD_VECTOR.
6062       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6063                               SVOps.size());
6064     } else if (InputUsed[0] < 0) {
6065       // No input vectors were used! The result is undefined.
6066       Output[l] = DAG.getUNDEF(NVT);
6067     } else {
6068       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6069                                         (InputUsed[0] % 2) * NumLaneElems,
6070                                         DAG, dl);
6071       // If only one input was used, use an undefined vector for the other.
6072       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6073         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6074                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6075       // At least one input vector was used. Create a new shuffle vector.
6076       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6077     }
6078
6079     Mask.clear();
6080   }
6081
6082   // Concatenate the result back
6083   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6084 }
6085
6086 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6087 /// 4 elements, and match them with several different shuffle types.
6088 static SDValue
6089 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6090   SDValue V1 = SVOp->getOperand(0);
6091   SDValue V2 = SVOp->getOperand(1);
6092   DebugLoc dl = SVOp->getDebugLoc();
6093   EVT VT = SVOp->getValueType(0);
6094
6095   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6096
6097   std::pair<int, int> Locs[4];
6098   int Mask1[] = { -1, -1, -1, -1 };
6099   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6100
6101   unsigned NumHi = 0;
6102   unsigned NumLo = 0;
6103   for (unsigned i = 0; i != 4; ++i) {
6104     int Idx = PermMask[i];
6105     if (Idx < 0) {
6106       Locs[i] = std::make_pair(-1, -1);
6107     } else {
6108       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6109       if (Idx < 4) {
6110         Locs[i] = std::make_pair(0, NumLo);
6111         Mask1[NumLo] = Idx;
6112         NumLo++;
6113       } else {
6114         Locs[i] = std::make_pair(1, NumHi);
6115         if (2+NumHi < 4)
6116           Mask1[2+NumHi] = Idx;
6117         NumHi++;
6118       }
6119     }
6120   }
6121
6122   if (NumLo <= 2 && NumHi <= 2) {
6123     // If no more than two elements come from either vector. This can be
6124     // implemented with two shuffles. First shuffle gather the elements.
6125     // The second shuffle, which takes the first shuffle as both of its
6126     // vector operands, put the elements into the right order.
6127     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6128
6129     int Mask2[] = { -1, -1, -1, -1 };
6130
6131     for (unsigned i = 0; i != 4; ++i)
6132       if (Locs[i].first != -1) {
6133         unsigned Idx = (i < 2) ? 0 : 4;
6134         Idx += Locs[i].first * 2 + Locs[i].second;
6135         Mask2[i] = Idx;
6136       }
6137
6138     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6139   }
6140
6141   if (NumLo == 3 || NumHi == 3) {
6142     // Otherwise, we must have three elements from one vector, call it X, and
6143     // one element from the other, call it Y.  First, use a shufps to build an
6144     // intermediate vector with the one element from Y and the element from X
6145     // that will be in the same half in the final destination (the indexes don't
6146     // matter). Then, use a shufps to build the final vector, taking the half
6147     // containing the element from Y from the intermediate, and the other half
6148     // from X.
6149     if (NumHi == 3) {
6150       // Normalize it so the 3 elements come from V1.
6151       CommuteVectorShuffleMask(PermMask, 4);
6152       std::swap(V1, V2);
6153     }
6154
6155     // Find the element from V2.
6156     unsigned HiIndex;
6157     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6158       int Val = PermMask[HiIndex];
6159       if (Val < 0)
6160         continue;
6161       if (Val >= 4)
6162         break;
6163     }
6164
6165     Mask1[0] = PermMask[HiIndex];
6166     Mask1[1] = -1;
6167     Mask1[2] = PermMask[HiIndex^1];
6168     Mask1[3] = -1;
6169     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6170
6171     if (HiIndex >= 2) {
6172       Mask1[0] = PermMask[0];
6173       Mask1[1] = PermMask[1];
6174       Mask1[2] = HiIndex & 1 ? 6 : 4;
6175       Mask1[3] = HiIndex & 1 ? 4 : 6;
6176       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6177     }
6178
6179     Mask1[0] = HiIndex & 1 ? 2 : 0;
6180     Mask1[1] = HiIndex & 1 ? 0 : 2;
6181     Mask1[2] = PermMask[2];
6182     Mask1[3] = PermMask[3];
6183     if (Mask1[2] >= 0)
6184       Mask1[2] += 4;
6185     if (Mask1[3] >= 0)
6186       Mask1[3] += 4;
6187     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6188   }
6189
6190   // Break it into (shuffle shuffle_hi, shuffle_lo).
6191   int LoMask[] = { -1, -1, -1, -1 };
6192   int HiMask[] = { -1, -1, -1, -1 };
6193
6194   int *MaskPtr = LoMask;
6195   unsigned MaskIdx = 0;
6196   unsigned LoIdx = 0;
6197   unsigned HiIdx = 2;
6198   for (unsigned i = 0; i != 4; ++i) {
6199     if (i == 2) {
6200       MaskPtr = HiMask;
6201       MaskIdx = 1;
6202       LoIdx = 0;
6203       HiIdx = 2;
6204     }
6205     int Idx = PermMask[i];
6206     if (Idx < 0) {
6207       Locs[i] = std::make_pair(-1, -1);
6208     } else if (Idx < 4) {
6209       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6210       MaskPtr[LoIdx] = Idx;
6211       LoIdx++;
6212     } else {
6213       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6214       MaskPtr[HiIdx] = Idx;
6215       HiIdx++;
6216     }
6217   }
6218
6219   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6220   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6221   int MaskOps[] = { -1, -1, -1, -1 };
6222   for (unsigned i = 0; i != 4; ++i)
6223     if (Locs[i].first != -1)
6224       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6225   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6226 }
6227
6228 static bool MayFoldVectorLoad(SDValue V) {
6229   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6230     V = V.getOperand(0);
6231   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6232     V = V.getOperand(0);
6233   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6234       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6235     // BUILD_VECTOR (load), undef
6236     V = V.getOperand(0);
6237   if (MayFoldLoad(V))
6238     return true;
6239   return false;
6240 }
6241
6242 // FIXME: the version above should always be used. Since there's
6243 // a bug where several vector shuffles can't be folded because the
6244 // DAG is not updated during lowering and a node claims to have two
6245 // uses while it only has one, use this version, and let isel match
6246 // another instruction if the load really happens to have more than
6247 // one use. Remove this version after this bug get fixed.
6248 // rdar://8434668, PR8156
6249 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6250   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6251     V = V.getOperand(0);
6252   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6253     V = V.getOperand(0);
6254   if (ISD::isNormalLoad(V.getNode()))
6255     return true;
6256   return false;
6257 }
6258
6259 static
6260 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6261   EVT VT = Op.getValueType();
6262
6263   // Canonizalize to v2f64.
6264   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6265   return DAG.getNode(ISD::BITCAST, dl, VT,
6266                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6267                                           V1, DAG));
6268 }
6269
6270 static
6271 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6272                         bool HasSSE2) {
6273   SDValue V1 = Op.getOperand(0);
6274   SDValue V2 = Op.getOperand(1);
6275   EVT VT = Op.getValueType();
6276
6277   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6278
6279   if (HasSSE2 && VT == MVT::v2f64)
6280     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6281
6282   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6283   return DAG.getNode(ISD::BITCAST, dl, VT,
6284                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6285                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6286                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6287 }
6288
6289 static
6290 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6291   SDValue V1 = Op.getOperand(0);
6292   SDValue V2 = Op.getOperand(1);
6293   EVT VT = Op.getValueType();
6294
6295   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6296          "unsupported shuffle type");
6297
6298   if (V2.getOpcode() == ISD::UNDEF)
6299     V2 = V1;
6300
6301   // v4i32 or v4f32
6302   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6303 }
6304
6305 static
6306 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6307   SDValue V1 = Op.getOperand(0);
6308   SDValue V2 = Op.getOperand(1);
6309   EVT VT = Op.getValueType();
6310   unsigned NumElems = VT.getVectorNumElements();
6311
6312   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6313   // operand of these instructions is only memory, so check if there's a
6314   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6315   // same masks.
6316   bool CanFoldLoad = false;
6317
6318   // Trivial case, when V2 comes from a load.
6319   if (MayFoldVectorLoad(V2))
6320     CanFoldLoad = true;
6321
6322   // When V1 is a load, it can be folded later into a store in isel, example:
6323   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6324   //    turns into:
6325   //  (MOVLPSmr addr:$src1, VR128:$src2)
6326   // So, recognize this potential and also use MOVLPS or MOVLPD
6327   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6328     CanFoldLoad = true;
6329
6330   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6331   if (CanFoldLoad) {
6332     if (HasSSE2 && NumElems == 2)
6333       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6334
6335     if (NumElems == 4)
6336       // If we don't care about the second element, proceed to use movss.
6337       if (SVOp->getMaskElt(1) != -1)
6338         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6339   }
6340
6341   // movl and movlp will both match v2i64, but v2i64 is never matched by
6342   // movl earlier because we make it strict to avoid messing with the movlp load
6343   // folding logic (see the code above getMOVLP call). Match it here then,
6344   // this is horrible, but will stay like this until we move all shuffle
6345   // matching to x86 specific nodes. Note that for the 1st condition all
6346   // types are matched with movsd.
6347   if (HasSSE2) {
6348     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6349     // as to remove this logic from here, as much as possible
6350     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6351       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6352     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6353   }
6354
6355   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6356
6357   // Invert the operand order and use SHUFPS to match it.
6358   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6359                               getShuffleSHUFImmediate(SVOp), DAG);
6360 }
6361
6362 SDValue
6363 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6364   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6365   EVT VT = Op.getValueType();
6366   DebugLoc dl = Op.getDebugLoc();
6367   SDValue V1 = Op.getOperand(0);
6368   SDValue V2 = Op.getOperand(1);
6369
6370   if (isZeroShuffle(SVOp))
6371     return getZeroVector(VT, Subtarget, DAG, dl);
6372
6373   // Handle splat operations
6374   if (SVOp->isSplat()) {
6375     unsigned NumElem = VT.getVectorNumElements();
6376     int Size = VT.getSizeInBits();
6377
6378     // Use vbroadcast whenever the splat comes from a foldable load
6379     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6380     if (Broadcast.getNode())
6381       return Broadcast;
6382
6383     // Handle splats by matching through known shuffle masks
6384     if ((Size == 128 && NumElem <= 4) ||
6385         (Size == 256 && NumElem < 8))
6386       return SDValue();
6387
6388     // All remaning splats are promoted to target supported vector shuffles.
6389     return PromoteSplat(SVOp, DAG);
6390   }
6391
6392   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6393   // do it!
6394   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6395       VT == MVT::v16i16 || VT == MVT::v32i8) {
6396     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6397     if (NewOp.getNode())
6398       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6399   } else if ((VT == MVT::v4i32 ||
6400              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6401     // FIXME: Figure out a cleaner way to do this.
6402     // Try to make use of movq to zero out the top part.
6403     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6404       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6405       if (NewOp.getNode()) {
6406         EVT NewVT = NewOp.getValueType();
6407         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6408                                NewVT, true, false))
6409           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6410                               DAG, Subtarget, dl);
6411       }
6412     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6413       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6414       if (NewOp.getNode()) {
6415         EVT NewVT = NewOp.getValueType();
6416         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6417           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6418                               DAG, Subtarget, dl);
6419       }
6420     }
6421   }
6422   return SDValue();
6423 }
6424
6425 SDValue
6426 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6427   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6428   SDValue V1 = Op.getOperand(0);
6429   SDValue V2 = Op.getOperand(1);
6430   EVT VT = Op.getValueType();
6431   DebugLoc dl = Op.getDebugLoc();
6432   unsigned NumElems = VT.getVectorNumElements();
6433   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6434   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6435   bool V1IsSplat = false;
6436   bool V2IsSplat = false;
6437   bool HasSSE2 = Subtarget->hasSSE2();
6438   bool HasAVX    = Subtarget->hasAVX();
6439   bool HasAVX2   = Subtarget->hasAVX2();
6440   MachineFunction &MF = DAG.getMachineFunction();
6441   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6442
6443   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6444
6445   if (V1IsUndef && V2IsUndef)
6446     return DAG.getUNDEF(VT);
6447
6448   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6449
6450   // Vector shuffle lowering takes 3 steps:
6451   //
6452   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6453   //    narrowing and commutation of operands should be handled.
6454   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6455   //    shuffle nodes.
6456   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6457   //    so the shuffle can be broken into other shuffles and the legalizer can
6458   //    try the lowering again.
6459   //
6460   // The general idea is that no vector_shuffle operation should be left to
6461   // be matched during isel, all of them must be converted to a target specific
6462   // node here.
6463
6464   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6465   // narrowing and commutation of operands should be handled. The actual code
6466   // doesn't include all of those, work in progress...
6467   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6468   if (NewOp.getNode())
6469     return NewOp;
6470
6471   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6472
6473   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6474   // unpckh_undef). Only use pshufd if speed is more important than size.
6475   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6476     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6477   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6478     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6479
6480   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6481       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6482     return getMOVDDup(Op, dl, V1, DAG);
6483
6484   if (isMOVHLPS_v_undef_Mask(M, VT))
6485     return getMOVHighToLow(Op, dl, DAG);
6486
6487   // Use to match splats
6488   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6489       (VT == MVT::v2f64 || VT == MVT::v2i64))
6490     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6491
6492   if (isPSHUFDMask(M, VT)) {
6493     // The actual implementation will match the mask in the if above and then
6494     // during isel it can match several different instructions, not only pshufd
6495     // as its name says, sad but true, emulate the behavior for now...
6496     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6497       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6498
6499     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6500
6501     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6502       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6503
6504     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6505       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6506
6507     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6508                                 TargetMask, DAG);
6509   }
6510
6511   // Check if this can be converted into a logical shift.
6512   bool isLeft = false;
6513   unsigned ShAmt = 0;
6514   SDValue ShVal;
6515   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6516   if (isShift && ShVal.hasOneUse()) {
6517     // If the shifted value has multiple uses, it may be cheaper to use
6518     // v_set0 + movlhps or movhlps, etc.
6519     EVT EltVT = VT.getVectorElementType();
6520     ShAmt *= EltVT.getSizeInBits();
6521     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6522   }
6523
6524   if (isMOVLMask(M, VT)) {
6525     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6526       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6527     if (!isMOVLPMask(M, VT)) {
6528       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6529         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6530
6531       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6532         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6533     }
6534   }
6535
6536   // FIXME: fold these into legal mask.
6537   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6538     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6539
6540   if (isMOVHLPSMask(M, VT))
6541     return getMOVHighToLow(Op, dl, DAG);
6542
6543   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6544     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6545
6546   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6547     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6548
6549   if (isMOVLPMask(M, VT))
6550     return getMOVLP(Op, dl, DAG, HasSSE2);
6551
6552   if (ShouldXformToMOVHLPS(M, VT) ||
6553       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6554     return CommuteVectorShuffle(SVOp, DAG);
6555
6556   if (isShift) {
6557     // No better options. Use a vshldq / vsrldq.
6558     EVT EltVT = VT.getVectorElementType();
6559     ShAmt *= EltVT.getSizeInBits();
6560     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6561   }
6562
6563   bool Commuted = false;
6564   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6565   // 1,1,1,1 -> v8i16 though.
6566   V1IsSplat = isSplatVector(V1.getNode());
6567   V2IsSplat = isSplatVector(V2.getNode());
6568
6569   // Canonicalize the splat or undef, if present, to be on the RHS.
6570   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6571     CommuteVectorShuffleMask(M, NumElems);
6572     std::swap(V1, V2);
6573     std::swap(V1IsSplat, V2IsSplat);
6574     Commuted = true;
6575   }
6576
6577   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6578     // Shuffling low element of v1 into undef, just return v1.
6579     if (V2IsUndef)
6580       return V1;
6581     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6582     // the instruction selector will not match, so get a canonical MOVL with
6583     // swapped operands to undo the commute.
6584     return getMOVL(DAG, dl, VT, V2, V1);
6585   }
6586
6587   if (isUNPCKLMask(M, VT, HasAVX2))
6588     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6589
6590   if (isUNPCKHMask(M, VT, HasAVX2))
6591     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6592
6593   if (V2IsSplat) {
6594     // Normalize mask so all entries that point to V2 points to its first
6595     // element then try to match unpck{h|l} again. If match, return a
6596     // new vector_shuffle with the corrected mask.p
6597     SmallVector<int, 8> NewMask(M.begin(), M.end());
6598     NormalizeMask(NewMask, NumElems);
6599     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6600       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6601     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6602       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6603   }
6604
6605   if (Commuted) {
6606     // Commute is back and try unpck* again.
6607     // FIXME: this seems wrong.
6608     CommuteVectorShuffleMask(M, NumElems);
6609     std::swap(V1, V2);
6610     std::swap(V1IsSplat, V2IsSplat);
6611     Commuted = false;
6612
6613     if (isUNPCKLMask(M, VT, HasAVX2))
6614       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6615
6616     if (isUNPCKHMask(M, VT, HasAVX2))
6617       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6618   }
6619
6620   // Normalize the node to match x86 shuffle ops if needed
6621   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6622     return CommuteVectorShuffle(SVOp, DAG);
6623
6624   // The checks below are all present in isShuffleMaskLegal, but they are
6625   // inlined here right now to enable us to directly emit target specific
6626   // nodes, and remove one by one until they don't return Op anymore.
6627
6628   if (isPALIGNRMask(M, VT, Subtarget))
6629     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6630                                 getShufflePALIGNRImmediate(SVOp),
6631                                 DAG);
6632
6633   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6634       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6635     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6636       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6637   }
6638
6639   if (isPSHUFHWMask(M, VT, HasAVX2))
6640     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6641                                 getShufflePSHUFHWImmediate(SVOp),
6642                                 DAG);
6643
6644   if (isPSHUFLWMask(M, VT, HasAVX2))
6645     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6646                                 getShufflePSHUFLWImmediate(SVOp),
6647                                 DAG);
6648
6649   if (isSHUFPMask(M, VT, HasAVX))
6650     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6651                                 getShuffleSHUFImmediate(SVOp), DAG);
6652
6653   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6654     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6655   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6656     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6657
6658   //===--------------------------------------------------------------------===//
6659   // Generate target specific nodes for 128 or 256-bit shuffles only
6660   // supported in the AVX instruction set.
6661   //
6662
6663   // Handle VMOVDDUPY permutations
6664   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6665     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6666
6667   // Handle VPERMILPS/D* permutations
6668   if (isVPERMILPMask(M, VT, HasAVX)) {
6669     if (HasAVX2 && VT == MVT::v8i32)
6670       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6671                                   getShuffleSHUFImmediate(SVOp), DAG);
6672     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6673                                 getShuffleSHUFImmediate(SVOp), DAG);
6674   }
6675
6676   // Handle VPERM2F128/VPERM2I128 permutations
6677   if (isVPERM2X128Mask(M, VT, HasAVX))
6678     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6679                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6680
6681   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6682   if (BlendOp.getNode())
6683     return BlendOp;
6684
6685   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6686     SmallVector<SDValue, 8> permclMask;
6687     for (unsigned i = 0; i != 8; ++i) {
6688       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6689     }
6690     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6691                                &permclMask[0], 8);
6692     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6693     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6694                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6695   }
6696
6697   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6698     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6699                                 getShuffleCLImmediate(SVOp), DAG);
6700
6701
6702   //===--------------------------------------------------------------------===//
6703   // Since no target specific shuffle was selected for this generic one,
6704   // lower it into other known shuffles. FIXME: this isn't true yet, but
6705   // this is the plan.
6706   //
6707
6708   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6709   if (VT == MVT::v8i16) {
6710     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6711     if (NewOp.getNode())
6712       return NewOp;
6713   }
6714
6715   if (VT == MVT::v16i8) {
6716     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6717     if (NewOp.getNode())
6718       return NewOp;
6719   }
6720
6721   // Handle all 128-bit wide vectors with 4 elements, and match them with
6722   // several different shuffle types.
6723   if (NumElems == 4 && VT.getSizeInBits() == 128)
6724     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6725
6726   // Handle general 256-bit shuffles
6727   if (VT.is256BitVector())
6728     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6729
6730   return SDValue();
6731 }
6732
6733 SDValue
6734 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6735                                                 SelectionDAG &DAG) const {
6736   EVT VT = Op.getValueType();
6737   DebugLoc dl = Op.getDebugLoc();
6738
6739   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6740     return SDValue();
6741
6742   if (VT.getSizeInBits() == 8) {
6743     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6744                                     Op.getOperand(0), Op.getOperand(1));
6745     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6746                                     DAG.getValueType(VT));
6747     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6748   }
6749
6750   if (VT.getSizeInBits() == 16) {
6751     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6752     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6753     if (Idx == 0)
6754       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6755                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6756                                      DAG.getNode(ISD::BITCAST, dl,
6757                                                  MVT::v4i32,
6758                                                  Op.getOperand(0)),
6759                                      Op.getOperand(1)));
6760     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6761                                     Op.getOperand(0), Op.getOperand(1));
6762     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6763                                     DAG.getValueType(VT));
6764     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6765   }
6766
6767   if (VT == MVT::f32) {
6768     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6769     // the result back to FR32 register. It's only worth matching if the
6770     // result has a single use which is a store or a bitcast to i32.  And in
6771     // the case of a store, it's not worth it if the index is a constant 0,
6772     // because a MOVSSmr can be used instead, which is smaller and faster.
6773     if (!Op.hasOneUse())
6774       return SDValue();
6775     SDNode *User = *Op.getNode()->use_begin();
6776     if ((User->getOpcode() != ISD::STORE ||
6777          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6778           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6779         (User->getOpcode() != ISD::BITCAST ||
6780          User->getValueType(0) != MVT::i32))
6781       return SDValue();
6782     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6783                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6784                                               Op.getOperand(0)),
6785                                               Op.getOperand(1));
6786     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6787   }
6788
6789   if (VT == MVT::i32 || VT == MVT::i64) {
6790     // ExtractPS/pextrq works with constant index.
6791     if (isa<ConstantSDNode>(Op.getOperand(1)))
6792       return Op;
6793   }
6794   return SDValue();
6795 }
6796
6797
6798 SDValue
6799 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6800                                            SelectionDAG &DAG) const {
6801   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6802     return SDValue();
6803
6804   SDValue Vec = Op.getOperand(0);
6805   EVT VecVT = Vec.getValueType();
6806
6807   // If this is a 256-bit vector result, first extract the 128-bit vector and
6808   // then extract the element from the 128-bit vector.
6809   if (VecVT.getSizeInBits() == 256) {
6810     DebugLoc dl = Op.getNode()->getDebugLoc();
6811     unsigned NumElems = VecVT.getVectorNumElements();
6812     SDValue Idx = Op.getOperand(1);
6813     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6814
6815     // Get the 128-bit vector.
6816     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6817
6818     if (IdxVal >= NumElems/2)
6819       IdxVal -= NumElems/2;
6820     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6821                        DAG.getConstant(IdxVal, MVT::i32));
6822   }
6823
6824   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6825
6826   if (Subtarget->hasSSE41()) {
6827     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6828     if (Res.getNode())
6829       return Res;
6830   }
6831
6832   EVT VT = Op.getValueType();
6833   DebugLoc dl = Op.getDebugLoc();
6834   // TODO: handle v16i8.
6835   if (VT.getSizeInBits() == 16) {
6836     SDValue Vec = Op.getOperand(0);
6837     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6838     if (Idx == 0)
6839       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6840                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6841                                      DAG.getNode(ISD::BITCAST, dl,
6842                                                  MVT::v4i32, Vec),
6843                                      Op.getOperand(1)));
6844     // Transform it so it match pextrw which produces a 32-bit result.
6845     EVT EltVT = MVT::i32;
6846     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6847                                     Op.getOperand(0), Op.getOperand(1));
6848     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6849                                     DAG.getValueType(VT));
6850     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6851   }
6852
6853   if (VT.getSizeInBits() == 32) {
6854     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6855     if (Idx == 0)
6856       return Op;
6857
6858     // SHUFPS the element to the lowest double word, then movss.
6859     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6860     EVT VVT = Op.getOperand(0).getValueType();
6861     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6862                                        DAG.getUNDEF(VVT), Mask);
6863     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6864                        DAG.getIntPtrConstant(0));
6865   }
6866
6867   if (VT.getSizeInBits() == 64) {
6868     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6869     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6870     //        to match extract_elt for f64.
6871     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6872     if (Idx == 0)
6873       return Op;
6874
6875     // UNPCKHPD the element to the lowest double word, then movsd.
6876     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6877     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6878     int Mask[2] = { 1, -1 };
6879     EVT VVT = Op.getOperand(0).getValueType();
6880     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6881                                        DAG.getUNDEF(VVT), Mask);
6882     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6883                        DAG.getIntPtrConstant(0));
6884   }
6885
6886   return SDValue();
6887 }
6888
6889 SDValue
6890 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6891                                                SelectionDAG &DAG) const {
6892   EVT VT = Op.getValueType();
6893   EVT EltVT = VT.getVectorElementType();
6894   DebugLoc dl = Op.getDebugLoc();
6895
6896   SDValue N0 = Op.getOperand(0);
6897   SDValue N1 = Op.getOperand(1);
6898   SDValue N2 = Op.getOperand(2);
6899
6900   if (VT.getSizeInBits() == 256)
6901     return SDValue();
6902
6903   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6904       isa<ConstantSDNode>(N2)) {
6905     unsigned Opc;
6906     if (VT == MVT::v8i16)
6907       Opc = X86ISD::PINSRW;
6908     else if (VT == MVT::v16i8)
6909       Opc = X86ISD::PINSRB;
6910     else
6911       Opc = X86ISD::PINSRB;
6912
6913     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6914     // argument.
6915     if (N1.getValueType() != MVT::i32)
6916       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6917     if (N2.getValueType() != MVT::i32)
6918       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6919     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6920   }
6921
6922   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6923     // Bits [7:6] of the constant are the source select.  This will always be
6924     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6925     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6926     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6927     // Bits [5:4] of the constant are the destination select.  This is the
6928     //  value of the incoming immediate.
6929     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6930     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6931     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6932     // Create this as a scalar to vector..
6933     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6934     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6935   }
6936
6937   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
6938     // PINSR* works with constant index.
6939     return Op;
6940   }
6941   return SDValue();
6942 }
6943
6944 SDValue
6945 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6946   EVT VT = Op.getValueType();
6947   EVT EltVT = VT.getVectorElementType();
6948
6949   DebugLoc dl = Op.getDebugLoc();
6950   SDValue N0 = Op.getOperand(0);
6951   SDValue N1 = Op.getOperand(1);
6952   SDValue N2 = Op.getOperand(2);
6953
6954   // If this is a 256-bit vector result, first extract the 128-bit vector,
6955   // insert the element into the extracted half and then place it back.
6956   if (VT.getSizeInBits() == 256) {
6957     if (!isa<ConstantSDNode>(N2))
6958       return SDValue();
6959
6960     // Get the desired 128-bit vector half.
6961     unsigned NumElems = VT.getVectorNumElements();
6962     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6963     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
6964
6965     // Insert the element into the desired half.
6966     bool Upper = IdxVal >= NumElems/2;
6967     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
6968                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
6969
6970     // Insert the changed part back to the 256-bit vector
6971     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
6972   }
6973
6974   if (Subtarget->hasSSE41())
6975     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6976
6977   if (EltVT == MVT::i8)
6978     return SDValue();
6979
6980   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6981     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6982     // as its second argument.
6983     if (N1.getValueType() != MVT::i32)
6984       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6985     if (N2.getValueType() != MVT::i32)
6986       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6987     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6988   }
6989   return SDValue();
6990 }
6991
6992 SDValue
6993 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6994   LLVMContext *Context = DAG.getContext();
6995   DebugLoc dl = Op.getDebugLoc();
6996   EVT OpVT = Op.getValueType();
6997
6998   // If this is a 256-bit vector result, first insert into a 128-bit
6999   // vector and then insert into the 256-bit vector.
7000   if (OpVT.getSizeInBits() > 128) {
7001     // Insert into a 128-bit vector.
7002     EVT VT128 = EVT::getVectorVT(*Context,
7003                                  OpVT.getVectorElementType(),
7004                                  OpVT.getVectorNumElements() / 2);
7005
7006     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7007
7008     // Insert the 128-bit vector.
7009     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7010   }
7011
7012   if (OpVT == MVT::v1i64 &&
7013       Op.getOperand(0).getValueType() == MVT::i64)
7014     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7015
7016   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7017   assert(OpVT.getSizeInBits() == 128 && "Expected an SSE type!");
7018   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7019                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7020 }
7021
7022 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7023 // a simple subregister reference or explicit instructions to grab
7024 // upper bits of a vector.
7025 SDValue
7026 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7027   if (Subtarget->hasAVX()) {
7028     DebugLoc dl = Op.getNode()->getDebugLoc();
7029     SDValue Vec = Op.getNode()->getOperand(0);
7030     SDValue Idx = Op.getNode()->getOperand(1);
7031
7032     if (Op.getNode()->getValueType(0).getSizeInBits() == 128 &&
7033         Vec.getNode()->getValueType(0).getSizeInBits() == 256 &&
7034         isa<ConstantSDNode>(Idx)) {
7035       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7036       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7037     }
7038   }
7039   return SDValue();
7040 }
7041
7042 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7043 // simple superregister reference or explicit instructions to insert
7044 // the upper bits of a vector.
7045 SDValue
7046 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7047   if (Subtarget->hasAVX()) {
7048     DebugLoc dl = Op.getNode()->getDebugLoc();
7049     SDValue Vec = Op.getNode()->getOperand(0);
7050     SDValue SubVec = Op.getNode()->getOperand(1);
7051     SDValue Idx = Op.getNode()->getOperand(2);
7052
7053     if (Op.getNode()->getValueType(0).getSizeInBits() == 256 &&
7054         SubVec.getNode()->getValueType(0).getSizeInBits() == 128 &&
7055         isa<ConstantSDNode>(Idx)) {
7056       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7057       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7058     }
7059   }
7060   return SDValue();
7061 }
7062
7063 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7064 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7065 // one of the above mentioned nodes. It has to be wrapped because otherwise
7066 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7067 // be used to form addressing mode. These wrapped nodes will be selected
7068 // into MOV32ri.
7069 SDValue
7070 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7071   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7072
7073   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7074   // global base reg.
7075   unsigned char OpFlag = 0;
7076   unsigned WrapperKind = X86ISD::Wrapper;
7077   CodeModel::Model M = getTargetMachine().getCodeModel();
7078
7079   if (Subtarget->isPICStyleRIPRel() &&
7080       (M == CodeModel::Small || M == CodeModel::Kernel))
7081     WrapperKind = X86ISD::WrapperRIP;
7082   else if (Subtarget->isPICStyleGOT())
7083     OpFlag = X86II::MO_GOTOFF;
7084   else if (Subtarget->isPICStyleStubPIC())
7085     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7086
7087   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7088                                              CP->getAlignment(),
7089                                              CP->getOffset(), OpFlag);
7090   DebugLoc DL = CP->getDebugLoc();
7091   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7092   // With PIC, the address is actually $g + Offset.
7093   if (OpFlag) {
7094     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7095                          DAG.getNode(X86ISD::GlobalBaseReg,
7096                                      DebugLoc(), getPointerTy()),
7097                          Result);
7098   }
7099
7100   return Result;
7101 }
7102
7103 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7104   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7105
7106   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7107   // global base reg.
7108   unsigned char OpFlag = 0;
7109   unsigned WrapperKind = X86ISD::Wrapper;
7110   CodeModel::Model M = getTargetMachine().getCodeModel();
7111
7112   if (Subtarget->isPICStyleRIPRel() &&
7113       (M == CodeModel::Small || M == CodeModel::Kernel))
7114     WrapperKind = X86ISD::WrapperRIP;
7115   else if (Subtarget->isPICStyleGOT())
7116     OpFlag = X86II::MO_GOTOFF;
7117   else if (Subtarget->isPICStyleStubPIC())
7118     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7119
7120   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7121                                           OpFlag);
7122   DebugLoc DL = JT->getDebugLoc();
7123   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7124
7125   // With PIC, the address is actually $g + Offset.
7126   if (OpFlag)
7127     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7128                          DAG.getNode(X86ISD::GlobalBaseReg,
7129                                      DebugLoc(), getPointerTy()),
7130                          Result);
7131
7132   return Result;
7133 }
7134
7135 SDValue
7136 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7137   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7138
7139   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7140   // global base reg.
7141   unsigned char OpFlag = 0;
7142   unsigned WrapperKind = X86ISD::Wrapper;
7143   CodeModel::Model M = getTargetMachine().getCodeModel();
7144
7145   if (Subtarget->isPICStyleRIPRel() &&
7146       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7147     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7148       OpFlag = X86II::MO_GOTPCREL;
7149     WrapperKind = X86ISD::WrapperRIP;
7150   } else if (Subtarget->isPICStyleGOT()) {
7151     OpFlag = X86II::MO_GOT;
7152   } else if (Subtarget->isPICStyleStubPIC()) {
7153     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7154   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7155     OpFlag = X86II::MO_DARWIN_NONLAZY;
7156   }
7157
7158   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7159
7160   DebugLoc DL = Op.getDebugLoc();
7161   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7162
7163
7164   // With PIC, the address is actually $g + Offset.
7165   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7166       !Subtarget->is64Bit()) {
7167     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7168                          DAG.getNode(X86ISD::GlobalBaseReg,
7169                                      DebugLoc(), getPointerTy()),
7170                          Result);
7171   }
7172
7173   // For symbols that require a load from a stub to get the address, emit the
7174   // load.
7175   if (isGlobalStubReference(OpFlag))
7176     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7177                          MachinePointerInfo::getGOT(), false, false, false, 0);
7178
7179   return Result;
7180 }
7181
7182 SDValue
7183 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7184   // Create the TargetBlockAddressAddress node.
7185   unsigned char OpFlags =
7186     Subtarget->ClassifyBlockAddressReference();
7187   CodeModel::Model M = getTargetMachine().getCodeModel();
7188   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7189   DebugLoc dl = Op.getDebugLoc();
7190   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7191                                        /*isTarget=*/true, OpFlags);
7192
7193   if (Subtarget->isPICStyleRIPRel() &&
7194       (M == CodeModel::Small || M == CodeModel::Kernel))
7195     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7196   else
7197     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7198
7199   // With PIC, the address is actually $g + Offset.
7200   if (isGlobalRelativeToPICBase(OpFlags)) {
7201     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7202                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7203                          Result);
7204   }
7205
7206   return Result;
7207 }
7208
7209 SDValue
7210 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7211                                       int64_t Offset,
7212                                       SelectionDAG &DAG) const {
7213   // Create the TargetGlobalAddress node, folding in the constant
7214   // offset if it is legal.
7215   unsigned char OpFlags =
7216     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7217   CodeModel::Model M = getTargetMachine().getCodeModel();
7218   SDValue Result;
7219   if (OpFlags == X86II::MO_NO_FLAG &&
7220       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7221     // A direct static reference to a global.
7222     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7223     Offset = 0;
7224   } else {
7225     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7226   }
7227
7228   if (Subtarget->isPICStyleRIPRel() &&
7229       (M == CodeModel::Small || M == CodeModel::Kernel))
7230     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7231   else
7232     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7233
7234   // With PIC, the address is actually $g + Offset.
7235   if (isGlobalRelativeToPICBase(OpFlags)) {
7236     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7237                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7238                          Result);
7239   }
7240
7241   // For globals that require a load from a stub to get the address, emit the
7242   // load.
7243   if (isGlobalStubReference(OpFlags))
7244     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7245                          MachinePointerInfo::getGOT(), false, false, false, 0);
7246
7247   // If there was a non-zero offset that we didn't fold, create an explicit
7248   // addition for it.
7249   if (Offset != 0)
7250     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7251                          DAG.getConstant(Offset, getPointerTy()));
7252
7253   return Result;
7254 }
7255
7256 SDValue
7257 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7258   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7259   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7260   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7261 }
7262
7263 static SDValue
7264 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7265            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7266            unsigned char OperandFlags, bool LocalDynamic = false) {
7267   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7268   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7269   DebugLoc dl = GA->getDebugLoc();
7270   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7271                                            GA->getValueType(0),
7272                                            GA->getOffset(),
7273                                            OperandFlags);
7274
7275   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7276                                            : X86ISD::TLSADDR;
7277
7278   if (InFlag) {
7279     SDValue Ops[] = { Chain,  TGA, *InFlag };
7280     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7281   } else {
7282     SDValue Ops[]  = { Chain, TGA };
7283     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7284   }
7285
7286   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7287   MFI->setAdjustsStack(true);
7288
7289   SDValue Flag = Chain.getValue(1);
7290   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7291 }
7292
7293 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7294 static SDValue
7295 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7296                                 const EVT PtrVT) {
7297   SDValue InFlag;
7298   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7299   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7300                                      DAG.getNode(X86ISD::GlobalBaseReg,
7301                                                  DebugLoc(), PtrVT), InFlag);
7302   InFlag = Chain.getValue(1);
7303
7304   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7305 }
7306
7307 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7308 static SDValue
7309 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7310                                 const EVT PtrVT) {
7311   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7312                     X86::RAX, X86II::MO_TLSGD);
7313 }
7314
7315 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7316                                            SelectionDAG &DAG,
7317                                            const EVT PtrVT,
7318                                            bool is64Bit) {
7319   DebugLoc dl = GA->getDebugLoc();
7320
7321   // Get the start address of the TLS block for this module.
7322   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7323       .getInfo<X86MachineFunctionInfo>();
7324   MFI->incNumLocalDynamicTLSAccesses();
7325
7326   SDValue Base;
7327   if (is64Bit) {
7328     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7329                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7330   } else {
7331     SDValue InFlag;
7332     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7333         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7334     InFlag = Chain.getValue(1);
7335     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7336                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7337   }
7338
7339   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7340   // of Base.
7341
7342   // Build x@dtpoff.
7343   unsigned char OperandFlags = X86II::MO_DTPOFF;
7344   unsigned WrapperKind = X86ISD::Wrapper;
7345   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7346                                            GA->getValueType(0),
7347                                            GA->getOffset(), OperandFlags);
7348   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7349
7350   // Add x@dtpoff with the base.
7351   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7352 }
7353
7354 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7355 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7356                                    const EVT PtrVT, TLSModel::Model model,
7357                                    bool is64Bit, bool isPIC) {
7358   DebugLoc dl = GA->getDebugLoc();
7359
7360   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7361   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7362                                                          is64Bit ? 257 : 256));
7363
7364   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7365                                       DAG.getIntPtrConstant(0),
7366                                       MachinePointerInfo(Ptr),
7367                                       false, false, false, 0);
7368
7369   unsigned char OperandFlags = 0;
7370   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7371   // initialexec.
7372   unsigned WrapperKind = X86ISD::Wrapper;
7373   if (model == TLSModel::LocalExec) {
7374     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7375   } else if (model == TLSModel::InitialExec) {
7376     if (is64Bit) {
7377       OperandFlags = X86II::MO_GOTTPOFF;
7378       WrapperKind = X86ISD::WrapperRIP;
7379     } else {
7380       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7381     }
7382   } else {
7383     llvm_unreachable("Unexpected model");
7384   }
7385
7386   // emit "addl x@ntpoff,%eax" (local exec)
7387   // or "addl x@indntpoff,%eax" (initial exec)
7388   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7389   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7390                                            GA->getValueType(0),
7391                                            GA->getOffset(), OperandFlags);
7392   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7393
7394   if (model == TLSModel::InitialExec) {
7395     if (isPIC && !is64Bit) {
7396       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7397                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7398                            Offset);
7399     } else {
7400       Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7401                            MachinePointerInfo::getGOT(), false, false, false,
7402                            0);
7403     }
7404   }
7405
7406   // The address of the thread local variable is the add of the thread
7407   // pointer with the offset of the variable.
7408   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7409 }
7410
7411 SDValue
7412 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7413
7414   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7415   const GlobalValue *GV = GA->getGlobal();
7416
7417   if (Subtarget->isTargetELF()) {
7418     // If GV is an alias then use the aliasee for determining
7419     // thread-localness.
7420     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7421       GV = GA->resolveAliasedGlobal(false);
7422
7423     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7424
7425     switch (model) {
7426       case TLSModel::GeneralDynamic:
7427         if (Subtarget->is64Bit())
7428           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7429         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7430       case TLSModel::LocalDynamic:
7431         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7432                                            Subtarget->is64Bit());
7433       case TLSModel::InitialExec:
7434       case TLSModel::LocalExec:
7435         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7436                                    Subtarget->is64Bit(),
7437                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7438     }
7439     llvm_unreachable("Unknown TLS model.");
7440   }
7441
7442   if (Subtarget->isTargetDarwin()) {
7443     // Darwin only has one model of TLS.  Lower to that.
7444     unsigned char OpFlag = 0;
7445     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7446                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7447
7448     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7449     // global base reg.
7450     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7451                   !Subtarget->is64Bit();
7452     if (PIC32)
7453       OpFlag = X86II::MO_TLVP_PIC_BASE;
7454     else
7455       OpFlag = X86II::MO_TLVP;
7456     DebugLoc DL = Op.getDebugLoc();
7457     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7458                                                 GA->getValueType(0),
7459                                                 GA->getOffset(), OpFlag);
7460     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7461
7462     // With PIC32, the address is actually $g + Offset.
7463     if (PIC32)
7464       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7465                            DAG.getNode(X86ISD::GlobalBaseReg,
7466                                        DebugLoc(), getPointerTy()),
7467                            Offset);
7468
7469     // Lowering the machine isd will make sure everything is in the right
7470     // location.
7471     SDValue Chain = DAG.getEntryNode();
7472     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7473     SDValue Args[] = { Chain, Offset };
7474     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7475
7476     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7477     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7478     MFI->setAdjustsStack(true);
7479
7480     // And our return value (tls address) is in the standard call return value
7481     // location.
7482     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7483     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7484                               Chain.getValue(1));
7485   }
7486
7487   if (Subtarget->isTargetWindows()) {
7488     // Just use the implicit TLS architecture
7489     // Need to generate someting similar to:
7490     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7491     //                                  ; from TEB
7492     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7493     //   mov     rcx, qword [rdx+rcx*8]
7494     //   mov     eax, .tls$:tlsvar
7495     //   [rax+rcx] contains the address
7496     // Windows 64bit: gs:0x58
7497     // Windows 32bit: fs:__tls_array
7498
7499     // If GV is an alias then use the aliasee for determining
7500     // thread-localness.
7501     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7502       GV = GA->resolveAliasedGlobal(false);
7503     DebugLoc dl = GA->getDebugLoc();
7504     SDValue Chain = DAG.getEntryNode();
7505
7506     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7507     // %gs:0x58 (64-bit).
7508     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7509                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7510                                                              256)
7511                                         : Type::getInt32PtrTy(*DAG.getContext(),
7512                                                               257));
7513
7514     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7515                                         Subtarget->is64Bit()
7516                                         ? DAG.getIntPtrConstant(0x58)
7517                                         : DAG.getExternalSymbol("_tls_array",
7518                                                                 getPointerTy()),
7519                                         MachinePointerInfo(Ptr),
7520                                         false, false, false, 0);
7521
7522     // Load the _tls_index variable
7523     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7524     if (Subtarget->is64Bit())
7525       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7526                            IDX, MachinePointerInfo(), MVT::i32,
7527                            false, false, 0);
7528     else
7529       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7530                         false, false, false, 0);
7531
7532     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7533                                     getPointerTy());
7534     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7535
7536     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7537     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7538                       false, false, false, 0);
7539
7540     // Get the offset of start of .tls section
7541     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7542                                              GA->getValueType(0),
7543                                              GA->getOffset(), X86II::MO_SECREL);
7544     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7545
7546     // The address of the thread local variable is the add of the thread
7547     // pointer with the offset of the variable.
7548     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7549   }
7550
7551   llvm_unreachable("TLS not implemented for this target.");
7552 }
7553
7554
7555 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7556 /// and take a 2 x i32 value to shift plus a shift amount.
7557 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7558   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7559   EVT VT = Op.getValueType();
7560   unsigned VTBits = VT.getSizeInBits();
7561   DebugLoc dl = Op.getDebugLoc();
7562   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7563   SDValue ShOpLo = Op.getOperand(0);
7564   SDValue ShOpHi = Op.getOperand(1);
7565   SDValue ShAmt  = Op.getOperand(2);
7566   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7567                                      DAG.getConstant(VTBits - 1, MVT::i8))
7568                        : DAG.getConstant(0, VT);
7569
7570   SDValue Tmp2, Tmp3;
7571   if (Op.getOpcode() == ISD::SHL_PARTS) {
7572     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7573     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7574   } else {
7575     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7576     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7577   }
7578
7579   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7580                                 DAG.getConstant(VTBits, MVT::i8));
7581   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7582                              AndNode, DAG.getConstant(0, MVT::i8));
7583
7584   SDValue Hi, Lo;
7585   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7586   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7587   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7588
7589   if (Op.getOpcode() == ISD::SHL_PARTS) {
7590     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7591     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7592   } else {
7593     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7594     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7595   }
7596
7597   SDValue Ops[2] = { Lo, Hi };
7598   return DAG.getMergeValues(Ops, 2, dl);
7599 }
7600
7601 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7602                                            SelectionDAG &DAG) const {
7603   EVT SrcVT = Op.getOperand(0).getValueType();
7604
7605   if (SrcVT.isVector())
7606     return SDValue();
7607
7608   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7609          "Unknown SINT_TO_FP to lower!");
7610
7611   // These are really Legal; return the operand so the caller accepts it as
7612   // Legal.
7613   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7614     return Op;
7615   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7616       Subtarget->is64Bit()) {
7617     return Op;
7618   }
7619
7620   DebugLoc dl = Op.getDebugLoc();
7621   unsigned Size = SrcVT.getSizeInBits()/8;
7622   MachineFunction &MF = DAG.getMachineFunction();
7623   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7624   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7625   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7626                                StackSlot,
7627                                MachinePointerInfo::getFixedStack(SSFI),
7628                                false, false, 0);
7629   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7630 }
7631
7632 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7633                                      SDValue StackSlot,
7634                                      SelectionDAG &DAG) const {
7635   // Build the FILD
7636   DebugLoc DL = Op.getDebugLoc();
7637   SDVTList Tys;
7638   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7639   if (useSSE)
7640     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7641   else
7642     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7643
7644   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7645
7646   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7647   MachineMemOperand *MMO;
7648   if (FI) {
7649     int SSFI = FI->getIndex();
7650     MMO =
7651       DAG.getMachineFunction()
7652       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7653                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7654   } else {
7655     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7656     StackSlot = StackSlot.getOperand(1);
7657   }
7658   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7659   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7660                                            X86ISD::FILD, DL,
7661                                            Tys, Ops, array_lengthof(Ops),
7662                                            SrcVT, MMO);
7663
7664   if (useSSE) {
7665     Chain = Result.getValue(1);
7666     SDValue InFlag = Result.getValue(2);
7667
7668     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7669     // shouldn't be necessary except that RFP cannot be live across
7670     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7671     MachineFunction &MF = DAG.getMachineFunction();
7672     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7673     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7674     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7675     Tys = DAG.getVTList(MVT::Other);
7676     SDValue Ops[] = {
7677       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7678     };
7679     MachineMemOperand *MMO =
7680       DAG.getMachineFunction()
7681       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7682                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7683
7684     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7685                                     Ops, array_lengthof(Ops),
7686                                     Op.getValueType(), MMO);
7687     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7688                          MachinePointerInfo::getFixedStack(SSFI),
7689                          false, false, false, 0);
7690   }
7691
7692   return Result;
7693 }
7694
7695 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7696 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7697                                                SelectionDAG &DAG) const {
7698   // This algorithm is not obvious. Here it is what we're trying to output:
7699   /*
7700      movq       %rax,  %xmm0
7701      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7702      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7703      #ifdef __SSE3__
7704        haddpd   %xmm0, %xmm0          
7705      #else
7706        pshufd   $0x4e, %xmm0, %xmm1 
7707        addpd    %xmm1, %xmm0
7708      #endif
7709   */
7710
7711   DebugLoc dl = Op.getDebugLoc();
7712   LLVMContext *Context = DAG.getContext();
7713
7714   // Build some magic constants.
7715   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7716   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7717   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7718
7719   SmallVector<Constant*,2> CV1;
7720   CV1.push_back(
7721         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7722   CV1.push_back(
7723         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7724   Constant *C1 = ConstantVector::get(CV1);
7725   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7726
7727   // Load the 64-bit value into an XMM register.
7728   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7729                             Op.getOperand(0));
7730   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7731                               MachinePointerInfo::getConstantPool(),
7732                               false, false, false, 16);
7733   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7734                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7735                               CLod0);
7736
7737   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7738                               MachinePointerInfo::getConstantPool(),
7739                               false, false, false, 16);
7740   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7741   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7742   SDValue Result;
7743
7744   if (Subtarget->hasSSE3()) {
7745     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7746     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7747   } else {
7748     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7749     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7750                                            S2F, 0x4E, DAG);
7751     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7752                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7753                          Sub);
7754   }
7755
7756   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7757                      DAG.getIntPtrConstant(0));
7758 }
7759
7760 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7761 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7762                                                SelectionDAG &DAG) const {
7763   DebugLoc dl = Op.getDebugLoc();
7764   // FP constant to bias correct the final result.
7765   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7766                                    MVT::f64);
7767
7768   // Load the 32-bit value into an XMM register.
7769   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7770                              Op.getOperand(0));
7771
7772   // Zero out the upper parts of the register.
7773   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7774
7775   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7776                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7777                      DAG.getIntPtrConstant(0));
7778
7779   // Or the load with the bias.
7780   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7781                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7782                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7783                                                    MVT::v2f64, Load)),
7784                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7785                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7786                                                    MVT::v2f64, Bias)));
7787   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7788                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7789                    DAG.getIntPtrConstant(0));
7790
7791   // Subtract the bias.
7792   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7793
7794   // Handle final rounding.
7795   EVT DestVT = Op.getValueType();
7796
7797   if (DestVT.bitsLT(MVT::f64))
7798     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7799                        DAG.getIntPtrConstant(0));
7800   if (DestVT.bitsGT(MVT::f64))
7801     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7802
7803   // Handle final rounding.
7804   return Sub;
7805 }
7806
7807 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7808                                            SelectionDAG &DAG) const {
7809   SDValue N0 = Op.getOperand(0);
7810   DebugLoc dl = Op.getDebugLoc();
7811
7812   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7813   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7814   // the optimization here.
7815   if (DAG.SignBitIsZero(N0))
7816     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7817
7818   EVT SrcVT = N0.getValueType();
7819   EVT DstVT = Op.getValueType();
7820   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7821     return LowerUINT_TO_FP_i64(Op, DAG);
7822   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7823     return LowerUINT_TO_FP_i32(Op, DAG);
7824   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7825     return SDValue();
7826
7827   // Make a 64-bit buffer, and use it to build an FILD.
7828   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7829   if (SrcVT == MVT::i32) {
7830     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7831     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7832                                      getPointerTy(), StackSlot, WordOff);
7833     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7834                                   StackSlot, MachinePointerInfo(),
7835                                   false, false, 0);
7836     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7837                                   OffsetSlot, MachinePointerInfo(),
7838                                   false, false, 0);
7839     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7840     return Fild;
7841   }
7842
7843   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7844   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7845                                StackSlot, MachinePointerInfo(),
7846                                false, false, 0);
7847   // For i64 source, we need to add the appropriate power of 2 if the input
7848   // was negative.  This is the same as the optimization in
7849   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7850   // we must be careful to do the computation in x87 extended precision, not
7851   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7852   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7853   MachineMemOperand *MMO =
7854     DAG.getMachineFunction()
7855     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7856                           MachineMemOperand::MOLoad, 8, 8);
7857
7858   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7859   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7860   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7861                                          MVT::i64, MMO);
7862
7863   APInt FF(32, 0x5F800000ULL);
7864
7865   // Check whether the sign bit is set.
7866   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7867                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7868                                  ISD::SETLT);
7869
7870   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7871   SDValue FudgePtr = DAG.getConstantPool(
7872                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7873                                          getPointerTy());
7874
7875   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7876   SDValue Zero = DAG.getIntPtrConstant(0);
7877   SDValue Four = DAG.getIntPtrConstant(4);
7878   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7879                                Zero, Four);
7880   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7881
7882   // Load the value out, extending it from f32 to f80.
7883   // FIXME: Avoid the extend by constructing the right constant pool?
7884   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7885                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7886                                  MVT::f32, false, false, 4);
7887   // Extend everything to 80 bits to force it to be done on x87.
7888   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7889   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7890 }
7891
7892 std::pair<SDValue,SDValue> X86TargetLowering::
7893 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7894   DebugLoc DL = Op.getDebugLoc();
7895
7896   EVT DstTy = Op.getValueType();
7897
7898   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7899     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7900     DstTy = MVT::i64;
7901   }
7902
7903   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7904          DstTy.getSimpleVT() >= MVT::i16 &&
7905          "Unknown FP_TO_INT to lower!");
7906
7907   // These are really Legal.
7908   if (DstTy == MVT::i32 &&
7909       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7910     return std::make_pair(SDValue(), SDValue());
7911   if (Subtarget->is64Bit() &&
7912       DstTy == MVT::i64 &&
7913       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7914     return std::make_pair(SDValue(), SDValue());
7915
7916   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
7917   // stack slot, or into the FTOL runtime function.
7918   MachineFunction &MF = DAG.getMachineFunction();
7919   unsigned MemSize = DstTy.getSizeInBits()/8;
7920   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7921   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7922
7923   unsigned Opc;
7924   if (!IsSigned && isIntegerTypeFTOL(DstTy))
7925     Opc = X86ISD::WIN_FTOL;
7926   else
7927     switch (DstTy.getSimpleVT().SimpleTy) {
7928     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7929     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7930     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7931     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7932     }
7933
7934   SDValue Chain = DAG.getEntryNode();
7935   SDValue Value = Op.getOperand(0);
7936   EVT TheVT = Op.getOperand(0).getValueType();
7937   // FIXME This causes a redundant load/store if the SSE-class value is already
7938   // in memory, such as if it is on the callstack.
7939   if (isScalarFPTypeInSSEReg(TheVT)) {
7940     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7941     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7942                          MachinePointerInfo::getFixedStack(SSFI),
7943                          false, false, 0);
7944     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7945     SDValue Ops[] = {
7946       Chain, StackSlot, DAG.getValueType(TheVT)
7947     };
7948
7949     MachineMemOperand *MMO =
7950       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7951                               MachineMemOperand::MOLoad, MemSize, MemSize);
7952     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7953                                     DstTy, MMO);
7954     Chain = Value.getValue(1);
7955     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7956     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7957   }
7958
7959   MachineMemOperand *MMO =
7960     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7961                             MachineMemOperand::MOStore, MemSize, MemSize);
7962
7963   if (Opc != X86ISD::WIN_FTOL) {
7964     // Build the FP_TO_INT*_IN_MEM
7965     SDValue Ops[] = { Chain, Value, StackSlot };
7966     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7967                                            Ops, 3, DstTy, MMO);
7968     return std::make_pair(FIST, StackSlot);
7969   } else {
7970     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
7971       DAG.getVTList(MVT::Other, MVT::Glue),
7972       Chain, Value);
7973     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
7974       MVT::i32, ftol.getValue(1));
7975     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
7976       MVT::i32, eax.getValue(2));
7977     SDValue Ops[] = { eax, edx };
7978     SDValue pair = IsReplace
7979       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
7980       : DAG.getMergeValues(Ops, 2, DL);
7981     return std::make_pair(pair, SDValue());
7982   }
7983 }
7984
7985 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7986                                            SelectionDAG &DAG) const {
7987   if (Op.getValueType().isVector())
7988     return SDValue();
7989
7990   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
7991     /*IsSigned=*/ true, /*IsReplace=*/ false);
7992   SDValue FIST = Vals.first, StackSlot = Vals.second;
7993   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7994   if (FIST.getNode() == 0) return Op;
7995
7996   if (StackSlot.getNode())
7997     // Load the result.
7998     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7999                        FIST, StackSlot, MachinePointerInfo(),
8000                        false, false, false, 0);
8001
8002   // The node is the result.
8003   return FIST;
8004 }
8005
8006 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8007                                            SelectionDAG &DAG) const {
8008   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8009     /*IsSigned=*/ false, /*IsReplace=*/ false);
8010   SDValue FIST = Vals.first, StackSlot = Vals.second;
8011   assert(FIST.getNode() && "Unexpected failure");
8012
8013   if (StackSlot.getNode())
8014     // Load the result.
8015     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8016                        FIST, StackSlot, MachinePointerInfo(),
8017                        false, false, false, 0);
8018
8019   // The node is the result.
8020   return FIST;
8021 }
8022
8023 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8024                                      SelectionDAG &DAG) const {
8025   LLVMContext *Context = DAG.getContext();
8026   DebugLoc dl = Op.getDebugLoc();
8027   EVT VT = Op.getValueType();
8028   EVT EltVT = VT;
8029   if (VT.isVector())
8030     EltVT = VT.getVectorElementType();
8031   Constant *C;
8032   if (EltVT == MVT::f64) {
8033     C = ConstantVector::getSplat(2, 
8034                 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8035   } else {
8036     C = ConstantVector::getSplat(4,
8037                ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8038   }
8039   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8040   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8041                              MachinePointerInfo::getConstantPool(),
8042                              false, false, false, 16);
8043   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8044 }
8045
8046 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8047   LLVMContext *Context = DAG.getContext();
8048   DebugLoc dl = Op.getDebugLoc();
8049   EVT VT = Op.getValueType();
8050   EVT EltVT = VT;
8051   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8052   if (VT.isVector()) {
8053     EltVT = VT.getVectorElementType();
8054     NumElts = VT.getVectorNumElements();
8055   }
8056   Constant *C;
8057   if (EltVT == MVT::f64)
8058     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8059   else
8060     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8061   C = ConstantVector::getSplat(NumElts, C);
8062   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8063   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8064                              MachinePointerInfo::getConstantPool(),
8065                              false, false, false, 16);
8066   if (VT.isVector()) {
8067     MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
8068     return DAG.getNode(ISD::BITCAST, dl, VT,
8069                        DAG.getNode(ISD::XOR, dl, XORVT,
8070                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8071                                                Op.getOperand(0)),
8072                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8073   }
8074
8075   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8076 }
8077
8078 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8079   LLVMContext *Context = DAG.getContext();
8080   SDValue Op0 = Op.getOperand(0);
8081   SDValue Op1 = Op.getOperand(1);
8082   DebugLoc dl = Op.getDebugLoc();
8083   EVT VT = Op.getValueType();
8084   EVT SrcVT = Op1.getValueType();
8085
8086   // If second operand is smaller, extend it first.
8087   if (SrcVT.bitsLT(VT)) {
8088     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8089     SrcVT = VT;
8090   }
8091   // And if it is bigger, shrink it first.
8092   if (SrcVT.bitsGT(VT)) {
8093     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8094     SrcVT = VT;
8095   }
8096
8097   // At this point the operands and the result should have the same
8098   // type, and that won't be f80 since that is not custom lowered.
8099
8100   // First get the sign bit of second operand.
8101   SmallVector<Constant*,4> CV;
8102   if (SrcVT == MVT::f64) {
8103     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8104     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8105   } else {
8106     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8107     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8108     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8109     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8110   }
8111   Constant *C = ConstantVector::get(CV);
8112   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8113   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8114                               MachinePointerInfo::getConstantPool(),
8115                               false, false, false, 16);
8116   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8117
8118   // Shift sign bit right or left if the two operands have different types.
8119   if (SrcVT.bitsGT(VT)) {
8120     // Op0 is MVT::f32, Op1 is MVT::f64.
8121     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8122     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8123                           DAG.getConstant(32, MVT::i32));
8124     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8125     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8126                           DAG.getIntPtrConstant(0));
8127   }
8128
8129   // Clear first operand sign bit.
8130   CV.clear();
8131   if (VT == MVT::f64) {
8132     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8133     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8134   } else {
8135     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8136     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8137     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8138     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8139   }
8140   C = ConstantVector::get(CV);
8141   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8142   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8143                               MachinePointerInfo::getConstantPool(),
8144                               false, false, false, 16);
8145   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8146
8147   // Or the value with the sign bit.
8148   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8149 }
8150
8151 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8152   SDValue N0 = Op.getOperand(0);
8153   DebugLoc dl = Op.getDebugLoc();
8154   EVT VT = Op.getValueType();
8155
8156   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8157   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8158                                   DAG.getConstant(1, VT));
8159   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8160 }
8161
8162 /// Emit nodes that will be selected as "test Op0,Op0", or something
8163 /// equivalent.
8164 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8165                                     SelectionDAG &DAG) const {
8166   DebugLoc dl = Op.getDebugLoc();
8167
8168   // CF and OF aren't always set the way we want. Determine which
8169   // of these we need.
8170   bool NeedCF = false;
8171   bool NeedOF = false;
8172   switch (X86CC) {
8173   default: break;
8174   case X86::COND_A: case X86::COND_AE:
8175   case X86::COND_B: case X86::COND_BE:
8176     NeedCF = true;
8177     break;
8178   case X86::COND_G: case X86::COND_GE:
8179   case X86::COND_L: case X86::COND_LE:
8180   case X86::COND_O: case X86::COND_NO:
8181     NeedOF = true;
8182     break;
8183   }
8184
8185   // See if we can use the EFLAGS value from the operand instead of
8186   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8187   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8188   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8189     // Emit a CMP with 0, which is the TEST pattern.
8190     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8191                        DAG.getConstant(0, Op.getValueType()));
8192
8193   unsigned Opcode = 0;
8194   unsigned NumOperands = 0;
8195   switch (Op.getNode()->getOpcode()) {
8196   case ISD::ADD:
8197     // Due to an isel shortcoming, be conservative if this add is likely to be
8198     // selected as part of a load-modify-store instruction. When the root node
8199     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8200     // uses of other nodes in the match, such as the ADD in this case. This
8201     // leads to the ADD being left around and reselected, with the result being
8202     // two adds in the output.  Alas, even if none our users are stores, that
8203     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8204     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8205     // climbing the DAG back to the root, and it doesn't seem to be worth the
8206     // effort.
8207     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8208          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8209       if (UI->getOpcode() != ISD::CopyToReg &&
8210           UI->getOpcode() != ISD::SETCC &&
8211           UI->getOpcode() != ISD::STORE)
8212         goto default_case;
8213
8214     if (ConstantSDNode *C =
8215         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8216       // An add of one will be selected as an INC.
8217       if (C->getAPIntValue() == 1) {
8218         Opcode = X86ISD::INC;
8219         NumOperands = 1;
8220         break;
8221       }
8222
8223       // An add of negative one (subtract of one) will be selected as a DEC.
8224       if (C->getAPIntValue().isAllOnesValue()) {
8225         Opcode = X86ISD::DEC;
8226         NumOperands = 1;
8227         break;
8228       }
8229     }
8230
8231     // Otherwise use a regular EFLAGS-setting add.
8232     Opcode = X86ISD::ADD;
8233     NumOperands = 2;
8234     break;
8235   case ISD::AND: {
8236     // If the primary and result isn't used, don't bother using X86ISD::AND,
8237     // because a TEST instruction will be better.
8238     bool NonFlagUse = false;
8239     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8240            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8241       SDNode *User = *UI;
8242       unsigned UOpNo = UI.getOperandNo();
8243       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8244         // Look pass truncate.
8245         UOpNo = User->use_begin().getOperandNo();
8246         User = *User->use_begin();
8247       }
8248
8249       if (User->getOpcode() != ISD::BRCOND &&
8250           User->getOpcode() != ISD::SETCC &&
8251           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8252         NonFlagUse = true;
8253         break;
8254       }
8255     }
8256
8257     if (!NonFlagUse)
8258       break;
8259   }
8260     // FALL THROUGH
8261   case ISD::SUB:
8262   case ISD::OR:
8263   case ISD::XOR:
8264     // Due to the ISEL shortcoming noted above, be conservative if this op is
8265     // likely to be selected as part of a load-modify-store instruction.
8266     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8267            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8268       if (UI->getOpcode() == ISD::STORE)
8269         goto default_case;
8270
8271     // Otherwise use a regular EFLAGS-setting instruction.
8272     switch (Op.getNode()->getOpcode()) {
8273     default: llvm_unreachable("unexpected operator!");
8274     case ISD::SUB:
8275       // If the only use of SUB is EFLAGS, use CMP instead.
8276       if (Op.hasOneUse())
8277         Opcode = X86ISD::CMP;
8278       else
8279         Opcode = X86ISD::SUB;
8280       break;
8281     case ISD::OR:  Opcode = X86ISD::OR;  break;
8282     case ISD::XOR: Opcode = X86ISD::XOR; break;
8283     case ISD::AND: Opcode = X86ISD::AND; break;
8284     }
8285
8286     NumOperands = 2;
8287     break;
8288   case X86ISD::ADD:
8289   case X86ISD::SUB:
8290   case X86ISD::INC:
8291   case X86ISD::DEC:
8292   case X86ISD::OR:
8293   case X86ISD::XOR:
8294   case X86ISD::AND:
8295     return SDValue(Op.getNode(), 1);
8296   default:
8297   default_case:
8298     break;
8299   }
8300
8301   if (Opcode == 0)
8302     // Emit a CMP with 0, which is the TEST pattern.
8303     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8304                        DAG.getConstant(0, Op.getValueType()));
8305
8306   if (Opcode == X86ISD::CMP) {
8307     SDValue New = DAG.getNode(Opcode, dl, MVT::i32, Op.getOperand(0),
8308                               Op.getOperand(1));
8309     // We can't replace usage of SUB with CMP.
8310     // The SUB node will be removed later because there is no use of it.
8311     return SDValue(New.getNode(), 0);
8312   }
8313
8314   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8315   SmallVector<SDValue, 4> Ops;
8316   for (unsigned i = 0; i != NumOperands; ++i)
8317     Ops.push_back(Op.getOperand(i));
8318
8319   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8320   DAG.ReplaceAllUsesWith(Op, New);
8321   return SDValue(New.getNode(), 1);
8322 }
8323
8324 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8325 /// equivalent.
8326 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8327                                    SelectionDAG &DAG) const {
8328   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8329     if (C->getAPIntValue() == 0)
8330       return EmitTest(Op0, X86CC, DAG);
8331
8332   DebugLoc dl = Op0.getDebugLoc();
8333   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8334 }
8335
8336 /// Convert a comparison if required by the subtarget.
8337 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8338                                                  SelectionDAG &DAG) const {
8339   // If the subtarget does not support the FUCOMI instruction, floating-point
8340   // comparisons have to be converted.
8341   if (Subtarget->hasCMov() ||
8342       Cmp.getOpcode() != X86ISD::CMP ||
8343       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8344       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8345     return Cmp;
8346
8347   // The instruction selector will select an FUCOM instruction instead of
8348   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8349   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8350   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8351   DebugLoc dl = Cmp.getDebugLoc();
8352   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8353   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8354   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8355                             DAG.getConstant(8, MVT::i8));
8356   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8357   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8358 }
8359
8360 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8361 /// if it's possible.
8362 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8363                                      DebugLoc dl, SelectionDAG &DAG) const {
8364   SDValue Op0 = And.getOperand(0);
8365   SDValue Op1 = And.getOperand(1);
8366   if (Op0.getOpcode() == ISD::TRUNCATE)
8367     Op0 = Op0.getOperand(0);
8368   if (Op1.getOpcode() == ISD::TRUNCATE)
8369     Op1 = Op1.getOperand(0);
8370
8371   SDValue LHS, RHS;
8372   if (Op1.getOpcode() == ISD::SHL)
8373     std::swap(Op0, Op1);
8374   if (Op0.getOpcode() == ISD::SHL) {
8375     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8376       if (And00C->getZExtValue() == 1) {
8377         // If we looked past a truncate, check that it's only truncating away
8378         // known zeros.
8379         unsigned BitWidth = Op0.getValueSizeInBits();
8380         unsigned AndBitWidth = And.getValueSizeInBits();
8381         if (BitWidth > AndBitWidth) {
8382           APInt Zeros, Ones;
8383           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8384           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8385             return SDValue();
8386         }
8387         LHS = Op1;
8388         RHS = Op0.getOperand(1);
8389       }
8390   } else if (Op1.getOpcode() == ISD::Constant) {
8391     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8392     uint64_t AndRHSVal = AndRHS->getZExtValue();
8393     SDValue AndLHS = Op0;
8394
8395     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8396       LHS = AndLHS.getOperand(0);
8397       RHS = AndLHS.getOperand(1);
8398     }
8399
8400     // Use BT if the immediate can't be encoded in a TEST instruction.
8401     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8402       LHS = AndLHS;
8403       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8404     }
8405   }
8406
8407   if (LHS.getNode()) {
8408     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8409     // instruction.  Since the shift amount is in-range-or-undefined, we know
8410     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8411     // the encoding for the i16 version is larger than the i32 version.
8412     // Also promote i16 to i32 for performance / code size reason.
8413     if (LHS.getValueType() == MVT::i8 ||
8414         LHS.getValueType() == MVT::i16)
8415       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8416
8417     // If the operand types disagree, extend the shift amount to match.  Since
8418     // BT ignores high bits (like shifts) we can use anyextend.
8419     if (LHS.getValueType() != RHS.getValueType())
8420       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8421
8422     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8423     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8424     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8425                        DAG.getConstant(Cond, MVT::i8), BT);
8426   }
8427
8428   return SDValue();
8429 }
8430
8431 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8432
8433   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8434
8435   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8436   SDValue Op0 = Op.getOperand(0);
8437   SDValue Op1 = Op.getOperand(1);
8438   DebugLoc dl = Op.getDebugLoc();
8439   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8440
8441   // Optimize to BT if possible.
8442   // Lower (X & (1 << N)) == 0 to BT(X, N).
8443   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8444   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8445   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8446       Op1.getOpcode() == ISD::Constant &&
8447       cast<ConstantSDNode>(Op1)->isNullValue() &&
8448       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8449     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8450     if (NewSetCC.getNode())
8451       return NewSetCC;
8452   }
8453
8454   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8455   // these.
8456   if (Op1.getOpcode() == ISD::Constant &&
8457       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8458        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8459       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8460
8461     // If the input is a setcc, then reuse the input setcc or use a new one with
8462     // the inverted condition.
8463     if (Op0.getOpcode() == X86ISD::SETCC) {
8464       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8465       bool Invert = (CC == ISD::SETNE) ^
8466         cast<ConstantSDNode>(Op1)->isNullValue();
8467       if (!Invert) return Op0;
8468
8469       CCode = X86::GetOppositeBranchCondition(CCode);
8470       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8471                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8472     }
8473   }
8474
8475   bool isFP = Op1.getValueType().isFloatingPoint();
8476   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8477   if (X86CC == X86::COND_INVALID)
8478     return SDValue();
8479
8480   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8481   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8482   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8483                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8484 }
8485
8486 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8487 // ones, and then concatenate the result back.
8488 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8489   EVT VT = Op.getValueType();
8490
8491   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8492          "Unsupported value type for operation");
8493
8494   unsigned NumElems = VT.getVectorNumElements();
8495   DebugLoc dl = Op.getDebugLoc();
8496   SDValue CC = Op.getOperand(2);
8497
8498   // Extract the LHS vectors
8499   SDValue LHS = Op.getOperand(0);
8500   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8501   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8502
8503   // Extract the RHS vectors
8504   SDValue RHS = Op.getOperand(1);
8505   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8506   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8507
8508   // Issue the operation on the smaller types and concatenate the result back
8509   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8510   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8511   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8512                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8513                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8514 }
8515
8516
8517 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8518   SDValue Cond;
8519   SDValue Op0 = Op.getOperand(0);
8520   SDValue Op1 = Op.getOperand(1);
8521   SDValue CC = Op.getOperand(2);
8522   EVT VT = Op.getValueType();
8523   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8524   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8525   DebugLoc dl = Op.getDebugLoc();
8526
8527   if (isFP) {
8528     unsigned SSECC = 8;
8529     EVT EltVT = Op0.getValueType().getVectorElementType();
8530     assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8531
8532     bool Swap = false;
8533
8534     // SSE Condition code mapping:
8535     //  0 - EQ
8536     //  1 - LT
8537     //  2 - LE
8538     //  3 - UNORD
8539     //  4 - NEQ
8540     //  5 - NLT
8541     //  6 - NLE
8542     //  7 - ORD
8543     switch (SetCCOpcode) {
8544     default: break;
8545     case ISD::SETOEQ:
8546     case ISD::SETEQ:  SSECC = 0; break;
8547     case ISD::SETOGT:
8548     case ISD::SETGT: Swap = true; // Fallthrough
8549     case ISD::SETLT:
8550     case ISD::SETOLT: SSECC = 1; break;
8551     case ISD::SETOGE:
8552     case ISD::SETGE: Swap = true; // Fallthrough
8553     case ISD::SETLE:
8554     case ISD::SETOLE: SSECC = 2; break;
8555     case ISD::SETUO:  SSECC = 3; break;
8556     case ISD::SETUNE:
8557     case ISD::SETNE:  SSECC = 4; break;
8558     case ISD::SETULE: Swap = true;
8559     case ISD::SETUGE: SSECC = 5; break;
8560     case ISD::SETULT: Swap = true;
8561     case ISD::SETUGT: SSECC = 6; break;
8562     case ISD::SETO:   SSECC = 7; break;
8563     }
8564     if (Swap)
8565       std::swap(Op0, Op1);
8566
8567     // In the two special cases we can't handle, emit two comparisons.
8568     if (SSECC == 8) {
8569       if (SetCCOpcode == ISD::SETUEQ) {
8570         SDValue UNORD, EQ;
8571         UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8572                             DAG.getConstant(3, MVT::i8));
8573         EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8574                          DAG.getConstant(0, MVT::i8));
8575         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8576       }
8577       if (SetCCOpcode == ISD::SETONE) {
8578         SDValue ORD, NEQ;
8579         ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8580                           DAG.getConstant(7, MVT::i8));
8581         NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8582                           DAG.getConstant(4, MVT::i8));
8583         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8584       }
8585       llvm_unreachable("Illegal FP comparison");
8586     }
8587     // Handle all other FP comparisons here.
8588     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8589                        DAG.getConstant(SSECC, MVT::i8));
8590   }
8591
8592   // Break 256-bit integer vector compare into smaller ones.
8593   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8594     return Lower256IntVSETCC(Op, DAG);
8595
8596   // We are handling one of the integer comparisons here.  Since SSE only has
8597   // GT and EQ comparisons for integer, swapping operands and multiple
8598   // operations may be required for some comparisons.
8599   unsigned Opc = 0;
8600   bool Swap = false, Invert = false, FlipSigns = false;
8601
8602   switch (SetCCOpcode) {
8603   default: break;
8604   case ISD::SETNE:  Invert = true;
8605   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8606   case ISD::SETLT:  Swap = true;
8607   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8608   case ISD::SETGE:  Swap = true;
8609   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8610   case ISD::SETULT: Swap = true;
8611   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8612   case ISD::SETUGE: Swap = true;
8613   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8614   }
8615   if (Swap)
8616     std::swap(Op0, Op1);
8617
8618   // Check that the operation in question is available (most are plain SSE2,
8619   // but PCMPGTQ and PCMPEQQ have different requirements).
8620   if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8621     return SDValue();
8622   if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8623     return SDValue();
8624
8625   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8626   // bits of the inputs before performing those operations.
8627   if (FlipSigns) {
8628     EVT EltVT = VT.getVectorElementType();
8629     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8630                                       EltVT);
8631     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8632     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8633                                     SignBits.size());
8634     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8635     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8636   }
8637
8638   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8639
8640   // If the logical-not of the result is required, perform that now.
8641   if (Invert)
8642     Result = DAG.getNOT(dl, Result, VT);
8643
8644   return Result;
8645 }
8646
8647 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8648 static bool isX86LogicalCmp(SDValue Op) {
8649   unsigned Opc = Op.getNode()->getOpcode();
8650   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8651       Opc == X86ISD::SAHF)
8652     return true;
8653   if (Op.getResNo() == 1 &&
8654       (Opc == X86ISD::ADD ||
8655        Opc == X86ISD::SUB ||
8656        Opc == X86ISD::ADC ||
8657        Opc == X86ISD::SBB ||
8658        Opc == X86ISD::SMUL ||
8659        Opc == X86ISD::UMUL ||
8660        Opc == X86ISD::INC ||
8661        Opc == X86ISD::DEC ||
8662        Opc == X86ISD::OR ||
8663        Opc == X86ISD::XOR ||
8664        Opc == X86ISD::AND))
8665     return true;
8666
8667   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8668     return true;
8669
8670   return false;
8671 }
8672
8673 static bool isZero(SDValue V) {
8674   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8675   return C && C->isNullValue();
8676 }
8677
8678 static bool isAllOnes(SDValue V) {
8679   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8680   return C && C->isAllOnesValue();
8681 }
8682
8683 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8684   bool addTest = true;
8685   SDValue Cond  = Op.getOperand(0);
8686   SDValue Op1 = Op.getOperand(1);
8687   SDValue Op2 = Op.getOperand(2);
8688   DebugLoc DL = Op.getDebugLoc();
8689   SDValue CC;
8690
8691   if (Cond.getOpcode() == ISD::SETCC) {
8692     SDValue NewCond = LowerSETCC(Cond, DAG);
8693     if (NewCond.getNode())
8694       Cond = NewCond;
8695   }
8696
8697   // Handle the following cases related to max and min:
8698   // (a > b) ? (a-b) : 0
8699   // (a >= b) ? (a-b) : 0
8700   // (b < a) ? (a-b) : 0
8701   // (b <= a) ? (a-b) : 0
8702   // Comparison is removed to use EFLAGS from SUB.
8703   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2))
8704     if (Cond.getOpcode() == X86ISD::SETCC &&
8705         Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8706         (Op1.getOpcode() == ISD::SUB || Op1.getOpcode() == X86ISD::SUB) &&
8707         C->getAPIntValue() == 0) {
8708       SDValue Cmp = Cond.getOperand(1);
8709       unsigned CC = cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8710       if ((DAG.isEqualTo(Op1.getOperand(0), Cmp.getOperand(0)) &&
8711            DAG.isEqualTo(Op1.getOperand(1), Cmp.getOperand(1)) &&
8712            (CC == X86::COND_G || CC == X86::COND_GE ||
8713             CC == X86::COND_A || CC == X86::COND_AE)) ||
8714           (DAG.isEqualTo(Op1.getOperand(0), Cmp.getOperand(1)) &&
8715            DAG.isEqualTo(Op1.getOperand(1), Cmp.getOperand(0)) &&
8716            (CC == X86::COND_L || CC == X86::COND_LE ||
8717             CC == X86::COND_B || CC == X86::COND_BE))) {
8718
8719         if (Op1.getOpcode() == ISD::SUB) {
8720           SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i32);
8721           SDValue New = DAG.getNode(X86ISD::SUB, DL, VTs,
8722                                     Op1.getOperand(0), Op1.getOperand(1));
8723           DAG.ReplaceAllUsesWith(Op1, New);
8724           Op1 = New;
8725         }
8726
8727         SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8728         unsigned NewCC = (CC == X86::COND_G || CC == X86::COND_GE ||
8729                           CC == X86::COND_L ||
8730                           CC == X86::COND_LE) ? X86::COND_GE : X86::COND_AE;
8731         SDValue Ops[] = { Op2, Op1, DAG.getConstant(NewCC, MVT::i8),
8732                           SDValue(Op1.getNode(), 1) };
8733         return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8734       }
8735     }
8736
8737   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8738   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8739   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8740   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8741   if (Cond.getOpcode() == X86ISD::SETCC &&
8742       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8743       isZero(Cond.getOperand(1).getOperand(1))) {
8744     SDValue Cmp = Cond.getOperand(1);
8745
8746     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8747
8748     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8749         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8750       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8751
8752       SDValue CmpOp0 = Cmp.getOperand(0);
8753       // Apply further optimizations for special cases
8754       // (select (x != 0), -1, 0) -> neg & sbb
8755       // (select (x == 0), 0, -1) -> neg & sbb
8756       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8757         if (YC->isNullValue() && 
8758             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8759           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8760           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs, 
8761                                     DAG.getConstant(0, CmpOp0.getValueType()), 
8762                                     CmpOp0);
8763           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8764                                     DAG.getConstant(X86::COND_B, MVT::i8),
8765                                     SDValue(Neg.getNode(), 1));
8766           return Res;
8767         }
8768
8769       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8770                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8771       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8772
8773       SDValue Res =   // Res = 0 or -1.
8774         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8775                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8776
8777       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8778         Res = DAG.getNOT(DL, Res, Res.getValueType());
8779
8780       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8781       if (N2C == 0 || !N2C->isNullValue())
8782         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8783       return Res;
8784     }
8785   }
8786
8787   // Look past (and (setcc_carry (cmp ...)), 1).
8788   if (Cond.getOpcode() == ISD::AND &&
8789       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8790     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8791     if (C && C->getAPIntValue() == 1)
8792       Cond = Cond.getOperand(0);
8793   }
8794
8795   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8796   // setting operand in place of the X86ISD::SETCC.
8797   unsigned CondOpcode = Cond.getOpcode();
8798   if (CondOpcode == X86ISD::SETCC ||
8799       CondOpcode == X86ISD::SETCC_CARRY) {
8800     CC = Cond.getOperand(0);
8801
8802     SDValue Cmp = Cond.getOperand(1);
8803     unsigned Opc = Cmp.getOpcode();
8804     EVT VT = Op.getValueType();
8805
8806     bool IllegalFPCMov = false;
8807     if (VT.isFloatingPoint() && !VT.isVector() &&
8808         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8809       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8810
8811     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8812         Opc == X86ISD::BT) { // FIXME
8813       Cond = Cmp;
8814       addTest = false;
8815     }
8816   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8817              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8818              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8819               Cond.getOperand(0).getValueType() != MVT::i8)) {
8820     SDValue LHS = Cond.getOperand(0);
8821     SDValue RHS = Cond.getOperand(1);
8822     unsigned X86Opcode;
8823     unsigned X86Cond;
8824     SDVTList VTs;
8825     switch (CondOpcode) {
8826     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8827     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8828     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8829     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8830     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8831     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8832     default: llvm_unreachable("unexpected overflowing operator");
8833     }
8834     if (CondOpcode == ISD::UMULO)
8835       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8836                           MVT::i32);
8837     else
8838       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8839
8840     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8841
8842     if (CondOpcode == ISD::UMULO)
8843       Cond = X86Op.getValue(2);
8844     else
8845       Cond = X86Op.getValue(1);
8846
8847     CC = DAG.getConstant(X86Cond, MVT::i8);
8848     addTest = false;
8849   }
8850
8851   if (addTest) {
8852     // Look pass the truncate.
8853     if (Cond.getOpcode() == ISD::TRUNCATE)
8854       Cond = Cond.getOperand(0);
8855
8856     // We know the result of AND is compared against zero. Try to match
8857     // it to BT.
8858     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8859       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8860       if (NewSetCC.getNode()) {
8861         CC = NewSetCC.getOperand(0);
8862         Cond = NewSetCC.getOperand(1);
8863         addTest = false;
8864       }
8865     }
8866   }
8867
8868   if (addTest) {
8869     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8870     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8871   }
8872
8873   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8874   // a <  b ?  0 : -1 -> RES = setcc_carry
8875   // a >= b ? -1 :  0 -> RES = setcc_carry
8876   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8877   if (Cond.getOpcode() == X86ISD::CMP) {
8878     Cond = ConvertCmpIfNecessary(Cond, DAG);
8879     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8880
8881     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8882         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8883       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8884                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8885       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8886         return DAG.getNOT(DL, Res, Res.getValueType());
8887       return Res;
8888     }
8889   }
8890
8891   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8892   // condition is true.
8893   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8894   SDValue Ops[] = { Op2, Op1, CC, Cond };
8895   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8896 }
8897
8898 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8899 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8900 // from the AND / OR.
8901 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8902   Opc = Op.getOpcode();
8903   if (Opc != ISD::OR && Opc != ISD::AND)
8904     return false;
8905   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8906           Op.getOperand(0).hasOneUse() &&
8907           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8908           Op.getOperand(1).hasOneUse());
8909 }
8910
8911 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8912 // 1 and that the SETCC node has a single use.
8913 static bool isXor1OfSetCC(SDValue Op) {
8914   if (Op.getOpcode() != ISD::XOR)
8915     return false;
8916   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8917   if (N1C && N1C->getAPIntValue() == 1) {
8918     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8919       Op.getOperand(0).hasOneUse();
8920   }
8921   return false;
8922 }
8923
8924 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8925   bool addTest = true;
8926   SDValue Chain = Op.getOperand(0);
8927   SDValue Cond  = Op.getOperand(1);
8928   SDValue Dest  = Op.getOperand(2);
8929   DebugLoc dl = Op.getDebugLoc();
8930   SDValue CC;
8931   bool Inverted = false;
8932
8933   if (Cond.getOpcode() == ISD::SETCC) {
8934     // Check for setcc([su]{add,sub,mul}o == 0).
8935     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8936         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8937         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8938         Cond.getOperand(0).getResNo() == 1 &&
8939         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8940          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8941          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8942          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8943          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8944          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8945       Inverted = true;
8946       Cond = Cond.getOperand(0);
8947     } else {
8948       SDValue NewCond = LowerSETCC(Cond, DAG);
8949       if (NewCond.getNode())
8950         Cond = NewCond;
8951     }
8952   }
8953 #if 0
8954   // FIXME: LowerXALUO doesn't handle these!!
8955   else if (Cond.getOpcode() == X86ISD::ADD  ||
8956            Cond.getOpcode() == X86ISD::SUB  ||
8957            Cond.getOpcode() == X86ISD::SMUL ||
8958            Cond.getOpcode() == X86ISD::UMUL)
8959     Cond = LowerXALUO(Cond, DAG);
8960 #endif
8961
8962   // Look pass (and (setcc_carry (cmp ...)), 1).
8963   if (Cond.getOpcode() == ISD::AND &&
8964       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8965     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8966     if (C && C->getAPIntValue() == 1)
8967       Cond = Cond.getOperand(0);
8968   }
8969
8970   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8971   // setting operand in place of the X86ISD::SETCC.
8972   unsigned CondOpcode = Cond.getOpcode();
8973   if (CondOpcode == X86ISD::SETCC ||
8974       CondOpcode == X86ISD::SETCC_CARRY) {
8975     CC = Cond.getOperand(0);
8976
8977     SDValue Cmp = Cond.getOperand(1);
8978     unsigned Opc = Cmp.getOpcode();
8979     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8980     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8981       Cond = Cmp;
8982       addTest = false;
8983     } else {
8984       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8985       default: break;
8986       case X86::COND_O:
8987       case X86::COND_B:
8988         // These can only come from an arithmetic instruction with overflow,
8989         // e.g. SADDO, UADDO.
8990         Cond = Cond.getNode()->getOperand(1);
8991         addTest = false;
8992         break;
8993       }
8994     }
8995   }
8996   CondOpcode = Cond.getOpcode();
8997   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8998       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8999       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9000        Cond.getOperand(0).getValueType() != MVT::i8)) {
9001     SDValue LHS = Cond.getOperand(0);
9002     SDValue RHS = Cond.getOperand(1);
9003     unsigned X86Opcode;
9004     unsigned X86Cond;
9005     SDVTList VTs;
9006     switch (CondOpcode) {
9007     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9008     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9009     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9010     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9011     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9012     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9013     default: llvm_unreachable("unexpected overflowing operator");
9014     }
9015     if (Inverted)
9016       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9017     if (CondOpcode == ISD::UMULO)
9018       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9019                           MVT::i32);
9020     else
9021       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9022
9023     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9024
9025     if (CondOpcode == ISD::UMULO)
9026       Cond = X86Op.getValue(2);
9027     else
9028       Cond = X86Op.getValue(1);
9029
9030     CC = DAG.getConstant(X86Cond, MVT::i8);
9031     addTest = false;
9032   } else {
9033     unsigned CondOpc;
9034     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9035       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9036       if (CondOpc == ISD::OR) {
9037         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9038         // two branches instead of an explicit OR instruction with a
9039         // separate test.
9040         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9041             isX86LogicalCmp(Cmp)) {
9042           CC = Cond.getOperand(0).getOperand(0);
9043           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9044                               Chain, Dest, CC, Cmp);
9045           CC = Cond.getOperand(1).getOperand(0);
9046           Cond = Cmp;
9047           addTest = false;
9048         }
9049       } else { // ISD::AND
9050         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9051         // two branches instead of an explicit AND instruction with a
9052         // separate test. However, we only do this if this block doesn't
9053         // have a fall-through edge, because this requires an explicit
9054         // jmp when the condition is false.
9055         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9056             isX86LogicalCmp(Cmp) &&
9057             Op.getNode()->hasOneUse()) {
9058           X86::CondCode CCode =
9059             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9060           CCode = X86::GetOppositeBranchCondition(CCode);
9061           CC = DAG.getConstant(CCode, MVT::i8);
9062           SDNode *User = *Op.getNode()->use_begin();
9063           // Look for an unconditional branch following this conditional branch.
9064           // We need this because we need to reverse the successors in order
9065           // to implement FCMP_OEQ.
9066           if (User->getOpcode() == ISD::BR) {
9067             SDValue FalseBB = User->getOperand(1);
9068             SDNode *NewBR =
9069               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9070             assert(NewBR == User);
9071             (void)NewBR;
9072             Dest = FalseBB;
9073
9074             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9075                                 Chain, Dest, CC, Cmp);
9076             X86::CondCode CCode =
9077               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9078             CCode = X86::GetOppositeBranchCondition(CCode);
9079             CC = DAG.getConstant(CCode, MVT::i8);
9080             Cond = Cmp;
9081             addTest = false;
9082           }
9083         }
9084       }
9085     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9086       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9087       // It should be transformed during dag combiner except when the condition
9088       // is set by a arithmetics with overflow node.
9089       X86::CondCode CCode =
9090         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9091       CCode = X86::GetOppositeBranchCondition(CCode);
9092       CC = DAG.getConstant(CCode, MVT::i8);
9093       Cond = Cond.getOperand(0).getOperand(1);
9094       addTest = false;
9095     } else if (Cond.getOpcode() == ISD::SETCC &&
9096                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9097       // For FCMP_OEQ, we can emit
9098       // two branches instead of an explicit AND instruction with a
9099       // separate test. However, we only do this if this block doesn't
9100       // have a fall-through edge, because this requires an explicit
9101       // jmp when the condition is false.
9102       if (Op.getNode()->hasOneUse()) {
9103         SDNode *User = *Op.getNode()->use_begin();
9104         // Look for an unconditional branch following this conditional branch.
9105         // We need this because we need to reverse the successors in order
9106         // to implement FCMP_OEQ.
9107         if (User->getOpcode() == ISD::BR) {
9108           SDValue FalseBB = User->getOperand(1);
9109           SDNode *NewBR =
9110             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9111           assert(NewBR == User);
9112           (void)NewBR;
9113           Dest = FalseBB;
9114
9115           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9116                                     Cond.getOperand(0), Cond.getOperand(1));
9117           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9118           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9119           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9120                               Chain, Dest, CC, Cmp);
9121           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9122           Cond = Cmp;
9123           addTest = false;
9124         }
9125       }
9126     } else if (Cond.getOpcode() == ISD::SETCC &&
9127                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9128       // For FCMP_UNE, we can emit
9129       // two branches instead of an explicit AND instruction with a
9130       // separate test. However, we only do this if this block doesn't
9131       // have a fall-through edge, because this requires an explicit
9132       // jmp when the condition is false.
9133       if (Op.getNode()->hasOneUse()) {
9134         SDNode *User = *Op.getNode()->use_begin();
9135         // Look for an unconditional branch following this conditional branch.
9136         // We need this because we need to reverse the successors in order
9137         // to implement FCMP_UNE.
9138         if (User->getOpcode() == ISD::BR) {
9139           SDValue FalseBB = User->getOperand(1);
9140           SDNode *NewBR =
9141             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9142           assert(NewBR == User);
9143           (void)NewBR;
9144
9145           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9146                                     Cond.getOperand(0), Cond.getOperand(1));
9147           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9148           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9149           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9150                               Chain, Dest, CC, Cmp);
9151           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9152           Cond = Cmp;
9153           addTest = false;
9154           Dest = FalseBB;
9155         }
9156       }
9157     }
9158   }
9159
9160   if (addTest) {
9161     // Look pass the truncate.
9162     if (Cond.getOpcode() == ISD::TRUNCATE)
9163       Cond = Cond.getOperand(0);
9164
9165     // We know the result of AND is compared against zero. Try to match
9166     // it to BT.
9167     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9168       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9169       if (NewSetCC.getNode()) {
9170         CC = NewSetCC.getOperand(0);
9171         Cond = NewSetCC.getOperand(1);
9172         addTest = false;
9173       }
9174     }
9175   }
9176
9177   if (addTest) {
9178     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9179     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9180   }
9181   Cond = ConvertCmpIfNecessary(Cond, DAG);
9182   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9183                      Chain, Dest, CC, Cond);
9184 }
9185
9186
9187 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9188 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9189 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9190 // that the guard pages used by the OS virtual memory manager are allocated in
9191 // correct sequence.
9192 SDValue
9193 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9194                                            SelectionDAG &DAG) const {
9195   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9196           getTargetMachine().Options.EnableSegmentedStacks) &&
9197          "This should be used only on Windows targets or when segmented stacks "
9198          "are being used");
9199   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9200   DebugLoc dl = Op.getDebugLoc();
9201
9202   // Get the inputs.
9203   SDValue Chain = Op.getOperand(0);
9204   SDValue Size  = Op.getOperand(1);
9205   // FIXME: Ensure alignment here
9206
9207   bool Is64Bit = Subtarget->is64Bit();
9208   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9209
9210   if (getTargetMachine().Options.EnableSegmentedStacks) {
9211     MachineFunction &MF = DAG.getMachineFunction();
9212     MachineRegisterInfo &MRI = MF.getRegInfo();
9213
9214     if (Is64Bit) {
9215       // The 64 bit implementation of segmented stacks needs to clobber both r10
9216       // r11. This makes it impossible to use it along with nested parameters.
9217       const Function *F = MF.getFunction();
9218
9219       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9220            I != E; ++I)
9221         if (I->hasNestAttr())
9222           report_fatal_error("Cannot use segmented stacks with functions that "
9223                              "have nested arguments.");
9224     }
9225
9226     const TargetRegisterClass *AddrRegClass =
9227       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9228     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9229     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9230     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9231                                 DAG.getRegister(Vreg, SPTy));
9232     SDValue Ops1[2] = { Value, Chain };
9233     return DAG.getMergeValues(Ops1, 2, dl);
9234   } else {
9235     SDValue Flag;
9236     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9237
9238     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9239     Flag = Chain.getValue(1);
9240     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9241
9242     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9243     Flag = Chain.getValue(1);
9244
9245     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9246
9247     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9248     return DAG.getMergeValues(Ops1, 2, dl);
9249   }
9250 }
9251
9252 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9253   MachineFunction &MF = DAG.getMachineFunction();
9254   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9255
9256   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9257   DebugLoc DL = Op.getDebugLoc();
9258
9259   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9260     // vastart just stores the address of the VarArgsFrameIndex slot into the
9261     // memory location argument.
9262     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9263                                    getPointerTy());
9264     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9265                         MachinePointerInfo(SV), false, false, 0);
9266   }
9267
9268   // __va_list_tag:
9269   //   gp_offset         (0 - 6 * 8)
9270   //   fp_offset         (48 - 48 + 8 * 16)
9271   //   overflow_arg_area (point to parameters coming in memory).
9272   //   reg_save_area
9273   SmallVector<SDValue, 8> MemOps;
9274   SDValue FIN = Op.getOperand(1);
9275   // Store gp_offset
9276   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9277                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9278                                                MVT::i32),
9279                                FIN, MachinePointerInfo(SV), false, false, 0);
9280   MemOps.push_back(Store);
9281
9282   // Store fp_offset
9283   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9284                     FIN, DAG.getIntPtrConstant(4));
9285   Store = DAG.getStore(Op.getOperand(0), DL,
9286                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9287                                        MVT::i32),
9288                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9289   MemOps.push_back(Store);
9290
9291   // Store ptr to overflow_arg_area
9292   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9293                     FIN, DAG.getIntPtrConstant(4));
9294   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9295                                     getPointerTy());
9296   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9297                        MachinePointerInfo(SV, 8),
9298                        false, false, 0);
9299   MemOps.push_back(Store);
9300
9301   // Store ptr to reg_save_area.
9302   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9303                     FIN, DAG.getIntPtrConstant(8));
9304   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9305                                     getPointerTy());
9306   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9307                        MachinePointerInfo(SV, 16), false, false, 0);
9308   MemOps.push_back(Store);
9309   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9310                      &MemOps[0], MemOps.size());
9311 }
9312
9313 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9314   assert(Subtarget->is64Bit() &&
9315          "LowerVAARG only handles 64-bit va_arg!");
9316   assert((Subtarget->isTargetLinux() ||
9317           Subtarget->isTargetDarwin()) &&
9318           "Unhandled target in LowerVAARG");
9319   assert(Op.getNode()->getNumOperands() == 4);
9320   SDValue Chain = Op.getOperand(0);
9321   SDValue SrcPtr = Op.getOperand(1);
9322   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9323   unsigned Align = Op.getConstantOperandVal(3);
9324   DebugLoc dl = Op.getDebugLoc();
9325
9326   EVT ArgVT = Op.getNode()->getValueType(0);
9327   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9328   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9329   uint8_t ArgMode;
9330
9331   // Decide which area this value should be read from.
9332   // TODO: Implement the AMD64 ABI in its entirety. This simple
9333   // selection mechanism works only for the basic types.
9334   if (ArgVT == MVT::f80) {
9335     llvm_unreachable("va_arg for f80 not yet implemented");
9336   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9337     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9338   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9339     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9340   } else {
9341     llvm_unreachable("Unhandled argument type in LowerVAARG");
9342   }
9343
9344   if (ArgMode == 2) {
9345     // Sanity Check: Make sure using fp_offset makes sense.
9346     assert(!getTargetMachine().Options.UseSoftFloat &&
9347            !(DAG.getMachineFunction()
9348                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9349            Subtarget->hasSSE1());
9350   }
9351
9352   // Insert VAARG_64 node into the DAG
9353   // VAARG_64 returns two values: Variable Argument Address, Chain
9354   SmallVector<SDValue, 11> InstOps;
9355   InstOps.push_back(Chain);
9356   InstOps.push_back(SrcPtr);
9357   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9358   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9359   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9360   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9361   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9362                                           VTs, &InstOps[0], InstOps.size(),
9363                                           MVT::i64,
9364                                           MachinePointerInfo(SV),
9365                                           /*Align=*/0,
9366                                           /*Volatile=*/false,
9367                                           /*ReadMem=*/true,
9368                                           /*WriteMem=*/true);
9369   Chain = VAARG.getValue(1);
9370
9371   // Load the next argument and return it
9372   return DAG.getLoad(ArgVT, dl,
9373                      Chain,
9374                      VAARG,
9375                      MachinePointerInfo(),
9376                      false, false, false, 0);
9377 }
9378
9379 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9380   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9381   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9382   SDValue Chain = Op.getOperand(0);
9383   SDValue DstPtr = Op.getOperand(1);
9384   SDValue SrcPtr = Op.getOperand(2);
9385   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9386   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9387   DebugLoc DL = Op.getDebugLoc();
9388
9389   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9390                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9391                        false,
9392                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9393 }
9394
9395 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9396 // may or may not be a constant. Takes immediate version of shift as input.
9397 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9398                                    SDValue SrcOp, SDValue ShAmt,
9399                                    SelectionDAG &DAG) {
9400   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9401
9402   if (isa<ConstantSDNode>(ShAmt)) {
9403     switch (Opc) {
9404       default: llvm_unreachable("Unknown target vector shift node");
9405       case X86ISD::VSHLI:
9406       case X86ISD::VSRLI:
9407       case X86ISD::VSRAI:
9408         return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9409     }
9410   }
9411
9412   // Change opcode to non-immediate version
9413   switch (Opc) {
9414     default: llvm_unreachable("Unknown target vector shift node");
9415     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9416     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9417     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9418   }
9419
9420   // Need to build a vector containing shift amount
9421   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9422   SDValue ShOps[4];
9423   ShOps[0] = ShAmt;
9424   ShOps[1] = DAG.getConstant(0, MVT::i32);
9425   ShOps[2] = DAG.getUNDEF(MVT::i32);
9426   ShOps[3] = DAG.getUNDEF(MVT::i32);
9427   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9428   ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9429   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9430 }
9431
9432 SDValue
9433 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9434   DebugLoc dl = Op.getDebugLoc();
9435   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9436   switch (IntNo) {
9437   default: return SDValue();    // Don't custom lower most intrinsics.
9438   // Comparison intrinsics.
9439   case Intrinsic::x86_sse_comieq_ss:
9440   case Intrinsic::x86_sse_comilt_ss:
9441   case Intrinsic::x86_sse_comile_ss:
9442   case Intrinsic::x86_sse_comigt_ss:
9443   case Intrinsic::x86_sse_comige_ss:
9444   case Intrinsic::x86_sse_comineq_ss:
9445   case Intrinsic::x86_sse_ucomieq_ss:
9446   case Intrinsic::x86_sse_ucomilt_ss:
9447   case Intrinsic::x86_sse_ucomile_ss:
9448   case Intrinsic::x86_sse_ucomigt_ss:
9449   case Intrinsic::x86_sse_ucomige_ss:
9450   case Intrinsic::x86_sse_ucomineq_ss:
9451   case Intrinsic::x86_sse2_comieq_sd:
9452   case Intrinsic::x86_sse2_comilt_sd:
9453   case Intrinsic::x86_sse2_comile_sd:
9454   case Intrinsic::x86_sse2_comigt_sd:
9455   case Intrinsic::x86_sse2_comige_sd:
9456   case Intrinsic::x86_sse2_comineq_sd:
9457   case Intrinsic::x86_sse2_ucomieq_sd:
9458   case Intrinsic::x86_sse2_ucomilt_sd:
9459   case Intrinsic::x86_sse2_ucomile_sd:
9460   case Intrinsic::x86_sse2_ucomigt_sd:
9461   case Intrinsic::x86_sse2_ucomige_sd:
9462   case Intrinsic::x86_sse2_ucomineq_sd: {
9463     unsigned Opc = 0;
9464     ISD::CondCode CC = ISD::SETCC_INVALID;
9465     switch (IntNo) {
9466     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9467     case Intrinsic::x86_sse_comieq_ss:
9468     case Intrinsic::x86_sse2_comieq_sd:
9469       Opc = X86ISD::COMI;
9470       CC = ISD::SETEQ;
9471       break;
9472     case Intrinsic::x86_sse_comilt_ss:
9473     case Intrinsic::x86_sse2_comilt_sd:
9474       Opc = X86ISD::COMI;
9475       CC = ISD::SETLT;
9476       break;
9477     case Intrinsic::x86_sse_comile_ss:
9478     case Intrinsic::x86_sse2_comile_sd:
9479       Opc = X86ISD::COMI;
9480       CC = ISD::SETLE;
9481       break;
9482     case Intrinsic::x86_sse_comigt_ss:
9483     case Intrinsic::x86_sse2_comigt_sd:
9484       Opc = X86ISD::COMI;
9485       CC = ISD::SETGT;
9486       break;
9487     case Intrinsic::x86_sse_comige_ss:
9488     case Intrinsic::x86_sse2_comige_sd:
9489       Opc = X86ISD::COMI;
9490       CC = ISD::SETGE;
9491       break;
9492     case Intrinsic::x86_sse_comineq_ss:
9493     case Intrinsic::x86_sse2_comineq_sd:
9494       Opc = X86ISD::COMI;
9495       CC = ISD::SETNE;
9496       break;
9497     case Intrinsic::x86_sse_ucomieq_ss:
9498     case Intrinsic::x86_sse2_ucomieq_sd:
9499       Opc = X86ISD::UCOMI;
9500       CC = ISD::SETEQ;
9501       break;
9502     case Intrinsic::x86_sse_ucomilt_ss:
9503     case Intrinsic::x86_sse2_ucomilt_sd:
9504       Opc = X86ISD::UCOMI;
9505       CC = ISD::SETLT;
9506       break;
9507     case Intrinsic::x86_sse_ucomile_ss:
9508     case Intrinsic::x86_sse2_ucomile_sd:
9509       Opc = X86ISD::UCOMI;
9510       CC = ISD::SETLE;
9511       break;
9512     case Intrinsic::x86_sse_ucomigt_ss:
9513     case Intrinsic::x86_sse2_ucomigt_sd:
9514       Opc = X86ISD::UCOMI;
9515       CC = ISD::SETGT;
9516       break;
9517     case Intrinsic::x86_sse_ucomige_ss:
9518     case Intrinsic::x86_sse2_ucomige_sd:
9519       Opc = X86ISD::UCOMI;
9520       CC = ISD::SETGE;
9521       break;
9522     case Intrinsic::x86_sse_ucomineq_ss:
9523     case Intrinsic::x86_sse2_ucomineq_sd:
9524       Opc = X86ISD::UCOMI;
9525       CC = ISD::SETNE;
9526       break;
9527     }
9528
9529     SDValue LHS = Op.getOperand(1);
9530     SDValue RHS = Op.getOperand(2);
9531     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9532     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9533     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9534     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9535                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9536     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9537   }
9538   // XOP comparison intrinsics
9539   case Intrinsic::x86_xop_vpcomltb:
9540   case Intrinsic::x86_xop_vpcomltw:
9541   case Intrinsic::x86_xop_vpcomltd:
9542   case Intrinsic::x86_xop_vpcomltq:
9543   case Intrinsic::x86_xop_vpcomltub:
9544   case Intrinsic::x86_xop_vpcomltuw:
9545   case Intrinsic::x86_xop_vpcomltud:
9546   case Intrinsic::x86_xop_vpcomltuq:
9547   case Intrinsic::x86_xop_vpcomleb:
9548   case Intrinsic::x86_xop_vpcomlew:
9549   case Intrinsic::x86_xop_vpcomled:
9550   case Intrinsic::x86_xop_vpcomleq:
9551   case Intrinsic::x86_xop_vpcomleub:
9552   case Intrinsic::x86_xop_vpcomleuw:
9553   case Intrinsic::x86_xop_vpcomleud:
9554   case Intrinsic::x86_xop_vpcomleuq:
9555   case Intrinsic::x86_xop_vpcomgtb:
9556   case Intrinsic::x86_xop_vpcomgtw:
9557   case Intrinsic::x86_xop_vpcomgtd:
9558   case Intrinsic::x86_xop_vpcomgtq:
9559   case Intrinsic::x86_xop_vpcomgtub:
9560   case Intrinsic::x86_xop_vpcomgtuw:
9561   case Intrinsic::x86_xop_vpcomgtud:
9562   case Intrinsic::x86_xop_vpcomgtuq:
9563   case Intrinsic::x86_xop_vpcomgeb:
9564   case Intrinsic::x86_xop_vpcomgew:
9565   case Intrinsic::x86_xop_vpcomged:
9566   case Intrinsic::x86_xop_vpcomgeq:
9567   case Intrinsic::x86_xop_vpcomgeub:
9568   case Intrinsic::x86_xop_vpcomgeuw:
9569   case Intrinsic::x86_xop_vpcomgeud:
9570   case Intrinsic::x86_xop_vpcomgeuq:
9571   case Intrinsic::x86_xop_vpcomeqb:
9572   case Intrinsic::x86_xop_vpcomeqw:
9573   case Intrinsic::x86_xop_vpcomeqd:
9574   case Intrinsic::x86_xop_vpcomeqq:
9575   case Intrinsic::x86_xop_vpcomequb:
9576   case Intrinsic::x86_xop_vpcomequw:
9577   case Intrinsic::x86_xop_vpcomequd:
9578   case Intrinsic::x86_xop_vpcomequq:
9579   case Intrinsic::x86_xop_vpcomneb:
9580   case Intrinsic::x86_xop_vpcomnew:
9581   case Intrinsic::x86_xop_vpcomned:
9582   case Intrinsic::x86_xop_vpcomneq:
9583   case Intrinsic::x86_xop_vpcomneub:
9584   case Intrinsic::x86_xop_vpcomneuw:
9585   case Intrinsic::x86_xop_vpcomneud:
9586   case Intrinsic::x86_xop_vpcomneuq:
9587   case Intrinsic::x86_xop_vpcomfalseb:
9588   case Intrinsic::x86_xop_vpcomfalsew:
9589   case Intrinsic::x86_xop_vpcomfalsed:
9590   case Intrinsic::x86_xop_vpcomfalseq:
9591   case Intrinsic::x86_xop_vpcomfalseub:
9592   case Intrinsic::x86_xop_vpcomfalseuw:
9593   case Intrinsic::x86_xop_vpcomfalseud:
9594   case Intrinsic::x86_xop_vpcomfalseuq:
9595   case Intrinsic::x86_xop_vpcomtrueb:
9596   case Intrinsic::x86_xop_vpcomtruew:
9597   case Intrinsic::x86_xop_vpcomtrued:
9598   case Intrinsic::x86_xop_vpcomtrueq:
9599   case Intrinsic::x86_xop_vpcomtrueub:
9600   case Intrinsic::x86_xop_vpcomtrueuw:
9601   case Intrinsic::x86_xop_vpcomtrueud:
9602   case Intrinsic::x86_xop_vpcomtrueuq: {
9603     unsigned CC = 0;
9604     unsigned Opc = 0;
9605
9606     switch (IntNo) {
9607     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9608     case Intrinsic::x86_xop_vpcomltb:
9609     case Intrinsic::x86_xop_vpcomltw:
9610     case Intrinsic::x86_xop_vpcomltd:
9611     case Intrinsic::x86_xop_vpcomltq:
9612       CC = 0;
9613       Opc = X86ISD::VPCOM;
9614       break;
9615     case Intrinsic::x86_xop_vpcomltub:
9616     case Intrinsic::x86_xop_vpcomltuw:
9617     case Intrinsic::x86_xop_vpcomltud:
9618     case Intrinsic::x86_xop_vpcomltuq:
9619       CC = 0;
9620       Opc = X86ISD::VPCOMU;
9621       break;
9622     case Intrinsic::x86_xop_vpcomleb:
9623     case Intrinsic::x86_xop_vpcomlew:
9624     case Intrinsic::x86_xop_vpcomled:
9625     case Intrinsic::x86_xop_vpcomleq:
9626       CC = 1;
9627       Opc = X86ISD::VPCOM;
9628       break;
9629     case Intrinsic::x86_xop_vpcomleub:
9630     case Intrinsic::x86_xop_vpcomleuw:
9631     case Intrinsic::x86_xop_vpcomleud:
9632     case Intrinsic::x86_xop_vpcomleuq:
9633       CC = 1;
9634       Opc = X86ISD::VPCOMU;
9635       break;
9636     case Intrinsic::x86_xop_vpcomgtb:
9637     case Intrinsic::x86_xop_vpcomgtw:
9638     case Intrinsic::x86_xop_vpcomgtd:
9639     case Intrinsic::x86_xop_vpcomgtq:
9640       CC = 2;
9641       Opc = X86ISD::VPCOM;
9642       break;
9643     case Intrinsic::x86_xop_vpcomgtub:
9644     case Intrinsic::x86_xop_vpcomgtuw:
9645     case Intrinsic::x86_xop_vpcomgtud:
9646     case Intrinsic::x86_xop_vpcomgtuq:
9647       CC = 2;
9648       Opc = X86ISD::VPCOMU;
9649       break;
9650     case Intrinsic::x86_xop_vpcomgeb:
9651     case Intrinsic::x86_xop_vpcomgew:
9652     case Intrinsic::x86_xop_vpcomged:
9653     case Intrinsic::x86_xop_vpcomgeq:
9654       CC = 3;
9655       Opc = X86ISD::VPCOM;
9656       break;
9657     case Intrinsic::x86_xop_vpcomgeub:
9658     case Intrinsic::x86_xop_vpcomgeuw:
9659     case Intrinsic::x86_xop_vpcomgeud:
9660     case Intrinsic::x86_xop_vpcomgeuq:
9661       CC = 3;
9662       Opc = X86ISD::VPCOMU;
9663       break;
9664     case Intrinsic::x86_xop_vpcomeqb:
9665     case Intrinsic::x86_xop_vpcomeqw:
9666     case Intrinsic::x86_xop_vpcomeqd:
9667     case Intrinsic::x86_xop_vpcomeqq:
9668       CC = 4;
9669       Opc = X86ISD::VPCOM;
9670       break;
9671     case Intrinsic::x86_xop_vpcomequb:
9672     case Intrinsic::x86_xop_vpcomequw:
9673     case Intrinsic::x86_xop_vpcomequd:
9674     case Intrinsic::x86_xop_vpcomequq:
9675       CC = 4;
9676       Opc = X86ISD::VPCOMU;
9677       break;
9678     case Intrinsic::x86_xop_vpcomneb:
9679     case Intrinsic::x86_xop_vpcomnew:
9680     case Intrinsic::x86_xop_vpcomned:
9681     case Intrinsic::x86_xop_vpcomneq:
9682       CC = 5;
9683       Opc = X86ISD::VPCOM;
9684       break;
9685     case Intrinsic::x86_xop_vpcomneub:
9686     case Intrinsic::x86_xop_vpcomneuw:
9687     case Intrinsic::x86_xop_vpcomneud:
9688     case Intrinsic::x86_xop_vpcomneuq:
9689       CC = 5;
9690       Opc = X86ISD::VPCOMU;
9691       break;
9692     case Intrinsic::x86_xop_vpcomfalseb:
9693     case Intrinsic::x86_xop_vpcomfalsew:
9694     case Intrinsic::x86_xop_vpcomfalsed:
9695     case Intrinsic::x86_xop_vpcomfalseq:
9696       CC = 6;
9697       Opc = X86ISD::VPCOM;
9698       break;
9699     case Intrinsic::x86_xop_vpcomfalseub:
9700     case Intrinsic::x86_xop_vpcomfalseuw:
9701     case Intrinsic::x86_xop_vpcomfalseud:
9702     case Intrinsic::x86_xop_vpcomfalseuq:
9703       CC = 6;
9704       Opc = X86ISD::VPCOMU;
9705       break;
9706     case Intrinsic::x86_xop_vpcomtrueb:
9707     case Intrinsic::x86_xop_vpcomtruew:
9708     case Intrinsic::x86_xop_vpcomtrued:
9709     case Intrinsic::x86_xop_vpcomtrueq:
9710       CC = 7;
9711       Opc = X86ISD::VPCOM;
9712       break;
9713     case Intrinsic::x86_xop_vpcomtrueub:
9714     case Intrinsic::x86_xop_vpcomtrueuw:
9715     case Intrinsic::x86_xop_vpcomtrueud:
9716     case Intrinsic::x86_xop_vpcomtrueuq:
9717       CC = 7;
9718       Opc = X86ISD::VPCOMU;
9719       break;
9720     }
9721
9722     SDValue LHS = Op.getOperand(1);
9723     SDValue RHS = Op.getOperand(2);
9724     return DAG.getNode(Opc, dl, Op.getValueType(), LHS, RHS,
9725                        DAG.getConstant(CC, MVT::i8));
9726   }
9727
9728   // Arithmetic intrinsics.
9729   case Intrinsic::x86_sse2_pmulu_dq:
9730   case Intrinsic::x86_avx2_pmulu_dq:
9731     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9732                        Op.getOperand(1), Op.getOperand(2));
9733   case Intrinsic::x86_sse3_hadd_ps:
9734   case Intrinsic::x86_sse3_hadd_pd:
9735   case Intrinsic::x86_avx_hadd_ps_256:
9736   case Intrinsic::x86_avx_hadd_pd_256:
9737     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9738                        Op.getOperand(1), Op.getOperand(2));
9739   case Intrinsic::x86_sse3_hsub_ps:
9740   case Intrinsic::x86_sse3_hsub_pd:
9741   case Intrinsic::x86_avx_hsub_ps_256:
9742   case Intrinsic::x86_avx_hsub_pd_256:
9743     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9744                        Op.getOperand(1), Op.getOperand(2));
9745   case Intrinsic::x86_ssse3_phadd_w_128:
9746   case Intrinsic::x86_ssse3_phadd_d_128:
9747   case Intrinsic::x86_avx2_phadd_w:
9748   case Intrinsic::x86_avx2_phadd_d:
9749     return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9750                        Op.getOperand(1), Op.getOperand(2));
9751   case Intrinsic::x86_ssse3_phsub_w_128:
9752   case Intrinsic::x86_ssse3_phsub_d_128:
9753   case Intrinsic::x86_avx2_phsub_w:
9754   case Intrinsic::x86_avx2_phsub_d:
9755     return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9756                        Op.getOperand(1), Op.getOperand(2));
9757   case Intrinsic::x86_avx2_psllv_d:
9758   case Intrinsic::x86_avx2_psllv_q:
9759   case Intrinsic::x86_avx2_psllv_d_256:
9760   case Intrinsic::x86_avx2_psllv_q_256:
9761     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9762                       Op.getOperand(1), Op.getOperand(2));
9763   case Intrinsic::x86_avx2_psrlv_d:
9764   case Intrinsic::x86_avx2_psrlv_q:
9765   case Intrinsic::x86_avx2_psrlv_d_256:
9766   case Intrinsic::x86_avx2_psrlv_q_256:
9767     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9768                       Op.getOperand(1), Op.getOperand(2));
9769   case Intrinsic::x86_avx2_psrav_d:
9770   case Intrinsic::x86_avx2_psrav_d_256:
9771     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9772                       Op.getOperand(1), Op.getOperand(2));
9773   case Intrinsic::x86_ssse3_pshuf_b_128:
9774   case Intrinsic::x86_avx2_pshuf_b:
9775     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9776                        Op.getOperand(1), Op.getOperand(2));
9777   case Intrinsic::x86_ssse3_psign_b_128:
9778   case Intrinsic::x86_ssse3_psign_w_128:
9779   case Intrinsic::x86_ssse3_psign_d_128:
9780   case Intrinsic::x86_avx2_psign_b:
9781   case Intrinsic::x86_avx2_psign_w:
9782   case Intrinsic::x86_avx2_psign_d:
9783     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9784                        Op.getOperand(1), Op.getOperand(2));
9785   case Intrinsic::x86_sse41_insertps:
9786     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9787                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9788   case Intrinsic::x86_avx_vperm2f128_ps_256:
9789   case Intrinsic::x86_avx_vperm2f128_pd_256:
9790   case Intrinsic::x86_avx_vperm2f128_si_256:
9791   case Intrinsic::x86_avx2_vperm2i128:
9792     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9793                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9794   case Intrinsic::x86_avx2_permd:
9795   case Intrinsic::x86_avx2_permps:
9796     // Operands intentionally swapped. Mask is last operand to intrinsic,
9797     // but second operand for node/intruction.
9798     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9799                        Op.getOperand(2), Op.getOperand(1));
9800
9801   // ptest and testp intrinsics. The intrinsic these come from are designed to
9802   // return an integer value, not just an instruction so lower it to the ptest
9803   // or testp pattern and a setcc for the result.
9804   case Intrinsic::x86_sse41_ptestz:
9805   case Intrinsic::x86_sse41_ptestc:
9806   case Intrinsic::x86_sse41_ptestnzc:
9807   case Intrinsic::x86_avx_ptestz_256:
9808   case Intrinsic::x86_avx_ptestc_256:
9809   case Intrinsic::x86_avx_ptestnzc_256:
9810   case Intrinsic::x86_avx_vtestz_ps:
9811   case Intrinsic::x86_avx_vtestc_ps:
9812   case Intrinsic::x86_avx_vtestnzc_ps:
9813   case Intrinsic::x86_avx_vtestz_pd:
9814   case Intrinsic::x86_avx_vtestc_pd:
9815   case Intrinsic::x86_avx_vtestnzc_pd:
9816   case Intrinsic::x86_avx_vtestz_ps_256:
9817   case Intrinsic::x86_avx_vtestc_ps_256:
9818   case Intrinsic::x86_avx_vtestnzc_ps_256:
9819   case Intrinsic::x86_avx_vtestz_pd_256:
9820   case Intrinsic::x86_avx_vtestc_pd_256:
9821   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9822     bool IsTestPacked = false;
9823     unsigned X86CC = 0;
9824     switch (IntNo) {
9825     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9826     case Intrinsic::x86_avx_vtestz_ps:
9827     case Intrinsic::x86_avx_vtestz_pd:
9828     case Intrinsic::x86_avx_vtestz_ps_256:
9829     case Intrinsic::x86_avx_vtestz_pd_256:
9830       IsTestPacked = true; // Fallthrough
9831     case Intrinsic::x86_sse41_ptestz:
9832     case Intrinsic::x86_avx_ptestz_256:
9833       // ZF = 1
9834       X86CC = X86::COND_E;
9835       break;
9836     case Intrinsic::x86_avx_vtestc_ps:
9837     case Intrinsic::x86_avx_vtestc_pd:
9838     case Intrinsic::x86_avx_vtestc_ps_256:
9839     case Intrinsic::x86_avx_vtestc_pd_256:
9840       IsTestPacked = true; // Fallthrough
9841     case Intrinsic::x86_sse41_ptestc:
9842     case Intrinsic::x86_avx_ptestc_256:
9843       // CF = 1
9844       X86CC = X86::COND_B;
9845       break;
9846     case Intrinsic::x86_avx_vtestnzc_ps:
9847     case Intrinsic::x86_avx_vtestnzc_pd:
9848     case Intrinsic::x86_avx_vtestnzc_ps_256:
9849     case Intrinsic::x86_avx_vtestnzc_pd_256:
9850       IsTestPacked = true; // Fallthrough
9851     case Intrinsic::x86_sse41_ptestnzc:
9852     case Intrinsic::x86_avx_ptestnzc_256:
9853       // ZF and CF = 0
9854       X86CC = X86::COND_A;
9855       break;
9856     }
9857
9858     SDValue LHS = Op.getOperand(1);
9859     SDValue RHS = Op.getOperand(2);
9860     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9861     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9862     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9863     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9864     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9865   }
9866
9867   // SSE/AVX shift intrinsics
9868   case Intrinsic::x86_sse2_psll_w:
9869   case Intrinsic::x86_sse2_psll_d:
9870   case Intrinsic::x86_sse2_psll_q:
9871   case Intrinsic::x86_avx2_psll_w:
9872   case Intrinsic::x86_avx2_psll_d:
9873   case Intrinsic::x86_avx2_psll_q:
9874     return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9875                        Op.getOperand(1), Op.getOperand(2));
9876   case Intrinsic::x86_sse2_psrl_w:
9877   case Intrinsic::x86_sse2_psrl_d:
9878   case Intrinsic::x86_sse2_psrl_q:
9879   case Intrinsic::x86_avx2_psrl_w:
9880   case Intrinsic::x86_avx2_psrl_d:
9881   case Intrinsic::x86_avx2_psrl_q:
9882     return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9883                        Op.getOperand(1), Op.getOperand(2));
9884   case Intrinsic::x86_sse2_psra_w:
9885   case Intrinsic::x86_sse2_psra_d:
9886   case Intrinsic::x86_avx2_psra_w:
9887   case Intrinsic::x86_avx2_psra_d:
9888     return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9889                        Op.getOperand(1), Op.getOperand(2));
9890   case Intrinsic::x86_sse2_pslli_w:
9891   case Intrinsic::x86_sse2_pslli_d:
9892   case Intrinsic::x86_sse2_pslli_q:
9893   case Intrinsic::x86_avx2_pslli_w:
9894   case Intrinsic::x86_avx2_pslli_d:
9895   case Intrinsic::x86_avx2_pslli_q:
9896     return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9897                                Op.getOperand(1), Op.getOperand(2), DAG);
9898   case Intrinsic::x86_sse2_psrli_w:
9899   case Intrinsic::x86_sse2_psrli_d:
9900   case Intrinsic::x86_sse2_psrli_q:
9901   case Intrinsic::x86_avx2_psrli_w:
9902   case Intrinsic::x86_avx2_psrli_d:
9903   case Intrinsic::x86_avx2_psrli_q:
9904     return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9905                                Op.getOperand(1), Op.getOperand(2), DAG);
9906   case Intrinsic::x86_sse2_psrai_w:
9907   case Intrinsic::x86_sse2_psrai_d:
9908   case Intrinsic::x86_avx2_psrai_w:
9909   case Intrinsic::x86_avx2_psrai_d:
9910     return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9911                                Op.getOperand(1), Op.getOperand(2), DAG);
9912   // Fix vector shift instructions where the last operand is a non-immediate
9913   // i32 value.
9914   case Intrinsic::x86_mmx_pslli_w:
9915   case Intrinsic::x86_mmx_pslli_d:
9916   case Intrinsic::x86_mmx_pslli_q:
9917   case Intrinsic::x86_mmx_psrli_w:
9918   case Intrinsic::x86_mmx_psrli_d:
9919   case Intrinsic::x86_mmx_psrli_q:
9920   case Intrinsic::x86_mmx_psrai_w:
9921   case Intrinsic::x86_mmx_psrai_d: {
9922     SDValue ShAmt = Op.getOperand(2);
9923     if (isa<ConstantSDNode>(ShAmt))
9924       return SDValue();
9925
9926     unsigned NewIntNo = 0;
9927     switch (IntNo) {
9928     case Intrinsic::x86_mmx_pslli_w:
9929       NewIntNo = Intrinsic::x86_mmx_psll_w;
9930       break;
9931     case Intrinsic::x86_mmx_pslli_d:
9932       NewIntNo = Intrinsic::x86_mmx_psll_d;
9933       break;
9934     case Intrinsic::x86_mmx_pslli_q:
9935       NewIntNo = Intrinsic::x86_mmx_psll_q;
9936       break;
9937     case Intrinsic::x86_mmx_psrli_w:
9938       NewIntNo = Intrinsic::x86_mmx_psrl_w;
9939       break;
9940     case Intrinsic::x86_mmx_psrli_d:
9941       NewIntNo = Intrinsic::x86_mmx_psrl_d;
9942       break;
9943     case Intrinsic::x86_mmx_psrli_q:
9944       NewIntNo = Intrinsic::x86_mmx_psrl_q;
9945       break;
9946     case Intrinsic::x86_mmx_psrai_w:
9947       NewIntNo = Intrinsic::x86_mmx_psra_w;
9948       break;
9949     case Intrinsic::x86_mmx_psrai_d:
9950       NewIntNo = Intrinsic::x86_mmx_psra_d;
9951       break;
9952     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9953     }
9954
9955     // The vector shift intrinsics with scalars uses 32b shift amounts but
9956     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9957     // to be zero.
9958     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9959                          DAG.getConstant(0, MVT::i32));
9960 // FIXME this must be lowered to get rid of the invalid type.
9961
9962     EVT VT = Op.getValueType();
9963     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9964     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9965                        DAG.getConstant(NewIntNo, MVT::i32),
9966                        Op.getOperand(1), ShAmt);
9967   }
9968   }
9969 }
9970
9971 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9972                                            SelectionDAG &DAG) const {
9973   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9974   MFI->setReturnAddressIsTaken(true);
9975
9976   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9977   DebugLoc dl = Op.getDebugLoc();
9978
9979   if (Depth > 0) {
9980     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9981     SDValue Offset =
9982       DAG.getConstant(TD->getPointerSize(),
9983                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9984     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9985                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9986                                    FrameAddr, Offset),
9987                        MachinePointerInfo(), false, false, false, 0);
9988   }
9989
9990   // Just load the return address.
9991   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9992   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9993                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9994 }
9995
9996 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9997   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9998   MFI->setFrameAddressIsTaken(true);
9999
10000   EVT VT = Op.getValueType();
10001   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10002   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10003   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10004   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10005   while (Depth--)
10006     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10007                             MachinePointerInfo(),
10008                             false, false, false, 0);
10009   return FrameAddr;
10010 }
10011
10012 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10013                                                      SelectionDAG &DAG) const {
10014   return DAG.getIntPtrConstant(2*TD->getPointerSize());
10015 }
10016
10017 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10018   MachineFunction &MF = DAG.getMachineFunction();
10019   SDValue Chain     = Op.getOperand(0);
10020   SDValue Offset    = Op.getOperand(1);
10021   SDValue Handler   = Op.getOperand(2);
10022   DebugLoc dl       = Op.getDebugLoc();
10023
10024   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10025                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10026                                      getPointerTy());
10027   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10028
10029   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10030                                   DAG.getIntPtrConstant(TD->getPointerSize()));
10031   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10032   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10033                        false, false, 0);
10034   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10035   MF.getRegInfo().addLiveOut(StoreAddrReg);
10036
10037   return DAG.getNode(X86ISD::EH_RETURN, dl,
10038                      MVT::Other,
10039                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10040 }
10041
10042 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
10043                                                   SelectionDAG &DAG) const {
10044   return Op.getOperand(0);
10045 }
10046
10047 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10048                                                 SelectionDAG &DAG) const {
10049   SDValue Root = Op.getOperand(0);
10050   SDValue Trmp = Op.getOperand(1); // trampoline
10051   SDValue FPtr = Op.getOperand(2); // nested function
10052   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10053   DebugLoc dl  = Op.getDebugLoc();
10054
10055   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10056
10057   if (Subtarget->is64Bit()) {
10058     SDValue OutChains[6];
10059
10060     // Large code-model.
10061     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10062     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10063
10064     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10065     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10066
10067     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10068
10069     // Load the pointer to the nested function into R11.
10070     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10071     SDValue Addr = Trmp;
10072     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10073                                 Addr, MachinePointerInfo(TrmpAddr),
10074                                 false, false, 0);
10075
10076     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10077                        DAG.getConstant(2, MVT::i64));
10078     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10079                                 MachinePointerInfo(TrmpAddr, 2),
10080                                 false, false, 2);
10081
10082     // Load the 'nest' parameter value into R10.
10083     // R10 is specified in X86CallingConv.td
10084     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10085     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10086                        DAG.getConstant(10, MVT::i64));
10087     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10088                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10089                                 false, false, 0);
10090
10091     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10092                        DAG.getConstant(12, MVT::i64));
10093     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10094                                 MachinePointerInfo(TrmpAddr, 12),
10095                                 false, false, 2);
10096
10097     // Jump to the nested function.
10098     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10099     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10100                        DAG.getConstant(20, MVT::i64));
10101     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10102                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10103                                 false, false, 0);
10104
10105     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10106     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10107                        DAG.getConstant(22, MVT::i64));
10108     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10109                                 MachinePointerInfo(TrmpAddr, 22),
10110                                 false, false, 0);
10111
10112     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10113   } else {
10114     const Function *Func =
10115       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10116     CallingConv::ID CC = Func->getCallingConv();
10117     unsigned NestReg;
10118
10119     switch (CC) {
10120     default:
10121       llvm_unreachable("Unsupported calling convention");
10122     case CallingConv::C:
10123     case CallingConv::X86_StdCall: {
10124       // Pass 'nest' parameter in ECX.
10125       // Must be kept in sync with X86CallingConv.td
10126       NestReg = X86::ECX;
10127
10128       // Check that ECX wasn't needed by an 'inreg' parameter.
10129       FunctionType *FTy = Func->getFunctionType();
10130       const AttrListPtr &Attrs = Func->getAttributes();
10131
10132       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10133         unsigned InRegCount = 0;
10134         unsigned Idx = 1;
10135
10136         for (FunctionType::param_iterator I = FTy->param_begin(),
10137              E = FTy->param_end(); I != E; ++I, ++Idx)
10138           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10139             // FIXME: should only count parameters that are lowered to integers.
10140             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10141
10142         if (InRegCount > 2) {
10143           report_fatal_error("Nest register in use - reduce number of inreg"
10144                              " parameters!");
10145         }
10146       }
10147       break;
10148     }
10149     case CallingConv::X86_FastCall:
10150     case CallingConv::X86_ThisCall:
10151     case CallingConv::Fast:
10152       // Pass 'nest' parameter in EAX.
10153       // Must be kept in sync with X86CallingConv.td
10154       NestReg = X86::EAX;
10155       break;
10156     }
10157
10158     SDValue OutChains[4];
10159     SDValue Addr, Disp;
10160
10161     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10162                        DAG.getConstant(10, MVT::i32));
10163     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10164
10165     // This is storing the opcode for MOV32ri.
10166     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10167     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10168     OutChains[0] = DAG.getStore(Root, dl,
10169                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10170                                 Trmp, MachinePointerInfo(TrmpAddr),
10171                                 false, false, 0);
10172
10173     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10174                        DAG.getConstant(1, MVT::i32));
10175     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10176                                 MachinePointerInfo(TrmpAddr, 1),
10177                                 false, false, 1);
10178
10179     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10180     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10181                        DAG.getConstant(5, MVT::i32));
10182     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10183                                 MachinePointerInfo(TrmpAddr, 5),
10184                                 false, false, 1);
10185
10186     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10187                        DAG.getConstant(6, MVT::i32));
10188     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10189                                 MachinePointerInfo(TrmpAddr, 6),
10190                                 false, false, 1);
10191
10192     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10193   }
10194 }
10195
10196 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10197                                             SelectionDAG &DAG) const {
10198   /*
10199    The rounding mode is in bits 11:10 of FPSR, and has the following
10200    settings:
10201      00 Round to nearest
10202      01 Round to -inf
10203      10 Round to +inf
10204      11 Round to 0
10205
10206   FLT_ROUNDS, on the other hand, expects the following:
10207     -1 Undefined
10208      0 Round to 0
10209      1 Round to nearest
10210      2 Round to +inf
10211      3 Round to -inf
10212
10213   To perform the conversion, we do:
10214     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10215   */
10216
10217   MachineFunction &MF = DAG.getMachineFunction();
10218   const TargetMachine &TM = MF.getTarget();
10219   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10220   unsigned StackAlignment = TFI.getStackAlignment();
10221   EVT VT = Op.getValueType();
10222   DebugLoc DL = Op.getDebugLoc();
10223
10224   // Save FP Control Word to stack slot
10225   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10226   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10227
10228
10229   MachineMemOperand *MMO =
10230    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10231                            MachineMemOperand::MOStore, 2, 2);
10232
10233   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10234   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10235                                           DAG.getVTList(MVT::Other),
10236                                           Ops, 2, MVT::i16, MMO);
10237
10238   // Load FP Control Word from stack slot
10239   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10240                             MachinePointerInfo(), false, false, false, 0);
10241
10242   // Transform as necessary
10243   SDValue CWD1 =
10244     DAG.getNode(ISD::SRL, DL, MVT::i16,
10245                 DAG.getNode(ISD::AND, DL, MVT::i16,
10246                             CWD, DAG.getConstant(0x800, MVT::i16)),
10247                 DAG.getConstant(11, MVT::i8));
10248   SDValue CWD2 =
10249     DAG.getNode(ISD::SRL, DL, MVT::i16,
10250                 DAG.getNode(ISD::AND, DL, MVT::i16,
10251                             CWD, DAG.getConstant(0x400, MVT::i16)),
10252                 DAG.getConstant(9, MVT::i8));
10253
10254   SDValue RetVal =
10255     DAG.getNode(ISD::AND, DL, MVT::i16,
10256                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10257                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10258                             DAG.getConstant(1, MVT::i16)),
10259                 DAG.getConstant(3, MVT::i16));
10260
10261
10262   return DAG.getNode((VT.getSizeInBits() < 16 ?
10263                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10264 }
10265
10266 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10267   EVT VT = Op.getValueType();
10268   EVT OpVT = VT;
10269   unsigned NumBits = VT.getSizeInBits();
10270   DebugLoc dl = Op.getDebugLoc();
10271
10272   Op = Op.getOperand(0);
10273   if (VT == MVT::i8) {
10274     // Zero extend to i32 since there is not an i8 bsr.
10275     OpVT = MVT::i32;
10276     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10277   }
10278
10279   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10280   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10281   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10282
10283   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10284   SDValue Ops[] = {
10285     Op,
10286     DAG.getConstant(NumBits+NumBits-1, OpVT),
10287     DAG.getConstant(X86::COND_E, MVT::i8),
10288     Op.getValue(1)
10289   };
10290   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10291
10292   // Finally xor with NumBits-1.
10293   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10294
10295   if (VT == MVT::i8)
10296     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10297   return Op;
10298 }
10299
10300 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10301                                                 SelectionDAG &DAG) const {
10302   EVT VT = Op.getValueType();
10303   EVT OpVT = VT;
10304   unsigned NumBits = VT.getSizeInBits();
10305   DebugLoc dl = Op.getDebugLoc();
10306
10307   Op = Op.getOperand(0);
10308   if (VT == MVT::i8) {
10309     // Zero extend to i32 since there is not an i8 bsr.
10310     OpVT = MVT::i32;
10311     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10312   }
10313
10314   // Issue a bsr (scan bits in reverse).
10315   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10316   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10317
10318   // And xor with NumBits-1.
10319   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10320
10321   if (VT == MVT::i8)
10322     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10323   return Op;
10324 }
10325
10326 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10327   EVT VT = Op.getValueType();
10328   unsigned NumBits = VT.getSizeInBits();
10329   DebugLoc dl = Op.getDebugLoc();
10330   Op = Op.getOperand(0);
10331
10332   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10333   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10334   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10335
10336   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10337   SDValue Ops[] = {
10338     Op,
10339     DAG.getConstant(NumBits, VT),
10340     DAG.getConstant(X86::COND_E, MVT::i8),
10341     Op.getValue(1)
10342   };
10343   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10344 }
10345
10346 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10347 // ones, and then concatenate the result back.
10348 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10349   EVT VT = Op.getValueType();
10350
10351   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10352          "Unsupported value type for operation");
10353
10354   unsigned NumElems = VT.getVectorNumElements();
10355   DebugLoc dl = Op.getDebugLoc();
10356
10357   // Extract the LHS vectors
10358   SDValue LHS = Op.getOperand(0);
10359   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10360   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10361
10362   // Extract the RHS vectors
10363   SDValue RHS = Op.getOperand(1);
10364   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10365   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10366
10367   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10368   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10369
10370   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10371                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10372                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10373 }
10374
10375 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10376   assert(Op.getValueType().getSizeInBits() == 256 &&
10377          Op.getValueType().isInteger() &&
10378          "Only handle AVX 256-bit vector integer operation");
10379   return Lower256IntArith(Op, DAG);
10380 }
10381
10382 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10383   assert(Op.getValueType().getSizeInBits() == 256 &&
10384          Op.getValueType().isInteger() &&
10385          "Only handle AVX 256-bit vector integer operation");
10386   return Lower256IntArith(Op, DAG);
10387 }
10388
10389 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10390   EVT VT = Op.getValueType();
10391
10392   // Decompose 256-bit ops into smaller 128-bit ops.
10393   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10394     return Lower256IntArith(Op, DAG);
10395
10396   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10397          "Only know how to lower V2I64/V4I64 multiply");
10398
10399   DebugLoc dl = Op.getDebugLoc();
10400
10401   //  Ahi = psrlqi(a, 32);
10402   //  Bhi = psrlqi(b, 32);
10403   //
10404   //  AloBlo = pmuludq(a, b);
10405   //  AloBhi = pmuludq(a, Bhi);
10406   //  AhiBlo = pmuludq(Ahi, b);
10407
10408   //  AloBhi = psllqi(AloBhi, 32);
10409   //  AhiBlo = psllqi(AhiBlo, 32);
10410   //  return AloBlo + AloBhi + AhiBlo;
10411
10412   SDValue A = Op.getOperand(0);
10413   SDValue B = Op.getOperand(1);
10414
10415   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10416
10417   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10418   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10419
10420   // Bit cast to 32-bit vectors for MULUDQ
10421   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10422   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10423   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10424   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10425   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10426
10427   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10428   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10429   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10430
10431   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10432   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10433
10434   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10435   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10436 }
10437
10438 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10439
10440   EVT VT = Op.getValueType();
10441   DebugLoc dl = Op.getDebugLoc();
10442   SDValue R = Op.getOperand(0);
10443   SDValue Amt = Op.getOperand(1);
10444   LLVMContext *Context = DAG.getContext();
10445
10446   if (!Subtarget->hasSSE2())
10447     return SDValue();
10448
10449   // Optimize shl/srl/sra with constant shift amount.
10450   if (isSplatVector(Amt.getNode())) {
10451     SDValue SclrAmt = Amt->getOperand(0);
10452     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10453       uint64_t ShiftAmt = C->getZExtValue();
10454
10455       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10456           (Subtarget->hasAVX2() &&
10457            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10458         if (Op.getOpcode() == ISD::SHL)
10459           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10460                              DAG.getConstant(ShiftAmt, MVT::i32));
10461         if (Op.getOpcode() == ISD::SRL)
10462           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10463                              DAG.getConstant(ShiftAmt, MVT::i32));
10464         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10465           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10466                              DAG.getConstant(ShiftAmt, MVT::i32));
10467       }
10468
10469       if (VT == MVT::v16i8) {
10470         if (Op.getOpcode() == ISD::SHL) {
10471           // Make a large shift.
10472           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10473                                     DAG.getConstant(ShiftAmt, MVT::i32));
10474           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10475           // Zero out the rightmost bits.
10476           SmallVector<SDValue, 16> V(16,
10477                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10478                                                      MVT::i8));
10479           return DAG.getNode(ISD::AND, dl, VT, SHL,
10480                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10481         }
10482         if (Op.getOpcode() == ISD::SRL) {
10483           // Make a large shift.
10484           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10485                                     DAG.getConstant(ShiftAmt, MVT::i32));
10486           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10487           // Zero out the leftmost bits.
10488           SmallVector<SDValue, 16> V(16,
10489                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10490                                                      MVT::i8));
10491           return DAG.getNode(ISD::AND, dl, VT, SRL,
10492                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10493         }
10494         if (Op.getOpcode() == ISD::SRA) {
10495           if (ShiftAmt == 7) {
10496             // R s>> 7  ===  R s< 0
10497             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10498             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10499           }
10500
10501           // R s>> a === ((R u>> a) ^ m) - m
10502           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10503           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10504                                                          MVT::i8));
10505           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10506           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10507           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10508           return Res;
10509         }
10510         llvm_unreachable("Unknown shift opcode.");
10511       }
10512
10513       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10514         if (Op.getOpcode() == ISD::SHL) {
10515           // Make a large shift.
10516           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10517                                     DAG.getConstant(ShiftAmt, MVT::i32));
10518           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10519           // Zero out the rightmost bits.
10520           SmallVector<SDValue, 32> V(32,
10521                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10522                                                      MVT::i8));
10523           return DAG.getNode(ISD::AND, dl, VT, SHL,
10524                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10525         }
10526         if (Op.getOpcode() == ISD::SRL) {
10527           // Make a large shift.
10528           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10529                                     DAG.getConstant(ShiftAmt, MVT::i32));
10530           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10531           // Zero out the leftmost bits.
10532           SmallVector<SDValue, 32> V(32,
10533                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10534                                                      MVT::i8));
10535           return DAG.getNode(ISD::AND, dl, VT, SRL,
10536                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10537         }
10538         if (Op.getOpcode() == ISD::SRA) {
10539           if (ShiftAmt == 7) {
10540             // R s>> 7  ===  R s< 0
10541             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10542             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10543           }
10544
10545           // R s>> a === ((R u>> a) ^ m) - m
10546           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10547           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10548                                                          MVT::i8));
10549           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10550           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10551           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10552           return Res;
10553         }
10554         llvm_unreachable("Unknown shift opcode.");
10555       }
10556     }
10557   }
10558
10559   // Lower SHL with variable shift amount.
10560   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10561     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10562                      DAG.getConstant(23, MVT::i32));
10563
10564     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10565     Constant *C = ConstantDataVector::get(*Context, CV);
10566     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10567     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10568                                  MachinePointerInfo::getConstantPool(),
10569                                  false, false, false, 16);
10570
10571     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10572     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10573     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10574     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10575   }
10576   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10577     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10578
10579     // a = a << 5;
10580     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10581                      DAG.getConstant(5, MVT::i32));
10582     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10583
10584     // Turn 'a' into a mask suitable for VSELECT
10585     SDValue VSelM = DAG.getConstant(0x80, VT);
10586     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10587     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10588
10589     SDValue CM1 = DAG.getConstant(0x0f, VT);
10590     SDValue CM2 = DAG.getConstant(0x3f, VT);
10591
10592     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10593     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10594     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10595                             DAG.getConstant(4, MVT::i32), DAG);
10596     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10597     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10598
10599     // a += a
10600     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10601     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10602     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10603
10604     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10605     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10606     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10607                             DAG.getConstant(2, MVT::i32), DAG);
10608     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10609     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10610
10611     // a += a
10612     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10613     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10614     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10615
10616     // return VSELECT(r, r+r, a);
10617     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10618                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10619     return R;
10620   }
10621
10622   // Decompose 256-bit shifts into smaller 128-bit shifts.
10623   if (VT.getSizeInBits() == 256) {
10624     unsigned NumElems = VT.getVectorNumElements();
10625     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10626     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10627
10628     // Extract the two vectors
10629     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10630     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10631
10632     // Recreate the shift amount vectors
10633     SDValue Amt1, Amt2;
10634     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10635       // Constant shift amount
10636       SmallVector<SDValue, 4> Amt1Csts;
10637       SmallVector<SDValue, 4> Amt2Csts;
10638       for (unsigned i = 0; i != NumElems/2; ++i)
10639         Amt1Csts.push_back(Amt->getOperand(i));
10640       for (unsigned i = NumElems/2; i != NumElems; ++i)
10641         Amt2Csts.push_back(Amt->getOperand(i));
10642
10643       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10644                                  &Amt1Csts[0], NumElems/2);
10645       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10646                                  &Amt2Csts[0], NumElems/2);
10647     } else {
10648       // Variable shift amount
10649       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10650       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10651     }
10652
10653     // Issue new vector shifts for the smaller types
10654     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10655     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10656
10657     // Concatenate the result back
10658     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10659   }
10660
10661   return SDValue();
10662 }
10663
10664 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10665   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10666   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10667   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10668   // has only one use.
10669   SDNode *N = Op.getNode();
10670   SDValue LHS = N->getOperand(0);
10671   SDValue RHS = N->getOperand(1);
10672   unsigned BaseOp = 0;
10673   unsigned Cond = 0;
10674   DebugLoc DL = Op.getDebugLoc();
10675   switch (Op.getOpcode()) {
10676   default: llvm_unreachable("Unknown ovf instruction!");
10677   case ISD::SADDO:
10678     // A subtract of one will be selected as a INC. Note that INC doesn't
10679     // set CF, so we can't do this for UADDO.
10680     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10681       if (C->isOne()) {
10682         BaseOp = X86ISD::INC;
10683         Cond = X86::COND_O;
10684         break;
10685       }
10686     BaseOp = X86ISD::ADD;
10687     Cond = X86::COND_O;
10688     break;
10689   case ISD::UADDO:
10690     BaseOp = X86ISD::ADD;
10691     Cond = X86::COND_B;
10692     break;
10693   case ISD::SSUBO:
10694     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10695     // set CF, so we can't do this for USUBO.
10696     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10697       if (C->isOne()) {
10698         BaseOp = X86ISD::DEC;
10699         Cond = X86::COND_O;
10700         break;
10701       }
10702     BaseOp = X86ISD::SUB;
10703     Cond = X86::COND_O;
10704     break;
10705   case ISD::USUBO:
10706     BaseOp = X86ISD::SUB;
10707     Cond = X86::COND_B;
10708     break;
10709   case ISD::SMULO:
10710     BaseOp = X86ISD::SMUL;
10711     Cond = X86::COND_O;
10712     break;
10713   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10714     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10715                                  MVT::i32);
10716     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10717
10718     SDValue SetCC =
10719       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10720                   DAG.getConstant(X86::COND_O, MVT::i32),
10721                   SDValue(Sum.getNode(), 2));
10722
10723     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10724   }
10725   }
10726
10727   // Also sets EFLAGS.
10728   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10729   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10730
10731   SDValue SetCC =
10732     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10733                 DAG.getConstant(Cond, MVT::i32),
10734                 SDValue(Sum.getNode(), 1));
10735
10736   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10737 }
10738
10739 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10740                                                   SelectionDAG &DAG) const {
10741   DebugLoc dl = Op.getDebugLoc();
10742   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10743   EVT VT = Op.getValueType();
10744
10745   if (!Subtarget->hasSSE2() || !VT.isVector())
10746     return SDValue();
10747
10748   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10749                       ExtraVT.getScalarType().getSizeInBits();
10750   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10751
10752   switch (VT.getSimpleVT().SimpleTy) {
10753     default: return SDValue();
10754     case MVT::v8i32:
10755     case MVT::v16i16:
10756       if (!Subtarget->hasAVX())
10757         return SDValue();
10758       if (!Subtarget->hasAVX2()) {
10759         // needs to be split
10760         unsigned NumElems = VT.getVectorNumElements();
10761
10762         // Extract the LHS vectors
10763         SDValue LHS = Op.getOperand(0);
10764         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10765         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10766
10767         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10768         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10769
10770         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10771         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10772         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10773                                    ExtraNumElems/2);
10774         SDValue Extra = DAG.getValueType(ExtraVT);
10775
10776         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10777         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10778
10779         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10780       }
10781       // fall through
10782     case MVT::v4i32:
10783     case MVT::v8i16: {
10784       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10785                                          Op.getOperand(0), ShAmt, DAG);
10786       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10787     }
10788   }
10789 }
10790
10791
10792 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10793   DebugLoc dl = Op.getDebugLoc();
10794
10795   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10796   // There isn't any reason to disable it if the target processor supports it.
10797   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10798     SDValue Chain = Op.getOperand(0);
10799     SDValue Zero = DAG.getConstant(0, MVT::i32);
10800     SDValue Ops[] = {
10801       DAG.getRegister(X86::ESP, MVT::i32), // Base
10802       DAG.getTargetConstant(1, MVT::i8),   // Scale
10803       DAG.getRegister(0, MVT::i32),        // Index
10804       DAG.getTargetConstant(0, MVT::i32),  // Disp
10805       DAG.getRegister(0, MVT::i32),        // Segment.
10806       Zero,
10807       Chain
10808     };
10809     SDNode *Res =
10810       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10811                           array_lengthof(Ops));
10812     return SDValue(Res, 0);
10813   }
10814
10815   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10816   if (!isDev)
10817     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10818
10819   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10820   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10821   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10822   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10823
10824   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10825   if (!Op1 && !Op2 && !Op3 && Op4)
10826     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10827
10828   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10829   if (Op1 && !Op2 && !Op3 && !Op4)
10830     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10831
10832   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10833   //           (MFENCE)>;
10834   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10835 }
10836
10837 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10838                                              SelectionDAG &DAG) const {
10839   DebugLoc dl = Op.getDebugLoc();
10840   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10841     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10842   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10843     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10844
10845   // The only fence that needs an instruction is a sequentially-consistent
10846   // cross-thread fence.
10847   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10848     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10849     // no-sse2). There isn't any reason to disable it if the target processor
10850     // supports it.
10851     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10852       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10853
10854     SDValue Chain = Op.getOperand(0);
10855     SDValue Zero = DAG.getConstant(0, MVT::i32);
10856     SDValue Ops[] = {
10857       DAG.getRegister(X86::ESP, MVT::i32), // Base
10858       DAG.getTargetConstant(1, MVT::i8),   // Scale
10859       DAG.getRegister(0, MVT::i32),        // Index
10860       DAG.getTargetConstant(0, MVT::i32),  // Disp
10861       DAG.getRegister(0, MVT::i32),        // Segment.
10862       Zero,
10863       Chain
10864     };
10865     SDNode *Res =
10866       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10867                          array_lengthof(Ops));
10868     return SDValue(Res, 0);
10869   }
10870
10871   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10872   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10873 }
10874
10875
10876 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10877   EVT T = Op.getValueType();
10878   DebugLoc DL = Op.getDebugLoc();
10879   unsigned Reg = 0;
10880   unsigned size = 0;
10881   switch(T.getSimpleVT().SimpleTy) {
10882   default: llvm_unreachable("Invalid value type!");
10883   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10884   case MVT::i16: Reg = X86::AX;  size = 2; break;
10885   case MVT::i32: Reg = X86::EAX; size = 4; break;
10886   case MVT::i64:
10887     assert(Subtarget->is64Bit() && "Node not type legal!");
10888     Reg = X86::RAX; size = 8;
10889     break;
10890   }
10891   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10892                                     Op.getOperand(2), SDValue());
10893   SDValue Ops[] = { cpIn.getValue(0),
10894                     Op.getOperand(1),
10895                     Op.getOperand(3),
10896                     DAG.getTargetConstant(size, MVT::i8),
10897                     cpIn.getValue(1) };
10898   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10899   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10900   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10901                                            Ops, 5, T, MMO);
10902   SDValue cpOut =
10903     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10904   return cpOut;
10905 }
10906
10907 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10908                                                  SelectionDAG &DAG) const {
10909   assert(Subtarget->is64Bit() && "Result not type legalized?");
10910   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10911   SDValue TheChain = Op.getOperand(0);
10912   DebugLoc dl = Op.getDebugLoc();
10913   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10914   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10915   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10916                                    rax.getValue(2));
10917   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10918                             DAG.getConstant(32, MVT::i8));
10919   SDValue Ops[] = {
10920     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10921     rdx.getValue(1)
10922   };
10923   return DAG.getMergeValues(Ops, 2, dl);
10924 }
10925
10926 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10927                                             SelectionDAG &DAG) const {
10928   EVT SrcVT = Op.getOperand(0).getValueType();
10929   EVT DstVT = Op.getValueType();
10930   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10931          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10932   assert((DstVT == MVT::i64 ||
10933           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10934          "Unexpected custom BITCAST");
10935   // i64 <=> MMX conversions are Legal.
10936   if (SrcVT==MVT::i64 && DstVT.isVector())
10937     return Op;
10938   if (DstVT==MVT::i64 && SrcVT.isVector())
10939     return Op;
10940   // MMX <=> MMX conversions are Legal.
10941   if (SrcVT.isVector() && DstVT.isVector())
10942     return Op;
10943   // All other conversions need to be expanded.
10944   return SDValue();
10945 }
10946
10947 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10948   SDNode *Node = Op.getNode();
10949   DebugLoc dl = Node->getDebugLoc();
10950   EVT T = Node->getValueType(0);
10951   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10952                               DAG.getConstant(0, T), Node->getOperand(2));
10953   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10954                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10955                        Node->getOperand(0),
10956                        Node->getOperand(1), negOp,
10957                        cast<AtomicSDNode>(Node)->getSrcValue(),
10958                        cast<AtomicSDNode>(Node)->getAlignment(),
10959                        cast<AtomicSDNode>(Node)->getOrdering(),
10960                        cast<AtomicSDNode>(Node)->getSynchScope());
10961 }
10962
10963 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10964   SDNode *Node = Op.getNode();
10965   DebugLoc dl = Node->getDebugLoc();
10966   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10967
10968   // Convert seq_cst store -> xchg
10969   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10970   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10971   //        (The only way to get a 16-byte store is cmpxchg16b)
10972   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10973   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10974       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10975     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10976                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10977                                  Node->getOperand(0),
10978                                  Node->getOperand(1), Node->getOperand(2),
10979                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10980                                  cast<AtomicSDNode>(Node)->getOrdering(),
10981                                  cast<AtomicSDNode>(Node)->getSynchScope());
10982     return Swap.getValue(1);
10983   }
10984   // Other atomic stores have a simple pattern.
10985   return Op;
10986 }
10987
10988 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10989   EVT VT = Op.getNode()->getValueType(0);
10990
10991   // Let legalize expand this if it isn't a legal type yet.
10992   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10993     return SDValue();
10994
10995   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10996
10997   unsigned Opc;
10998   bool ExtraOp = false;
10999   switch (Op.getOpcode()) {
11000   default: llvm_unreachable("Invalid code");
11001   case ISD::ADDC: Opc = X86ISD::ADD; break;
11002   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11003   case ISD::SUBC: Opc = X86ISD::SUB; break;
11004   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11005   }
11006
11007   if (!ExtraOp)
11008     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11009                        Op.getOperand(1));
11010   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11011                      Op.getOperand(1), Op.getOperand(2));
11012 }
11013
11014 /// LowerOperation - Provide custom lowering hooks for some operations.
11015 ///
11016 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11017   switch (Op.getOpcode()) {
11018   default: llvm_unreachable("Should not custom lower this!");
11019   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11020   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
11021   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
11022   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
11023   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11024   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11025   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11026   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11027   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11028   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11029   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11030   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
11031   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
11032   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11033   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11034   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11035   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11036   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11037   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11038   case ISD::SHL_PARTS:
11039   case ISD::SRA_PARTS:
11040   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11041   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11042   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11043   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11044   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11045   case ISD::FABS:               return LowerFABS(Op, DAG);
11046   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11047   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11048   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11049   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11050   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11051   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11052   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11053   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11054   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11055   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11056   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11057   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11058   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11059   case ISD::FRAME_TO_ARGS_OFFSET:
11060                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11061   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11062   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11063   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11064   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11065   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11066   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11067   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11068   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11069   case ISD::MUL:                return LowerMUL(Op, DAG);
11070   case ISD::SRA:
11071   case ISD::SRL:
11072   case ISD::SHL:                return LowerShift(Op, DAG);
11073   case ISD::SADDO:
11074   case ISD::UADDO:
11075   case ISD::SSUBO:
11076   case ISD::USUBO:
11077   case ISD::SMULO:
11078   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11079   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
11080   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11081   case ISD::ADDC:
11082   case ISD::ADDE:
11083   case ISD::SUBC:
11084   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11085   case ISD::ADD:                return LowerADD(Op, DAG);
11086   case ISD::SUB:                return LowerSUB(Op, DAG);
11087   }
11088 }
11089
11090 static void ReplaceATOMIC_LOAD(SDNode *Node,
11091                                   SmallVectorImpl<SDValue> &Results,
11092                                   SelectionDAG &DAG) {
11093   DebugLoc dl = Node->getDebugLoc();
11094   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11095
11096   // Convert wide load -> cmpxchg8b/cmpxchg16b
11097   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11098   //        (The only way to get a 16-byte load is cmpxchg16b)
11099   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11100   SDValue Zero = DAG.getConstant(0, VT);
11101   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11102                                Node->getOperand(0),
11103                                Node->getOperand(1), Zero, Zero,
11104                                cast<AtomicSDNode>(Node)->getMemOperand(),
11105                                cast<AtomicSDNode>(Node)->getOrdering(),
11106                                cast<AtomicSDNode>(Node)->getSynchScope());
11107   Results.push_back(Swap.getValue(0));
11108   Results.push_back(Swap.getValue(1));
11109 }
11110
11111 void X86TargetLowering::
11112 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11113                         SelectionDAG &DAG, unsigned NewOp) const {
11114   DebugLoc dl = Node->getDebugLoc();
11115   assert (Node->getValueType(0) == MVT::i64 &&
11116           "Only know how to expand i64 atomics");
11117
11118   SDValue Chain = Node->getOperand(0);
11119   SDValue In1 = Node->getOperand(1);
11120   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11121                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11122   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11123                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11124   SDValue Ops[] = { Chain, In1, In2L, In2H };
11125   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11126   SDValue Result =
11127     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11128                             cast<MemSDNode>(Node)->getMemOperand());
11129   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11130   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11131   Results.push_back(Result.getValue(2));
11132 }
11133
11134 /// ReplaceNodeResults - Replace a node with an illegal result type
11135 /// with a new node built out of custom code.
11136 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11137                                            SmallVectorImpl<SDValue>&Results,
11138                                            SelectionDAG &DAG) const {
11139   DebugLoc dl = N->getDebugLoc();
11140   switch (N->getOpcode()) {
11141   default:
11142     llvm_unreachable("Do not know how to custom type legalize this operation!");
11143   case ISD::SIGN_EXTEND_INREG:
11144   case ISD::ADDC:
11145   case ISD::ADDE:
11146   case ISD::SUBC:
11147   case ISD::SUBE:
11148     // We don't want to expand or promote these.
11149     return;
11150   case ISD::FP_TO_SINT:
11151   case ISD::FP_TO_UINT: {
11152     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11153
11154     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11155       return;
11156
11157     std::pair<SDValue,SDValue> Vals =
11158         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11159     SDValue FIST = Vals.first, StackSlot = Vals.second;
11160     if (FIST.getNode() != 0) {
11161       EVT VT = N->getValueType(0);
11162       // Return a load from the stack slot.
11163       if (StackSlot.getNode() != 0)
11164         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11165                                       MachinePointerInfo(),
11166                                       false, false, false, 0));
11167       else
11168         Results.push_back(FIST);
11169     }
11170     return;
11171   }
11172   case ISD::READCYCLECOUNTER: {
11173     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11174     SDValue TheChain = N->getOperand(0);
11175     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11176     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11177                                      rd.getValue(1));
11178     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11179                                      eax.getValue(2));
11180     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11181     SDValue Ops[] = { eax, edx };
11182     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11183     Results.push_back(edx.getValue(1));
11184     return;
11185   }
11186   case ISD::ATOMIC_CMP_SWAP: {
11187     EVT T = N->getValueType(0);
11188     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11189     bool Regs64bit = T == MVT::i128;
11190     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11191     SDValue cpInL, cpInH;
11192     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11193                         DAG.getConstant(0, HalfT));
11194     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11195                         DAG.getConstant(1, HalfT));
11196     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11197                              Regs64bit ? X86::RAX : X86::EAX,
11198                              cpInL, SDValue());
11199     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11200                              Regs64bit ? X86::RDX : X86::EDX,
11201                              cpInH, cpInL.getValue(1));
11202     SDValue swapInL, swapInH;
11203     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11204                           DAG.getConstant(0, HalfT));
11205     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11206                           DAG.getConstant(1, HalfT));
11207     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11208                                Regs64bit ? X86::RBX : X86::EBX,
11209                                swapInL, cpInH.getValue(1));
11210     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11211                                Regs64bit ? X86::RCX : X86::ECX, 
11212                                swapInH, swapInL.getValue(1));
11213     SDValue Ops[] = { swapInH.getValue(0),
11214                       N->getOperand(1),
11215                       swapInH.getValue(1) };
11216     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11217     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11218     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11219                                   X86ISD::LCMPXCHG8_DAG;
11220     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11221                                              Ops, 3, T, MMO);
11222     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11223                                         Regs64bit ? X86::RAX : X86::EAX,
11224                                         HalfT, Result.getValue(1));
11225     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11226                                         Regs64bit ? X86::RDX : X86::EDX,
11227                                         HalfT, cpOutL.getValue(2));
11228     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11229     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11230     Results.push_back(cpOutH.getValue(1));
11231     return;
11232   }
11233   case ISD::ATOMIC_LOAD_ADD:
11234     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11235     return;
11236   case ISD::ATOMIC_LOAD_AND:
11237     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11238     return;
11239   case ISD::ATOMIC_LOAD_NAND:
11240     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11241     return;
11242   case ISD::ATOMIC_LOAD_OR:
11243     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11244     return;
11245   case ISD::ATOMIC_LOAD_SUB:
11246     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11247     return;
11248   case ISD::ATOMIC_LOAD_XOR:
11249     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11250     return;
11251   case ISD::ATOMIC_SWAP:
11252     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11253     return;
11254   case ISD::ATOMIC_LOAD:
11255     ReplaceATOMIC_LOAD(N, Results, DAG);
11256   }
11257 }
11258
11259 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11260   switch (Opcode) {
11261   default: return NULL;
11262   case X86ISD::BSF:                return "X86ISD::BSF";
11263   case X86ISD::BSR:                return "X86ISD::BSR";
11264   case X86ISD::SHLD:               return "X86ISD::SHLD";
11265   case X86ISD::SHRD:               return "X86ISD::SHRD";
11266   case X86ISD::FAND:               return "X86ISD::FAND";
11267   case X86ISD::FOR:                return "X86ISD::FOR";
11268   case X86ISD::FXOR:               return "X86ISD::FXOR";
11269   case X86ISD::FSRL:               return "X86ISD::FSRL";
11270   case X86ISD::FILD:               return "X86ISD::FILD";
11271   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11272   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11273   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11274   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11275   case X86ISD::FLD:                return "X86ISD::FLD";
11276   case X86ISD::FST:                return "X86ISD::FST";
11277   case X86ISD::CALL:               return "X86ISD::CALL";
11278   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11279   case X86ISD::BT:                 return "X86ISD::BT";
11280   case X86ISD::CMP:                return "X86ISD::CMP";
11281   case X86ISD::COMI:               return "X86ISD::COMI";
11282   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11283   case X86ISD::SETCC:              return "X86ISD::SETCC";
11284   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11285   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11286   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11287   case X86ISD::CMOV:               return "X86ISD::CMOV";
11288   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11289   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11290   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11291   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11292   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11293   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11294   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11295   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11296   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11297   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11298   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11299   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11300   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11301   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11302   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11303   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11304   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11305   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11306   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11307   case X86ISD::HADD:               return "X86ISD::HADD";
11308   case X86ISD::HSUB:               return "X86ISD::HSUB";
11309   case X86ISD::FHADD:              return "X86ISD::FHADD";
11310   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11311   case X86ISD::FMAX:               return "X86ISD::FMAX";
11312   case X86ISD::FMIN:               return "X86ISD::FMIN";
11313   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11314   case X86ISD::FRCP:               return "X86ISD::FRCP";
11315   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11316   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11317   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11318   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11319   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11320   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11321   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11322   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11323   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11324   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11325   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11326   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11327   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11328   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11329   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11330   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11331   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11332   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11333   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11334   case X86ISD::VSHL:               return "X86ISD::VSHL";
11335   case X86ISD::VSRL:               return "X86ISD::VSRL";
11336   case X86ISD::VSRA:               return "X86ISD::VSRA";
11337   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11338   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11339   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11340   case X86ISD::CMPP:               return "X86ISD::CMPP";
11341   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11342   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11343   case X86ISD::ADD:                return "X86ISD::ADD";
11344   case X86ISD::SUB:                return "X86ISD::SUB";
11345   case X86ISD::ADC:                return "X86ISD::ADC";
11346   case X86ISD::SBB:                return "X86ISD::SBB";
11347   case X86ISD::SMUL:               return "X86ISD::SMUL";
11348   case X86ISD::UMUL:               return "X86ISD::UMUL";
11349   case X86ISD::INC:                return "X86ISD::INC";
11350   case X86ISD::DEC:                return "X86ISD::DEC";
11351   case X86ISD::OR:                 return "X86ISD::OR";
11352   case X86ISD::XOR:                return "X86ISD::XOR";
11353   case X86ISD::AND:                return "X86ISD::AND";
11354   case X86ISD::ANDN:               return "X86ISD::ANDN";
11355   case X86ISD::BLSI:               return "X86ISD::BLSI";
11356   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11357   case X86ISD::BLSR:               return "X86ISD::BLSR";
11358   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11359   case X86ISD::PTEST:              return "X86ISD::PTEST";
11360   case X86ISD::TESTP:              return "X86ISD::TESTP";
11361   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11362   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11363   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11364   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11365   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11366   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11367   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11368   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11369   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11370   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11371   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11372   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11373   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11374   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11375   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11376   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11377   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11378   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11379   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11380   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11381   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11382   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11383   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11384   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11385   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11386   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11387   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11388   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11389   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11390   case X86ISD::SAHF:               return "X86ISD::SAHF";
11391   }
11392 }
11393
11394 // isLegalAddressingMode - Return true if the addressing mode represented
11395 // by AM is legal for this target, for a load/store of the specified type.
11396 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11397                                               Type *Ty) const {
11398   // X86 supports extremely general addressing modes.
11399   CodeModel::Model M = getTargetMachine().getCodeModel();
11400   Reloc::Model R = getTargetMachine().getRelocationModel();
11401
11402   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11403   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11404     return false;
11405
11406   if (AM.BaseGV) {
11407     unsigned GVFlags =
11408       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11409
11410     // If a reference to this global requires an extra load, we can't fold it.
11411     if (isGlobalStubReference(GVFlags))
11412       return false;
11413
11414     // If BaseGV requires a register for the PIC base, we cannot also have a
11415     // BaseReg specified.
11416     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11417       return false;
11418
11419     // If lower 4G is not available, then we must use rip-relative addressing.
11420     if ((M != CodeModel::Small || R != Reloc::Static) &&
11421         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11422       return false;
11423   }
11424
11425   switch (AM.Scale) {
11426   case 0:
11427   case 1:
11428   case 2:
11429   case 4:
11430   case 8:
11431     // These scales always work.
11432     break;
11433   case 3:
11434   case 5:
11435   case 9:
11436     // These scales are formed with basereg+scalereg.  Only accept if there is
11437     // no basereg yet.
11438     if (AM.HasBaseReg)
11439       return false;
11440     break;
11441   default:  // Other stuff never works.
11442     return false;
11443   }
11444
11445   return true;
11446 }
11447
11448
11449 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11450   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11451     return false;
11452   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11453   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11454   if (NumBits1 <= NumBits2)
11455     return false;
11456   return true;
11457 }
11458
11459 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11460   if (!VT1.isInteger() || !VT2.isInteger())
11461     return false;
11462   unsigned NumBits1 = VT1.getSizeInBits();
11463   unsigned NumBits2 = VT2.getSizeInBits();
11464   if (NumBits1 <= NumBits2)
11465     return false;
11466   return true;
11467 }
11468
11469 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11470   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11471   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11472 }
11473
11474 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11475   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11476   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11477 }
11478
11479 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11480   // i16 instructions are longer (0x66 prefix) and potentially slower.
11481   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11482 }
11483
11484 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11485 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11486 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11487 /// are assumed to be legal.
11488 bool
11489 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11490                                       EVT VT) const {
11491   // Very little shuffling can be done for 64-bit vectors right now.
11492   if (VT.getSizeInBits() == 64)
11493     return false;
11494
11495   // FIXME: pshufb, blends, shifts.
11496   return (VT.getVectorNumElements() == 2 ||
11497           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11498           isMOVLMask(M, VT) ||
11499           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11500           isPSHUFDMask(M, VT) ||
11501           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11502           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11503           isPALIGNRMask(M, VT, Subtarget) ||
11504           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11505           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11506           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11507           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11508 }
11509
11510 bool
11511 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11512                                           EVT VT) const {
11513   unsigned NumElts = VT.getVectorNumElements();
11514   // FIXME: This collection of masks seems suspect.
11515   if (NumElts == 2)
11516     return true;
11517   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11518     return (isMOVLMask(Mask, VT)  ||
11519             isCommutedMOVLMask(Mask, VT, true) ||
11520             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11521             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11522   }
11523   return false;
11524 }
11525
11526 //===----------------------------------------------------------------------===//
11527 //                           X86 Scheduler Hooks
11528 //===----------------------------------------------------------------------===//
11529
11530 // private utility function
11531 MachineBasicBlock *
11532 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11533                                                        MachineBasicBlock *MBB,
11534                                                        unsigned regOpc,
11535                                                        unsigned immOpc,
11536                                                        unsigned LoadOpc,
11537                                                        unsigned CXchgOpc,
11538                                                        unsigned notOpc,
11539                                                        unsigned EAXreg,
11540                                                  const TargetRegisterClass *RC,
11541                                                        bool Invert) const {
11542   // For the atomic bitwise operator, we generate
11543   //   thisMBB:
11544   //   newMBB:
11545   //     ld  t1 = [bitinstr.addr]
11546   //     op  t2 = t1, [bitinstr.val]
11547   //     not t3 = t2  (if Invert)
11548   //     mov EAX = t1
11549   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11550   //     bz  newMBB
11551   //     fallthrough -->nextMBB
11552   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11553   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11554   MachineFunction::iterator MBBIter = MBB;
11555   ++MBBIter;
11556
11557   /// First build the CFG
11558   MachineFunction *F = MBB->getParent();
11559   MachineBasicBlock *thisMBB = MBB;
11560   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11561   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11562   F->insert(MBBIter, newMBB);
11563   F->insert(MBBIter, nextMBB);
11564
11565   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11566   nextMBB->splice(nextMBB->begin(), thisMBB,
11567                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11568                   thisMBB->end());
11569   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11570
11571   // Update thisMBB to fall through to newMBB
11572   thisMBB->addSuccessor(newMBB);
11573
11574   // newMBB jumps to itself and fall through to nextMBB
11575   newMBB->addSuccessor(nextMBB);
11576   newMBB->addSuccessor(newMBB);
11577
11578   // Insert instructions into newMBB based on incoming instruction
11579   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11580          "unexpected number of operands");
11581   DebugLoc dl = bInstr->getDebugLoc();
11582   MachineOperand& destOper = bInstr->getOperand(0);
11583   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11584   int numArgs = bInstr->getNumOperands() - 1;
11585   for (int i=0; i < numArgs; ++i)
11586     argOpers[i] = &bInstr->getOperand(i+1);
11587
11588   // x86 address has 4 operands: base, index, scale, and displacement
11589   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11590   int valArgIndx = lastAddrIndx + 1;
11591
11592   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11593   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11594   for (int i=0; i <= lastAddrIndx; ++i)
11595     (*MIB).addOperand(*argOpers[i]);
11596
11597   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11598   assert((argOpers[valArgIndx]->isReg() ||
11599           argOpers[valArgIndx]->isImm()) &&
11600          "invalid operand");
11601   if (argOpers[valArgIndx]->isReg())
11602     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11603   else
11604     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11605   MIB.addReg(t1);
11606   (*MIB).addOperand(*argOpers[valArgIndx]);
11607
11608   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11609   if (Invert) {
11610     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11611   }
11612   else
11613     t3 = t2;
11614
11615   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11616   MIB.addReg(t1);
11617
11618   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11619   for (int i=0; i <= lastAddrIndx; ++i)
11620     (*MIB).addOperand(*argOpers[i]);
11621   MIB.addReg(t3);
11622   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11623   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11624                     bInstr->memoperands_end());
11625
11626   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11627   MIB.addReg(EAXreg);
11628
11629   // insert branch
11630   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11631
11632   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11633   return nextMBB;
11634 }
11635
11636 // private utility function:  64 bit atomics on 32 bit host.
11637 MachineBasicBlock *
11638 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11639                                                        MachineBasicBlock *MBB,
11640                                                        unsigned regOpcL,
11641                                                        unsigned regOpcH,
11642                                                        unsigned immOpcL,
11643                                                        unsigned immOpcH,
11644                                                        bool Invert) const {
11645   // For the atomic bitwise operator, we generate
11646   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11647   //     ld t1,t2 = [bitinstr.addr]
11648   //   newMBB:
11649   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11650   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11651   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11652   //     neg t7, t8 < t5, t6  (if Invert)
11653   //     mov ECX, EBX <- t5, t6
11654   //     mov EAX, EDX <- t1, t2
11655   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11656   //     mov t3, t4 <- EAX, EDX
11657   //     bz  newMBB
11658   //     result in out1, out2
11659   //     fallthrough -->nextMBB
11660
11661   const TargetRegisterClass *RC = &X86::GR32RegClass;
11662   const unsigned LoadOpc = X86::MOV32rm;
11663   const unsigned NotOpc = X86::NOT32r;
11664   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11665   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11666   MachineFunction::iterator MBBIter = MBB;
11667   ++MBBIter;
11668
11669   /// First build the CFG
11670   MachineFunction *F = MBB->getParent();
11671   MachineBasicBlock *thisMBB = MBB;
11672   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11673   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11674   F->insert(MBBIter, newMBB);
11675   F->insert(MBBIter, nextMBB);
11676
11677   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11678   nextMBB->splice(nextMBB->begin(), thisMBB,
11679                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11680                   thisMBB->end());
11681   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11682
11683   // Update thisMBB to fall through to newMBB
11684   thisMBB->addSuccessor(newMBB);
11685
11686   // newMBB jumps to itself and fall through to nextMBB
11687   newMBB->addSuccessor(nextMBB);
11688   newMBB->addSuccessor(newMBB);
11689
11690   DebugLoc dl = bInstr->getDebugLoc();
11691   // Insert instructions into newMBB based on incoming instruction
11692   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11693   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11694          "unexpected number of operands");
11695   MachineOperand& dest1Oper = bInstr->getOperand(0);
11696   MachineOperand& dest2Oper = bInstr->getOperand(1);
11697   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11698   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11699     argOpers[i] = &bInstr->getOperand(i+2);
11700
11701     // We use some of the operands multiple times, so conservatively just
11702     // clear any kill flags that might be present.
11703     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11704       argOpers[i]->setIsKill(false);
11705   }
11706
11707   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11708   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11709
11710   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11711   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11712   for (int i=0; i <= lastAddrIndx; ++i)
11713     (*MIB).addOperand(*argOpers[i]);
11714   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11715   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11716   // add 4 to displacement.
11717   for (int i=0; i <= lastAddrIndx-2; ++i)
11718     (*MIB).addOperand(*argOpers[i]);
11719   MachineOperand newOp3 = *(argOpers[3]);
11720   if (newOp3.isImm())
11721     newOp3.setImm(newOp3.getImm()+4);
11722   else
11723     newOp3.setOffset(newOp3.getOffset()+4);
11724   (*MIB).addOperand(newOp3);
11725   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11726
11727   // t3/4 are defined later, at the bottom of the loop
11728   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11729   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11730   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11731     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11732   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11733     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11734
11735   // The subsequent operations should be using the destination registers of
11736   // the PHI instructions.
11737   t1 = dest1Oper.getReg();
11738   t2 = dest2Oper.getReg();
11739
11740   int valArgIndx = lastAddrIndx + 1;
11741   assert((argOpers[valArgIndx]->isReg() ||
11742           argOpers[valArgIndx]->isImm()) &&
11743          "invalid operand");
11744   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11745   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11746   if (argOpers[valArgIndx]->isReg())
11747     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11748   else
11749     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11750   if (regOpcL != X86::MOV32rr)
11751     MIB.addReg(t1);
11752   (*MIB).addOperand(*argOpers[valArgIndx]);
11753   assert(argOpers[valArgIndx + 1]->isReg() ==
11754          argOpers[valArgIndx]->isReg());
11755   assert(argOpers[valArgIndx + 1]->isImm() ==
11756          argOpers[valArgIndx]->isImm());
11757   if (argOpers[valArgIndx + 1]->isReg())
11758     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11759   else
11760     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11761   if (regOpcH != X86::MOV32rr)
11762     MIB.addReg(t2);
11763   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11764
11765   unsigned t7, t8;
11766   if (Invert) {
11767     t7 = F->getRegInfo().createVirtualRegister(RC);
11768     t8 = F->getRegInfo().createVirtualRegister(RC);
11769     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11770     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11771   } else {
11772     t7 = t5;
11773     t8 = t6;
11774   }
11775
11776   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11777   MIB.addReg(t1);
11778   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11779   MIB.addReg(t2);
11780
11781   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11782   MIB.addReg(t7);
11783   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11784   MIB.addReg(t8);
11785
11786   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11787   for (int i=0; i <= lastAddrIndx; ++i)
11788     (*MIB).addOperand(*argOpers[i]);
11789
11790   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11791   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11792                     bInstr->memoperands_end());
11793
11794   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11795   MIB.addReg(X86::EAX);
11796   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11797   MIB.addReg(X86::EDX);
11798
11799   // insert branch
11800   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11801
11802   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11803   return nextMBB;
11804 }
11805
11806 // private utility function
11807 MachineBasicBlock *
11808 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11809                                                       MachineBasicBlock *MBB,
11810                                                       unsigned cmovOpc) const {
11811   // For the atomic min/max operator, we generate
11812   //   thisMBB:
11813   //   newMBB:
11814   //     ld t1 = [min/max.addr]
11815   //     mov t2 = [min/max.val]
11816   //     cmp  t1, t2
11817   //     cmov[cond] t2 = t1
11818   //     mov EAX = t1
11819   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11820   //     bz   newMBB
11821   //     fallthrough -->nextMBB
11822   //
11823   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11824   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11825   MachineFunction::iterator MBBIter = MBB;
11826   ++MBBIter;
11827
11828   /// First build the CFG
11829   MachineFunction *F = MBB->getParent();
11830   MachineBasicBlock *thisMBB = MBB;
11831   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11832   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11833   F->insert(MBBIter, newMBB);
11834   F->insert(MBBIter, nextMBB);
11835
11836   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11837   nextMBB->splice(nextMBB->begin(), thisMBB,
11838                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11839                   thisMBB->end());
11840   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11841
11842   // Update thisMBB to fall through to newMBB
11843   thisMBB->addSuccessor(newMBB);
11844
11845   // newMBB jumps to newMBB and fall through to nextMBB
11846   newMBB->addSuccessor(nextMBB);
11847   newMBB->addSuccessor(newMBB);
11848
11849   DebugLoc dl = mInstr->getDebugLoc();
11850   // Insert instructions into newMBB based on incoming instruction
11851   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11852          "unexpected number of operands");
11853   MachineOperand& destOper = mInstr->getOperand(0);
11854   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11855   int numArgs = mInstr->getNumOperands() - 1;
11856   for (int i=0; i < numArgs; ++i)
11857     argOpers[i] = &mInstr->getOperand(i+1);
11858
11859   // x86 address has 4 operands: base, index, scale, and displacement
11860   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11861   int valArgIndx = lastAddrIndx + 1;
11862
11863   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11864   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11865   for (int i=0; i <= lastAddrIndx; ++i)
11866     (*MIB).addOperand(*argOpers[i]);
11867
11868   // We only support register and immediate values
11869   assert((argOpers[valArgIndx]->isReg() ||
11870           argOpers[valArgIndx]->isImm()) &&
11871          "invalid operand");
11872
11873   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11874   if (argOpers[valArgIndx]->isReg())
11875     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11876   else
11877     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11878   (*MIB).addOperand(*argOpers[valArgIndx]);
11879
11880   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11881   MIB.addReg(t1);
11882
11883   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11884   MIB.addReg(t1);
11885   MIB.addReg(t2);
11886
11887   // Generate movc
11888   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11889   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11890   MIB.addReg(t2);
11891   MIB.addReg(t1);
11892
11893   // Cmp and exchange if none has modified the memory location
11894   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11895   for (int i=0; i <= lastAddrIndx; ++i)
11896     (*MIB).addOperand(*argOpers[i]);
11897   MIB.addReg(t3);
11898   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11899   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11900                     mInstr->memoperands_end());
11901
11902   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11903   MIB.addReg(X86::EAX);
11904
11905   // insert branch
11906   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11907
11908   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11909   return nextMBB;
11910 }
11911
11912 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11913 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11914 // in the .td file.
11915 MachineBasicBlock *
11916 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11917                             unsigned numArgs, bool memArg) const {
11918   assert(Subtarget->hasSSE42() &&
11919          "Target must have SSE4.2 or AVX features enabled");
11920
11921   DebugLoc dl = MI->getDebugLoc();
11922   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11923   unsigned Opc;
11924   if (!Subtarget->hasAVX()) {
11925     if (memArg)
11926       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11927     else
11928       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11929   } else {
11930     if (memArg)
11931       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11932     else
11933       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11934   }
11935
11936   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11937   for (unsigned i = 0; i < numArgs; ++i) {
11938     MachineOperand &Op = MI->getOperand(i+1);
11939     if (!(Op.isReg() && Op.isImplicit()))
11940       MIB.addOperand(Op);
11941   }
11942   BuildMI(*BB, MI, dl,
11943     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11944              MI->getOperand(0).getReg())
11945     .addReg(X86::XMM0);
11946
11947   MI->eraseFromParent();
11948   return BB;
11949 }
11950
11951 MachineBasicBlock *
11952 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11953   DebugLoc dl = MI->getDebugLoc();
11954   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11955
11956   // Address into RAX/EAX, other two args into ECX, EDX.
11957   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11958   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11959   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11960   for (int i = 0; i < X86::AddrNumOperands; ++i)
11961     MIB.addOperand(MI->getOperand(i));
11962
11963   unsigned ValOps = X86::AddrNumOperands;
11964   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11965     .addReg(MI->getOperand(ValOps).getReg());
11966   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11967     .addReg(MI->getOperand(ValOps+1).getReg());
11968
11969   // The instruction doesn't actually take any operands though.
11970   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11971
11972   MI->eraseFromParent(); // The pseudo is gone now.
11973   return BB;
11974 }
11975
11976 MachineBasicBlock *
11977 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11978   DebugLoc dl = MI->getDebugLoc();
11979   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11980
11981   // First arg in ECX, the second in EAX.
11982   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11983     .addReg(MI->getOperand(0).getReg());
11984   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11985     .addReg(MI->getOperand(1).getReg());
11986
11987   // The instruction doesn't actually take any operands though.
11988   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11989
11990   MI->eraseFromParent(); // The pseudo is gone now.
11991   return BB;
11992 }
11993
11994 MachineBasicBlock *
11995 X86TargetLowering::EmitVAARG64WithCustomInserter(
11996                    MachineInstr *MI,
11997                    MachineBasicBlock *MBB) const {
11998   // Emit va_arg instruction on X86-64.
11999
12000   // Operands to this pseudo-instruction:
12001   // 0  ) Output        : destination address (reg)
12002   // 1-5) Input         : va_list address (addr, i64mem)
12003   // 6  ) ArgSize       : Size (in bytes) of vararg type
12004   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12005   // 8  ) Align         : Alignment of type
12006   // 9  ) EFLAGS (implicit-def)
12007
12008   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12009   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12010
12011   unsigned DestReg = MI->getOperand(0).getReg();
12012   MachineOperand &Base = MI->getOperand(1);
12013   MachineOperand &Scale = MI->getOperand(2);
12014   MachineOperand &Index = MI->getOperand(3);
12015   MachineOperand &Disp = MI->getOperand(4);
12016   MachineOperand &Segment = MI->getOperand(5);
12017   unsigned ArgSize = MI->getOperand(6).getImm();
12018   unsigned ArgMode = MI->getOperand(7).getImm();
12019   unsigned Align = MI->getOperand(8).getImm();
12020
12021   // Memory Reference
12022   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12023   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12024   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12025
12026   // Machine Information
12027   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12028   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12029   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12030   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12031   DebugLoc DL = MI->getDebugLoc();
12032
12033   // struct va_list {
12034   //   i32   gp_offset
12035   //   i32   fp_offset
12036   //   i64   overflow_area (address)
12037   //   i64   reg_save_area (address)
12038   // }
12039   // sizeof(va_list) = 24
12040   // alignment(va_list) = 8
12041
12042   unsigned TotalNumIntRegs = 6;
12043   unsigned TotalNumXMMRegs = 8;
12044   bool UseGPOffset = (ArgMode == 1);
12045   bool UseFPOffset = (ArgMode == 2);
12046   unsigned MaxOffset = TotalNumIntRegs * 8 +
12047                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12048
12049   /* Align ArgSize to a multiple of 8 */
12050   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12051   bool NeedsAlign = (Align > 8);
12052
12053   MachineBasicBlock *thisMBB = MBB;
12054   MachineBasicBlock *overflowMBB;
12055   MachineBasicBlock *offsetMBB;
12056   MachineBasicBlock *endMBB;
12057
12058   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12059   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12060   unsigned OffsetReg = 0;
12061
12062   if (!UseGPOffset && !UseFPOffset) {
12063     // If we only pull from the overflow region, we don't create a branch.
12064     // We don't need to alter control flow.
12065     OffsetDestReg = 0; // unused
12066     OverflowDestReg = DestReg;
12067
12068     offsetMBB = NULL;
12069     overflowMBB = thisMBB;
12070     endMBB = thisMBB;
12071   } else {
12072     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12073     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12074     // If not, pull from overflow_area. (branch to overflowMBB)
12075     //
12076     //       thisMBB
12077     //         |     .
12078     //         |        .
12079     //     offsetMBB   overflowMBB
12080     //         |        .
12081     //         |     .
12082     //        endMBB
12083
12084     // Registers for the PHI in endMBB
12085     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12086     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12087
12088     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12089     MachineFunction *MF = MBB->getParent();
12090     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12091     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12092     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12093
12094     MachineFunction::iterator MBBIter = MBB;
12095     ++MBBIter;
12096
12097     // Insert the new basic blocks
12098     MF->insert(MBBIter, offsetMBB);
12099     MF->insert(MBBIter, overflowMBB);
12100     MF->insert(MBBIter, endMBB);
12101
12102     // Transfer the remainder of MBB and its successor edges to endMBB.
12103     endMBB->splice(endMBB->begin(), thisMBB,
12104                     llvm::next(MachineBasicBlock::iterator(MI)),
12105                     thisMBB->end());
12106     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12107
12108     // Make offsetMBB and overflowMBB successors of thisMBB
12109     thisMBB->addSuccessor(offsetMBB);
12110     thisMBB->addSuccessor(overflowMBB);
12111
12112     // endMBB is a successor of both offsetMBB and overflowMBB
12113     offsetMBB->addSuccessor(endMBB);
12114     overflowMBB->addSuccessor(endMBB);
12115
12116     // Load the offset value into a register
12117     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12118     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12119       .addOperand(Base)
12120       .addOperand(Scale)
12121       .addOperand(Index)
12122       .addDisp(Disp, UseFPOffset ? 4 : 0)
12123       .addOperand(Segment)
12124       .setMemRefs(MMOBegin, MMOEnd);
12125
12126     // Check if there is enough room left to pull this argument.
12127     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12128       .addReg(OffsetReg)
12129       .addImm(MaxOffset + 8 - ArgSizeA8);
12130
12131     // Branch to "overflowMBB" if offset >= max
12132     // Fall through to "offsetMBB" otherwise
12133     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12134       .addMBB(overflowMBB);
12135   }
12136
12137   // In offsetMBB, emit code to use the reg_save_area.
12138   if (offsetMBB) {
12139     assert(OffsetReg != 0);
12140
12141     // Read the reg_save_area address.
12142     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12143     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12144       .addOperand(Base)
12145       .addOperand(Scale)
12146       .addOperand(Index)
12147       .addDisp(Disp, 16)
12148       .addOperand(Segment)
12149       .setMemRefs(MMOBegin, MMOEnd);
12150
12151     // Zero-extend the offset
12152     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12153       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12154         .addImm(0)
12155         .addReg(OffsetReg)
12156         .addImm(X86::sub_32bit);
12157
12158     // Add the offset to the reg_save_area to get the final address.
12159     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12160       .addReg(OffsetReg64)
12161       .addReg(RegSaveReg);
12162
12163     // Compute the offset for the next argument
12164     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12165     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12166       .addReg(OffsetReg)
12167       .addImm(UseFPOffset ? 16 : 8);
12168
12169     // Store it back into the va_list.
12170     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12171       .addOperand(Base)
12172       .addOperand(Scale)
12173       .addOperand(Index)
12174       .addDisp(Disp, UseFPOffset ? 4 : 0)
12175       .addOperand(Segment)
12176       .addReg(NextOffsetReg)
12177       .setMemRefs(MMOBegin, MMOEnd);
12178
12179     // Jump to endMBB
12180     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12181       .addMBB(endMBB);
12182   }
12183
12184   //
12185   // Emit code to use overflow area
12186   //
12187
12188   // Load the overflow_area address into a register.
12189   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12190   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12191     .addOperand(Base)
12192     .addOperand(Scale)
12193     .addOperand(Index)
12194     .addDisp(Disp, 8)
12195     .addOperand(Segment)
12196     .setMemRefs(MMOBegin, MMOEnd);
12197
12198   // If we need to align it, do so. Otherwise, just copy the address
12199   // to OverflowDestReg.
12200   if (NeedsAlign) {
12201     // Align the overflow address
12202     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12203     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12204
12205     // aligned_addr = (addr + (align-1)) & ~(align-1)
12206     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12207       .addReg(OverflowAddrReg)
12208       .addImm(Align-1);
12209
12210     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12211       .addReg(TmpReg)
12212       .addImm(~(uint64_t)(Align-1));
12213   } else {
12214     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12215       .addReg(OverflowAddrReg);
12216   }
12217
12218   // Compute the next overflow address after this argument.
12219   // (the overflow address should be kept 8-byte aligned)
12220   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12221   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12222     .addReg(OverflowDestReg)
12223     .addImm(ArgSizeA8);
12224
12225   // Store the new overflow address.
12226   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12227     .addOperand(Base)
12228     .addOperand(Scale)
12229     .addOperand(Index)
12230     .addDisp(Disp, 8)
12231     .addOperand(Segment)
12232     .addReg(NextAddrReg)
12233     .setMemRefs(MMOBegin, MMOEnd);
12234
12235   // If we branched, emit the PHI to the front of endMBB.
12236   if (offsetMBB) {
12237     BuildMI(*endMBB, endMBB->begin(), DL,
12238             TII->get(X86::PHI), DestReg)
12239       .addReg(OffsetDestReg).addMBB(offsetMBB)
12240       .addReg(OverflowDestReg).addMBB(overflowMBB);
12241   }
12242
12243   // Erase the pseudo instruction
12244   MI->eraseFromParent();
12245
12246   return endMBB;
12247 }
12248
12249 MachineBasicBlock *
12250 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12251                                                  MachineInstr *MI,
12252                                                  MachineBasicBlock *MBB) const {
12253   // Emit code to save XMM registers to the stack. The ABI says that the
12254   // number of registers to save is given in %al, so it's theoretically
12255   // possible to do an indirect jump trick to avoid saving all of them,
12256   // however this code takes a simpler approach and just executes all
12257   // of the stores if %al is non-zero. It's less code, and it's probably
12258   // easier on the hardware branch predictor, and stores aren't all that
12259   // expensive anyway.
12260
12261   // Create the new basic blocks. One block contains all the XMM stores,
12262   // and one block is the final destination regardless of whether any
12263   // stores were performed.
12264   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12265   MachineFunction *F = MBB->getParent();
12266   MachineFunction::iterator MBBIter = MBB;
12267   ++MBBIter;
12268   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12269   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12270   F->insert(MBBIter, XMMSaveMBB);
12271   F->insert(MBBIter, EndMBB);
12272
12273   // Transfer the remainder of MBB and its successor edges to EndMBB.
12274   EndMBB->splice(EndMBB->begin(), MBB,
12275                  llvm::next(MachineBasicBlock::iterator(MI)),
12276                  MBB->end());
12277   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12278
12279   // The original block will now fall through to the XMM save block.
12280   MBB->addSuccessor(XMMSaveMBB);
12281   // The XMMSaveMBB will fall through to the end block.
12282   XMMSaveMBB->addSuccessor(EndMBB);
12283
12284   // Now add the instructions.
12285   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12286   DebugLoc DL = MI->getDebugLoc();
12287
12288   unsigned CountReg = MI->getOperand(0).getReg();
12289   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12290   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12291
12292   if (!Subtarget->isTargetWin64()) {
12293     // If %al is 0, branch around the XMM save block.
12294     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12295     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12296     MBB->addSuccessor(EndMBB);
12297   }
12298
12299   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12300   // In the XMM save block, save all the XMM argument registers.
12301   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12302     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12303     MachineMemOperand *MMO =
12304       F->getMachineMemOperand(
12305           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12306         MachineMemOperand::MOStore,
12307         /*Size=*/16, /*Align=*/16);
12308     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12309       .addFrameIndex(RegSaveFrameIndex)
12310       .addImm(/*Scale=*/1)
12311       .addReg(/*IndexReg=*/0)
12312       .addImm(/*Disp=*/Offset)
12313       .addReg(/*Segment=*/0)
12314       .addReg(MI->getOperand(i).getReg())
12315       .addMemOperand(MMO);
12316   }
12317
12318   MI->eraseFromParent();   // The pseudo instruction is gone now.
12319
12320   return EndMBB;
12321 }
12322
12323 // The EFLAGS operand of SelectItr might be missing a kill marker
12324 // because there were multiple uses of EFLAGS, and ISel didn't know
12325 // which to mark. Figure out whether SelectItr should have had a
12326 // kill marker, and set it if it should. Returns the correct kill
12327 // marker value.
12328 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12329                                      MachineBasicBlock* BB,
12330                                      const TargetRegisterInfo* TRI) {
12331   // Scan forward through BB for a use/def of EFLAGS.
12332   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12333   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12334     const MachineInstr& mi = *miI;
12335     if (mi.readsRegister(X86::EFLAGS))
12336       return false;
12337     if (mi.definesRegister(X86::EFLAGS))
12338       break; // Should have kill-flag - update below.
12339   }
12340
12341   // If we hit the end of the block, check whether EFLAGS is live into a
12342   // successor.
12343   if (miI == BB->end()) {
12344     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12345                                           sEnd = BB->succ_end();
12346          sItr != sEnd; ++sItr) {
12347       MachineBasicBlock* succ = *sItr;
12348       if (succ->isLiveIn(X86::EFLAGS))
12349         return false;
12350     }
12351   }
12352
12353   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12354   // out. SelectMI should have a kill flag on EFLAGS.
12355   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12356   return true;
12357 }
12358
12359 MachineBasicBlock *
12360 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12361                                      MachineBasicBlock *BB) const {
12362   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12363   DebugLoc DL = MI->getDebugLoc();
12364
12365   // To "insert" a SELECT_CC instruction, we actually have to insert the
12366   // diamond control-flow pattern.  The incoming instruction knows the
12367   // destination vreg to set, the condition code register to branch on, the
12368   // true/false values to select between, and a branch opcode to use.
12369   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12370   MachineFunction::iterator It = BB;
12371   ++It;
12372
12373   //  thisMBB:
12374   //  ...
12375   //   TrueVal = ...
12376   //   cmpTY ccX, r1, r2
12377   //   bCC copy1MBB
12378   //   fallthrough --> copy0MBB
12379   MachineBasicBlock *thisMBB = BB;
12380   MachineFunction *F = BB->getParent();
12381   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12382   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12383   F->insert(It, copy0MBB);
12384   F->insert(It, sinkMBB);
12385
12386   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12387   // live into the sink and copy blocks.
12388   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12389   if (!MI->killsRegister(X86::EFLAGS) &&
12390       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12391     copy0MBB->addLiveIn(X86::EFLAGS);
12392     sinkMBB->addLiveIn(X86::EFLAGS);
12393   }
12394
12395   // Transfer the remainder of BB and its successor edges to sinkMBB.
12396   sinkMBB->splice(sinkMBB->begin(), BB,
12397                   llvm::next(MachineBasicBlock::iterator(MI)),
12398                   BB->end());
12399   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12400
12401   // Add the true and fallthrough blocks as its successors.
12402   BB->addSuccessor(copy0MBB);
12403   BB->addSuccessor(sinkMBB);
12404
12405   // Create the conditional branch instruction.
12406   unsigned Opc =
12407     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12408   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12409
12410   //  copy0MBB:
12411   //   %FalseValue = ...
12412   //   # fallthrough to sinkMBB
12413   copy0MBB->addSuccessor(sinkMBB);
12414
12415   //  sinkMBB:
12416   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12417   //  ...
12418   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12419           TII->get(X86::PHI), MI->getOperand(0).getReg())
12420     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12421     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12422
12423   MI->eraseFromParent();   // The pseudo instruction is gone now.
12424   return sinkMBB;
12425 }
12426
12427 MachineBasicBlock *
12428 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12429                                         bool Is64Bit) const {
12430   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12431   DebugLoc DL = MI->getDebugLoc();
12432   MachineFunction *MF = BB->getParent();
12433   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12434
12435   assert(getTargetMachine().Options.EnableSegmentedStacks);
12436
12437   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12438   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12439
12440   // BB:
12441   //  ... [Till the alloca]
12442   // If stacklet is not large enough, jump to mallocMBB
12443   //
12444   // bumpMBB:
12445   //  Allocate by subtracting from RSP
12446   //  Jump to continueMBB
12447   //
12448   // mallocMBB:
12449   //  Allocate by call to runtime
12450   //
12451   // continueMBB:
12452   //  ...
12453   //  [rest of original BB]
12454   //
12455
12456   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12457   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12458   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12459
12460   MachineRegisterInfo &MRI = MF->getRegInfo();
12461   const TargetRegisterClass *AddrRegClass =
12462     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12463
12464   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12465     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12466     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12467     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12468     sizeVReg = MI->getOperand(1).getReg(),
12469     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12470
12471   MachineFunction::iterator MBBIter = BB;
12472   ++MBBIter;
12473
12474   MF->insert(MBBIter, bumpMBB);
12475   MF->insert(MBBIter, mallocMBB);
12476   MF->insert(MBBIter, continueMBB);
12477
12478   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12479                       (MachineBasicBlock::iterator(MI)), BB->end());
12480   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12481
12482   // Add code to the main basic block to check if the stack limit has been hit,
12483   // and if so, jump to mallocMBB otherwise to bumpMBB.
12484   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12485   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12486     .addReg(tmpSPVReg).addReg(sizeVReg);
12487   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12488     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12489     .addReg(SPLimitVReg);
12490   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12491
12492   // bumpMBB simply decreases the stack pointer, since we know the current
12493   // stacklet has enough space.
12494   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12495     .addReg(SPLimitVReg);
12496   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12497     .addReg(SPLimitVReg);
12498   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12499
12500   // Calls into a routine in libgcc to allocate more space from the heap.
12501   const uint32_t *RegMask =
12502     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12503   if (Is64Bit) {
12504     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12505       .addReg(sizeVReg);
12506     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12507       .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI)
12508       .addRegMask(RegMask)
12509       .addReg(X86::RAX, RegState::ImplicitDefine);
12510   } else {
12511     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12512       .addImm(12);
12513     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12514     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12515       .addExternalSymbol("__morestack_allocate_stack_space")
12516       .addRegMask(RegMask)
12517       .addReg(X86::EAX, RegState::ImplicitDefine);
12518   }
12519
12520   if (!Is64Bit)
12521     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12522       .addImm(16);
12523
12524   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12525     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12526   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12527
12528   // Set up the CFG correctly.
12529   BB->addSuccessor(bumpMBB);
12530   BB->addSuccessor(mallocMBB);
12531   mallocMBB->addSuccessor(continueMBB);
12532   bumpMBB->addSuccessor(continueMBB);
12533
12534   // Take care of the PHI nodes.
12535   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12536           MI->getOperand(0).getReg())
12537     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12538     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12539
12540   // Delete the original pseudo instruction.
12541   MI->eraseFromParent();
12542
12543   // And we're done.
12544   return continueMBB;
12545 }
12546
12547 MachineBasicBlock *
12548 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12549                                           MachineBasicBlock *BB) const {
12550   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12551   DebugLoc DL = MI->getDebugLoc();
12552
12553   assert(!Subtarget->isTargetEnvMacho());
12554
12555   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12556   // non-trivial part is impdef of ESP.
12557
12558   if (Subtarget->isTargetWin64()) {
12559     if (Subtarget->isTargetCygMing()) {
12560       // ___chkstk(Mingw64):
12561       // Clobbers R10, R11, RAX and EFLAGS.
12562       // Updates RSP.
12563       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12564         .addExternalSymbol("___chkstk")
12565         .addReg(X86::RAX, RegState::Implicit)
12566         .addReg(X86::RSP, RegState::Implicit)
12567         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12568         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12569         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12570     } else {
12571       // __chkstk(MSVCRT): does not update stack pointer.
12572       // Clobbers R10, R11 and EFLAGS.
12573       // FIXME: RAX(allocated size) might be reused and not killed.
12574       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12575         .addExternalSymbol("__chkstk")
12576         .addReg(X86::RAX, RegState::Implicit)
12577         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12578       // RAX has the offset to subtracted from RSP.
12579       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12580         .addReg(X86::RSP)
12581         .addReg(X86::RAX);
12582     }
12583   } else {
12584     const char *StackProbeSymbol =
12585       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12586
12587     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12588       .addExternalSymbol(StackProbeSymbol)
12589       .addReg(X86::EAX, RegState::Implicit)
12590       .addReg(X86::ESP, RegState::Implicit)
12591       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12592       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12593       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12594   }
12595
12596   MI->eraseFromParent();   // The pseudo instruction is gone now.
12597   return BB;
12598 }
12599
12600 MachineBasicBlock *
12601 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12602                                       MachineBasicBlock *BB) const {
12603   // This is pretty easy.  We're taking the value that we received from
12604   // our load from the relocation, sticking it in either RDI (x86-64)
12605   // or EAX and doing an indirect call.  The return value will then
12606   // be in the normal return register.
12607   const X86InstrInfo *TII
12608     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12609   DebugLoc DL = MI->getDebugLoc();
12610   MachineFunction *F = BB->getParent();
12611
12612   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12613   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12614
12615   // Get a register mask for the lowered call.
12616   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12617   // proper register mask.
12618   const uint32_t *RegMask =
12619     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12620   if (Subtarget->is64Bit()) {
12621     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12622                                       TII->get(X86::MOV64rm), X86::RDI)
12623     .addReg(X86::RIP)
12624     .addImm(0).addReg(0)
12625     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12626                       MI->getOperand(3).getTargetFlags())
12627     .addReg(0);
12628     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12629     addDirectMem(MIB, X86::RDI);
12630     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12631   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12632     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12633                                       TII->get(X86::MOV32rm), X86::EAX)
12634     .addReg(0)
12635     .addImm(0).addReg(0)
12636     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12637                       MI->getOperand(3).getTargetFlags())
12638     .addReg(0);
12639     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12640     addDirectMem(MIB, X86::EAX);
12641     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12642   } else {
12643     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12644                                       TII->get(X86::MOV32rm), X86::EAX)
12645     .addReg(TII->getGlobalBaseReg(F))
12646     .addImm(0).addReg(0)
12647     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12648                       MI->getOperand(3).getTargetFlags())
12649     .addReg(0);
12650     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12651     addDirectMem(MIB, X86::EAX);
12652     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12653   }
12654
12655   MI->eraseFromParent(); // The pseudo instruction is gone now.
12656   return BB;
12657 }
12658
12659 MachineBasicBlock *
12660 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12661                                                MachineBasicBlock *BB) const {
12662   switch (MI->getOpcode()) {
12663   default: llvm_unreachable("Unexpected instr type to insert");
12664   case X86::TAILJMPd64:
12665   case X86::TAILJMPr64:
12666   case X86::TAILJMPm64:
12667     llvm_unreachable("TAILJMP64 would not be touched here.");
12668   case X86::TCRETURNdi64:
12669   case X86::TCRETURNri64:
12670   case X86::TCRETURNmi64:
12671     return BB;
12672   case X86::WIN_ALLOCA:
12673     return EmitLoweredWinAlloca(MI, BB);
12674   case X86::SEG_ALLOCA_32:
12675     return EmitLoweredSegAlloca(MI, BB, false);
12676   case X86::SEG_ALLOCA_64:
12677     return EmitLoweredSegAlloca(MI, BB, true);
12678   case X86::TLSCall_32:
12679   case X86::TLSCall_64:
12680     return EmitLoweredTLSCall(MI, BB);
12681   case X86::CMOV_GR8:
12682   case X86::CMOV_FR32:
12683   case X86::CMOV_FR64:
12684   case X86::CMOV_V4F32:
12685   case X86::CMOV_V2F64:
12686   case X86::CMOV_V2I64:
12687   case X86::CMOV_V8F32:
12688   case X86::CMOV_V4F64:
12689   case X86::CMOV_V4I64:
12690   case X86::CMOV_GR16:
12691   case X86::CMOV_GR32:
12692   case X86::CMOV_RFP32:
12693   case X86::CMOV_RFP64:
12694   case X86::CMOV_RFP80:
12695     return EmitLoweredSelect(MI, BB);
12696
12697   case X86::FP32_TO_INT16_IN_MEM:
12698   case X86::FP32_TO_INT32_IN_MEM:
12699   case X86::FP32_TO_INT64_IN_MEM:
12700   case X86::FP64_TO_INT16_IN_MEM:
12701   case X86::FP64_TO_INT32_IN_MEM:
12702   case X86::FP64_TO_INT64_IN_MEM:
12703   case X86::FP80_TO_INT16_IN_MEM:
12704   case X86::FP80_TO_INT32_IN_MEM:
12705   case X86::FP80_TO_INT64_IN_MEM: {
12706     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12707     DebugLoc DL = MI->getDebugLoc();
12708
12709     // Change the floating point control register to use "round towards zero"
12710     // mode when truncating to an integer value.
12711     MachineFunction *F = BB->getParent();
12712     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12713     addFrameReference(BuildMI(*BB, MI, DL,
12714                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12715
12716     // Load the old value of the high byte of the control word...
12717     unsigned OldCW =
12718       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12719     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12720                       CWFrameIdx);
12721
12722     // Set the high part to be round to zero...
12723     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12724       .addImm(0xC7F);
12725
12726     // Reload the modified control word now...
12727     addFrameReference(BuildMI(*BB, MI, DL,
12728                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12729
12730     // Restore the memory image of control word to original value
12731     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12732       .addReg(OldCW);
12733
12734     // Get the X86 opcode to use.
12735     unsigned Opc;
12736     switch (MI->getOpcode()) {
12737     default: llvm_unreachable("illegal opcode!");
12738     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12739     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12740     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12741     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12742     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12743     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12744     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12745     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12746     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12747     }
12748
12749     X86AddressMode AM;
12750     MachineOperand &Op = MI->getOperand(0);
12751     if (Op.isReg()) {
12752       AM.BaseType = X86AddressMode::RegBase;
12753       AM.Base.Reg = Op.getReg();
12754     } else {
12755       AM.BaseType = X86AddressMode::FrameIndexBase;
12756       AM.Base.FrameIndex = Op.getIndex();
12757     }
12758     Op = MI->getOperand(1);
12759     if (Op.isImm())
12760       AM.Scale = Op.getImm();
12761     Op = MI->getOperand(2);
12762     if (Op.isImm())
12763       AM.IndexReg = Op.getImm();
12764     Op = MI->getOperand(3);
12765     if (Op.isGlobal()) {
12766       AM.GV = Op.getGlobal();
12767     } else {
12768       AM.Disp = Op.getImm();
12769     }
12770     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12771                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12772
12773     // Reload the original control word now.
12774     addFrameReference(BuildMI(*BB, MI, DL,
12775                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12776
12777     MI->eraseFromParent();   // The pseudo instruction is gone now.
12778     return BB;
12779   }
12780     // String/text processing lowering.
12781   case X86::PCMPISTRM128REG:
12782   case X86::VPCMPISTRM128REG:
12783     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12784   case X86::PCMPISTRM128MEM:
12785   case X86::VPCMPISTRM128MEM:
12786     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12787   case X86::PCMPESTRM128REG:
12788   case X86::VPCMPESTRM128REG:
12789     return EmitPCMP(MI, BB, 5, false /* in mem */);
12790   case X86::PCMPESTRM128MEM:
12791   case X86::VPCMPESTRM128MEM:
12792     return EmitPCMP(MI, BB, 5, true /* in mem */);
12793
12794     // Thread synchronization.
12795   case X86::MONITOR:
12796     return EmitMonitor(MI, BB);
12797   case X86::MWAIT:
12798     return EmitMwait(MI, BB);
12799
12800     // Atomic Lowering.
12801   case X86::ATOMAND32:
12802     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12803                                                X86::AND32ri, X86::MOV32rm,
12804                                                X86::LCMPXCHG32,
12805                                                X86::NOT32r, X86::EAX,
12806                                                &X86::GR32RegClass);
12807   case X86::ATOMOR32:
12808     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12809                                                X86::OR32ri, X86::MOV32rm,
12810                                                X86::LCMPXCHG32,
12811                                                X86::NOT32r, X86::EAX,
12812                                                &X86::GR32RegClass);
12813   case X86::ATOMXOR32:
12814     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12815                                                X86::XOR32ri, X86::MOV32rm,
12816                                                X86::LCMPXCHG32,
12817                                                X86::NOT32r, X86::EAX,
12818                                                &X86::GR32RegClass);
12819   case X86::ATOMNAND32:
12820     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12821                                                X86::AND32ri, X86::MOV32rm,
12822                                                X86::LCMPXCHG32,
12823                                                X86::NOT32r, X86::EAX,
12824                                                &X86::GR32RegClass, true);
12825   case X86::ATOMMIN32:
12826     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12827   case X86::ATOMMAX32:
12828     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12829   case X86::ATOMUMIN32:
12830     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12831   case X86::ATOMUMAX32:
12832     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12833
12834   case X86::ATOMAND16:
12835     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12836                                                X86::AND16ri, X86::MOV16rm,
12837                                                X86::LCMPXCHG16,
12838                                                X86::NOT16r, X86::AX,
12839                                                &X86::GR16RegClass);
12840   case X86::ATOMOR16:
12841     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12842                                                X86::OR16ri, X86::MOV16rm,
12843                                                X86::LCMPXCHG16,
12844                                                X86::NOT16r, X86::AX,
12845                                                &X86::GR16RegClass);
12846   case X86::ATOMXOR16:
12847     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12848                                                X86::XOR16ri, X86::MOV16rm,
12849                                                X86::LCMPXCHG16,
12850                                                X86::NOT16r, X86::AX,
12851                                                &X86::GR16RegClass);
12852   case X86::ATOMNAND16:
12853     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12854                                                X86::AND16ri, X86::MOV16rm,
12855                                                X86::LCMPXCHG16,
12856                                                X86::NOT16r, X86::AX,
12857                                                &X86::GR16RegClass, true);
12858   case X86::ATOMMIN16:
12859     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12860   case X86::ATOMMAX16:
12861     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12862   case X86::ATOMUMIN16:
12863     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12864   case X86::ATOMUMAX16:
12865     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12866
12867   case X86::ATOMAND8:
12868     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12869                                                X86::AND8ri, X86::MOV8rm,
12870                                                X86::LCMPXCHG8,
12871                                                X86::NOT8r, X86::AL,
12872                                                &X86::GR8RegClass);
12873   case X86::ATOMOR8:
12874     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12875                                                X86::OR8ri, X86::MOV8rm,
12876                                                X86::LCMPXCHG8,
12877                                                X86::NOT8r, X86::AL,
12878                                                &X86::GR8RegClass);
12879   case X86::ATOMXOR8:
12880     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12881                                                X86::XOR8ri, X86::MOV8rm,
12882                                                X86::LCMPXCHG8,
12883                                                X86::NOT8r, X86::AL,
12884                                                &X86::GR8RegClass);
12885   case X86::ATOMNAND8:
12886     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12887                                                X86::AND8ri, X86::MOV8rm,
12888                                                X86::LCMPXCHG8,
12889                                                X86::NOT8r, X86::AL,
12890                                                &X86::GR8RegClass, true);
12891   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12892   // This group is for 64-bit host.
12893   case X86::ATOMAND64:
12894     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12895                                                X86::AND64ri32, X86::MOV64rm,
12896                                                X86::LCMPXCHG64,
12897                                                X86::NOT64r, X86::RAX,
12898                                                &X86::GR64RegClass);
12899   case X86::ATOMOR64:
12900     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12901                                                X86::OR64ri32, X86::MOV64rm,
12902                                                X86::LCMPXCHG64,
12903                                                X86::NOT64r, X86::RAX,
12904                                                &X86::GR64RegClass);
12905   case X86::ATOMXOR64:
12906     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12907                                                X86::XOR64ri32, X86::MOV64rm,
12908                                                X86::LCMPXCHG64,
12909                                                X86::NOT64r, X86::RAX,
12910                                                &X86::GR64RegClass);
12911   case X86::ATOMNAND64:
12912     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12913                                                X86::AND64ri32, X86::MOV64rm,
12914                                                X86::LCMPXCHG64,
12915                                                X86::NOT64r, X86::RAX,
12916                                                &X86::GR64RegClass, true);
12917   case X86::ATOMMIN64:
12918     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12919   case X86::ATOMMAX64:
12920     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12921   case X86::ATOMUMIN64:
12922     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12923   case X86::ATOMUMAX64:
12924     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12925
12926   // This group does 64-bit operations on a 32-bit host.
12927   case X86::ATOMAND6432:
12928     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12929                                                X86::AND32rr, X86::AND32rr,
12930                                                X86::AND32ri, X86::AND32ri,
12931                                                false);
12932   case X86::ATOMOR6432:
12933     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12934                                                X86::OR32rr, X86::OR32rr,
12935                                                X86::OR32ri, X86::OR32ri,
12936                                                false);
12937   case X86::ATOMXOR6432:
12938     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12939                                                X86::XOR32rr, X86::XOR32rr,
12940                                                X86::XOR32ri, X86::XOR32ri,
12941                                                false);
12942   case X86::ATOMNAND6432:
12943     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12944                                                X86::AND32rr, X86::AND32rr,
12945                                                X86::AND32ri, X86::AND32ri,
12946                                                true);
12947   case X86::ATOMADD6432:
12948     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12949                                                X86::ADD32rr, X86::ADC32rr,
12950                                                X86::ADD32ri, X86::ADC32ri,
12951                                                false);
12952   case X86::ATOMSUB6432:
12953     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12954                                                X86::SUB32rr, X86::SBB32rr,
12955                                                X86::SUB32ri, X86::SBB32ri,
12956                                                false);
12957   case X86::ATOMSWAP6432:
12958     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12959                                                X86::MOV32rr, X86::MOV32rr,
12960                                                X86::MOV32ri, X86::MOV32ri,
12961                                                false);
12962   case X86::VASTART_SAVE_XMM_REGS:
12963     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12964
12965   case X86::VAARG_64:
12966     return EmitVAARG64WithCustomInserter(MI, BB);
12967   }
12968 }
12969
12970 //===----------------------------------------------------------------------===//
12971 //                           X86 Optimization Hooks
12972 //===----------------------------------------------------------------------===//
12973
12974 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12975                                                        APInt &KnownZero,
12976                                                        APInt &KnownOne,
12977                                                        const SelectionDAG &DAG,
12978                                                        unsigned Depth) const {
12979   unsigned BitWidth = KnownZero.getBitWidth();
12980   unsigned Opc = Op.getOpcode();
12981   assert((Opc >= ISD::BUILTIN_OP_END ||
12982           Opc == ISD::INTRINSIC_WO_CHAIN ||
12983           Opc == ISD::INTRINSIC_W_CHAIN ||
12984           Opc == ISD::INTRINSIC_VOID) &&
12985          "Should use MaskedValueIsZero if you don't know whether Op"
12986          " is a target node!");
12987
12988   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
12989   switch (Opc) {
12990   default: break;
12991   case X86ISD::ADD:
12992   case X86ISD::SUB:
12993   case X86ISD::ADC:
12994   case X86ISD::SBB:
12995   case X86ISD::SMUL:
12996   case X86ISD::UMUL:
12997   case X86ISD::INC:
12998   case X86ISD::DEC:
12999   case X86ISD::OR:
13000   case X86ISD::XOR:
13001   case X86ISD::AND:
13002     // These nodes' second result is a boolean.
13003     if (Op.getResNo() == 0)
13004       break;
13005     // Fallthrough
13006   case X86ISD::SETCC:
13007     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13008     break;
13009   case ISD::INTRINSIC_WO_CHAIN: {
13010     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13011     unsigned NumLoBits = 0;
13012     switch (IntId) {
13013     default: break;
13014     case Intrinsic::x86_sse_movmsk_ps:
13015     case Intrinsic::x86_avx_movmsk_ps_256:
13016     case Intrinsic::x86_sse2_movmsk_pd:
13017     case Intrinsic::x86_avx_movmsk_pd_256:
13018     case Intrinsic::x86_mmx_pmovmskb:
13019     case Intrinsic::x86_sse2_pmovmskb_128:
13020     case Intrinsic::x86_avx2_pmovmskb: {
13021       // High bits of movmskp{s|d}, pmovmskb are known zero.
13022       switch (IntId) {
13023         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13024         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13025         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13026         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13027         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13028         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13029         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13030         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13031       }
13032       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13033       break;
13034     }
13035     }
13036     break;
13037   }
13038   }
13039 }
13040
13041 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13042                                                          unsigned Depth) const {
13043   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13044   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13045     return Op.getValueType().getScalarType().getSizeInBits();
13046
13047   // Fallback case.
13048   return 1;
13049 }
13050
13051 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13052 /// node is a GlobalAddress + offset.
13053 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13054                                        const GlobalValue* &GA,
13055                                        int64_t &Offset) const {
13056   if (N->getOpcode() == X86ISD::Wrapper) {
13057     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13058       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13059       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13060       return true;
13061     }
13062   }
13063   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13064 }
13065
13066 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13067 /// same as extracting the high 128-bit part of 256-bit vector and then
13068 /// inserting the result into the low part of a new 256-bit vector
13069 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13070   EVT VT = SVOp->getValueType(0);
13071   unsigned NumElems = VT.getVectorNumElements();
13072
13073   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13074   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13075     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13076         SVOp->getMaskElt(j) >= 0)
13077       return false;
13078
13079   return true;
13080 }
13081
13082 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13083 /// same as extracting the low 128-bit part of 256-bit vector and then
13084 /// inserting the result into the high part of a new 256-bit vector
13085 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13086   EVT VT = SVOp->getValueType(0);
13087   unsigned NumElems = VT.getVectorNumElements();
13088
13089   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13090   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13091     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13092         SVOp->getMaskElt(j) >= 0)
13093       return false;
13094
13095   return true;
13096 }
13097
13098 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13099 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13100                                         TargetLowering::DAGCombinerInfo &DCI,
13101                                         const X86Subtarget* Subtarget) {
13102   DebugLoc dl = N->getDebugLoc();
13103   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13104   SDValue V1 = SVOp->getOperand(0);
13105   SDValue V2 = SVOp->getOperand(1);
13106   EVT VT = SVOp->getValueType(0);
13107   unsigned NumElems = VT.getVectorNumElements();
13108
13109   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13110       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13111     //
13112     //                   0,0,0,...
13113     //                      |
13114     //    V      UNDEF    BUILD_VECTOR    UNDEF
13115     //     \      /           \           /
13116     //  CONCAT_VECTOR         CONCAT_VECTOR
13117     //         \                  /
13118     //          \                /
13119     //          RESULT: V + zero extended
13120     //
13121     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13122         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13123         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13124       return SDValue();
13125
13126     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13127       return SDValue();
13128
13129     // To match the shuffle mask, the first half of the mask should
13130     // be exactly the first vector, and all the rest a splat with the
13131     // first element of the second one.
13132     for (unsigned i = 0; i != NumElems/2; ++i)
13133       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13134           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13135         return SDValue();
13136
13137     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13138     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13139       if (Ld->hasNUsesOfValue(1, 0)) {
13140         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13141         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13142         SDValue ResNode =
13143           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13144                                   Ld->getMemoryVT(),
13145                                   Ld->getPointerInfo(),
13146                                   Ld->getAlignment(),
13147                                   false/*isVolatile*/, true/*ReadMem*/,
13148                                   false/*WriteMem*/);
13149         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13150       }
13151     } 
13152
13153     // Emit a zeroed vector and insert the desired subvector on its
13154     // first half.
13155     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13156     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13157     return DCI.CombineTo(N, InsV);
13158   }
13159
13160   //===--------------------------------------------------------------------===//
13161   // Combine some shuffles into subvector extracts and inserts:
13162   //
13163
13164   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13165   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13166     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13167     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13168     return DCI.CombineTo(N, InsV);
13169   }
13170
13171   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13172   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13173     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13174     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13175     return DCI.CombineTo(N, InsV);
13176   }
13177
13178   return SDValue();
13179 }
13180
13181 /// PerformShuffleCombine - Performs several different shuffle combines.
13182 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13183                                      TargetLowering::DAGCombinerInfo &DCI,
13184                                      const X86Subtarget *Subtarget) {
13185   DebugLoc dl = N->getDebugLoc();
13186   EVT VT = N->getValueType(0);
13187
13188   // Don't create instructions with illegal types after legalize types has run.
13189   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13190   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13191     return SDValue();
13192
13193   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13194   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13195       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13196     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13197
13198   // Only handle 128 wide vector from here on.
13199   if (VT.getSizeInBits() != 128)
13200     return SDValue();
13201
13202   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13203   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13204   // consecutive, non-overlapping, and in the right order.
13205   SmallVector<SDValue, 16> Elts;
13206   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13207     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13208
13209   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13210 }
13211
13212
13213 /// DCI, PerformTruncateCombine - Converts truncate operation to
13214 /// a sequence of vector shuffle operations.
13215 /// It is possible when we truncate 256-bit vector to 128-bit vector
13216
13217 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG, 
13218                                                   DAGCombinerInfo &DCI) const {
13219   if (!DCI.isBeforeLegalizeOps())
13220     return SDValue();
13221
13222   if (!Subtarget->hasAVX())
13223     return SDValue();
13224
13225   EVT VT = N->getValueType(0);
13226   SDValue Op = N->getOperand(0);
13227   EVT OpVT = Op.getValueType();
13228   DebugLoc dl = N->getDebugLoc();
13229
13230   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13231
13232     if (Subtarget->hasAVX2()) {
13233       // AVX2: v4i64 -> v4i32
13234
13235       // VPERMD
13236       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13237
13238       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13239       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13240                                 ShufMask);
13241
13242       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13243                          DAG.getIntPtrConstant(0));
13244     }
13245
13246     // AVX: v4i64 -> v4i32
13247     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13248                                DAG.getIntPtrConstant(0));
13249
13250     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13251                                DAG.getIntPtrConstant(2));
13252
13253     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13254     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13255
13256     // PSHUFD
13257     static const int ShufMask1[] = {0, 2, 0, 0};
13258
13259     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1);
13260     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1);
13261
13262     // MOVLHPS
13263     static const int ShufMask2[] = {0, 1, 4, 5};
13264
13265     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13266   }
13267
13268   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13269
13270     if (Subtarget->hasAVX2()) {
13271       // AVX2: v8i32 -> v8i16
13272
13273       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13274
13275       // PSHUFB
13276       SmallVector<SDValue,32> pshufbMask;
13277       for (unsigned i = 0; i < 2; ++i) {
13278         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13279         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13280         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13281         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13282         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13283         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13284         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13285         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13286         for (unsigned j = 0; j < 8; ++j)
13287           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13288       }
13289       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13290                                &pshufbMask[0], 32);
13291       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13292
13293       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13294
13295       static const int ShufMask[] = {0,  2,  -1,  -1};
13296       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13297                                 &ShufMask[0]);
13298
13299       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13300                        DAG.getIntPtrConstant(0));
13301
13302       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13303     }
13304
13305     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13306                                DAG.getIntPtrConstant(0));
13307
13308     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13309                                DAG.getIntPtrConstant(4));
13310
13311     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13312     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13313
13314     // PSHUFB
13315     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13316                                    -1, -1, -1, -1, -1, -1, -1, -1};
13317
13318     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8),
13319                                 ShufMask1);
13320     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8),
13321                                 ShufMask1);
13322
13323     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13324     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13325
13326     // MOVLHPS
13327     static const int ShufMask2[] = {0, 1, 4, 5};
13328
13329     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13330     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13331   }
13332
13333   return SDValue();
13334 }
13335
13336 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13337 /// specific shuffle of a load can be folded into a single element load.
13338 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13339 /// shuffles have been customed lowered so we need to handle those here.
13340 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13341                                          TargetLowering::DAGCombinerInfo &DCI) {
13342   if (DCI.isBeforeLegalizeOps())
13343     return SDValue();
13344
13345   SDValue InVec = N->getOperand(0);
13346   SDValue EltNo = N->getOperand(1);
13347
13348   if (!isa<ConstantSDNode>(EltNo))
13349     return SDValue();
13350
13351   EVT VT = InVec.getValueType();
13352
13353   bool HasShuffleIntoBitcast = false;
13354   if (InVec.getOpcode() == ISD::BITCAST) {
13355     // Don't duplicate a load with other uses.
13356     if (!InVec.hasOneUse())
13357       return SDValue();
13358     EVT BCVT = InVec.getOperand(0).getValueType();
13359     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13360       return SDValue();
13361     InVec = InVec.getOperand(0);
13362     HasShuffleIntoBitcast = true;
13363   }
13364
13365   if (!isTargetShuffle(InVec.getOpcode()))
13366     return SDValue();
13367
13368   // Don't duplicate a load with other uses.
13369   if (!InVec.hasOneUse())
13370     return SDValue();
13371
13372   SmallVector<int, 16> ShuffleMask;
13373   bool UnaryShuffle;
13374   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13375                             UnaryShuffle))
13376     return SDValue();
13377
13378   // Select the input vector, guarding against out of range extract vector.
13379   unsigned NumElems = VT.getVectorNumElements();
13380   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13381   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13382   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13383                                          : InVec.getOperand(1);
13384
13385   // If inputs to shuffle are the same for both ops, then allow 2 uses
13386   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13387
13388   if (LdNode.getOpcode() == ISD::BITCAST) {
13389     // Don't duplicate a load with other uses.
13390     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13391       return SDValue();
13392
13393     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13394     LdNode = LdNode.getOperand(0);
13395   }
13396
13397   if (!ISD::isNormalLoad(LdNode.getNode()))
13398     return SDValue();
13399
13400   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13401
13402   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13403     return SDValue();
13404
13405   if (HasShuffleIntoBitcast) {
13406     // If there's a bitcast before the shuffle, check if the load type and
13407     // alignment is valid.
13408     unsigned Align = LN0->getAlignment();
13409     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13410     unsigned NewAlign = TLI.getTargetData()->
13411       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13412
13413     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13414       return SDValue();
13415   }
13416
13417   // All checks match so transform back to vector_shuffle so that DAG combiner
13418   // can finish the job
13419   DebugLoc dl = N->getDebugLoc();
13420
13421   // Create shuffle node taking into account the case that its a unary shuffle
13422   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13423   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13424                                  InVec.getOperand(0), Shuffle,
13425                                  &ShuffleMask[0]);
13426   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13427   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13428                      EltNo);
13429 }
13430
13431 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13432 /// generation and convert it from being a bunch of shuffles and extracts
13433 /// to a simple store and scalar loads to extract the elements.
13434 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13435                                          TargetLowering::DAGCombinerInfo &DCI) {
13436   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13437   if (NewOp.getNode())
13438     return NewOp;
13439
13440   SDValue InputVector = N->getOperand(0);
13441
13442   // Only operate on vectors of 4 elements, where the alternative shuffling
13443   // gets to be more expensive.
13444   if (InputVector.getValueType() != MVT::v4i32)
13445     return SDValue();
13446
13447   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13448   // single use which is a sign-extend or zero-extend, and all elements are
13449   // used.
13450   SmallVector<SDNode *, 4> Uses;
13451   unsigned ExtractedElements = 0;
13452   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13453        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13454     if (UI.getUse().getResNo() != InputVector.getResNo())
13455       return SDValue();
13456
13457     SDNode *Extract = *UI;
13458     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13459       return SDValue();
13460
13461     if (Extract->getValueType(0) != MVT::i32)
13462       return SDValue();
13463     if (!Extract->hasOneUse())
13464       return SDValue();
13465     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13466         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13467       return SDValue();
13468     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13469       return SDValue();
13470
13471     // Record which element was extracted.
13472     ExtractedElements |=
13473       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13474
13475     Uses.push_back(Extract);
13476   }
13477
13478   // If not all the elements were used, this may not be worthwhile.
13479   if (ExtractedElements != 15)
13480     return SDValue();
13481
13482   // Ok, we've now decided to do the transformation.
13483   DebugLoc dl = InputVector.getDebugLoc();
13484
13485   // Store the value to a temporary stack slot.
13486   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13487   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13488                             MachinePointerInfo(), false, false, 0);
13489
13490   // Replace each use (extract) with a load of the appropriate element.
13491   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13492        UE = Uses.end(); UI != UE; ++UI) {
13493     SDNode *Extract = *UI;
13494
13495     // cOMpute the element's address.
13496     SDValue Idx = Extract->getOperand(1);
13497     unsigned EltSize =
13498         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13499     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13500     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13501     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13502
13503     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13504                                      StackPtr, OffsetVal);
13505
13506     // Load the scalar.
13507     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13508                                      ScalarAddr, MachinePointerInfo(),
13509                                      false, false, false, 0);
13510
13511     // Replace the exact with the load.
13512     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13513   }
13514
13515   // The replacement was made in place; don't return anything.
13516   return SDValue();
13517 }
13518
13519 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13520 /// nodes.
13521 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13522                                     TargetLowering::DAGCombinerInfo &DCI,
13523                                     const X86Subtarget *Subtarget) {
13524   DebugLoc DL = N->getDebugLoc();
13525   SDValue Cond = N->getOperand(0);
13526   // Get the LHS/RHS of the select.
13527   SDValue LHS = N->getOperand(1);
13528   SDValue RHS = N->getOperand(2);
13529   EVT VT = LHS.getValueType();
13530
13531   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13532   // instructions match the semantics of the common C idiom x<y?x:y but not
13533   // x<=y?x:y, because of how they handle negative zero (which can be
13534   // ignored in unsafe-math mode).
13535   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13536       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13537       (Subtarget->hasSSE2() ||
13538        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13539     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13540
13541     unsigned Opcode = 0;
13542     // Check for x CC y ? x : y.
13543     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13544         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13545       switch (CC) {
13546       default: break;
13547       case ISD::SETULT:
13548         // Converting this to a min would handle NaNs incorrectly, and swapping
13549         // the operands would cause it to handle comparisons between positive
13550         // and negative zero incorrectly.
13551         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13552           if (!DAG.getTarget().Options.UnsafeFPMath &&
13553               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13554             break;
13555           std::swap(LHS, RHS);
13556         }
13557         Opcode = X86ISD::FMIN;
13558         break;
13559       case ISD::SETOLE:
13560         // Converting this to a min would handle comparisons between positive
13561         // and negative zero incorrectly.
13562         if (!DAG.getTarget().Options.UnsafeFPMath &&
13563             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13564           break;
13565         Opcode = X86ISD::FMIN;
13566         break;
13567       case ISD::SETULE:
13568         // Converting this to a min would handle both negative zeros and NaNs
13569         // incorrectly, but we can swap the operands to fix both.
13570         std::swap(LHS, RHS);
13571       case ISD::SETOLT:
13572       case ISD::SETLT:
13573       case ISD::SETLE:
13574         Opcode = X86ISD::FMIN;
13575         break;
13576
13577       case ISD::SETOGE:
13578         // Converting this to a max would handle comparisons between positive
13579         // and negative zero incorrectly.
13580         if (!DAG.getTarget().Options.UnsafeFPMath &&
13581             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13582           break;
13583         Opcode = X86ISD::FMAX;
13584         break;
13585       case ISD::SETUGT:
13586         // Converting this to a max would handle NaNs incorrectly, and swapping
13587         // the operands would cause it to handle comparisons between positive
13588         // and negative zero incorrectly.
13589         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13590           if (!DAG.getTarget().Options.UnsafeFPMath &&
13591               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13592             break;
13593           std::swap(LHS, RHS);
13594         }
13595         Opcode = X86ISD::FMAX;
13596         break;
13597       case ISD::SETUGE:
13598         // Converting this to a max would handle both negative zeros and NaNs
13599         // incorrectly, but we can swap the operands to fix both.
13600         std::swap(LHS, RHS);
13601       case ISD::SETOGT:
13602       case ISD::SETGT:
13603       case ISD::SETGE:
13604         Opcode = X86ISD::FMAX;
13605         break;
13606       }
13607     // Check for x CC y ? y : x -- a min/max with reversed arms.
13608     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13609                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13610       switch (CC) {
13611       default: break;
13612       case ISD::SETOGE:
13613         // Converting this to a min would handle comparisons between positive
13614         // and negative zero incorrectly, and swapping the operands would
13615         // cause it to handle NaNs incorrectly.
13616         if (!DAG.getTarget().Options.UnsafeFPMath &&
13617             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13618           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13619             break;
13620           std::swap(LHS, RHS);
13621         }
13622         Opcode = X86ISD::FMIN;
13623         break;
13624       case ISD::SETUGT:
13625         // Converting this to a min would handle NaNs incorrectly.
13626         if (!DAG.getTarget().Options.UnsafeFPMath &&
13627             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13628           break;
13629         Opcode = X86ISD::FMIN;
13630         break;
13631       case ISD::SETUGE:
13632         // Converting this to a min would handle both negative zeros and NaNs
13633         // incorrectly, but we can swap the operands to fix both.
13634         std::swap(LHS, RHS);
13635       case ISD::SETOGT:
13636       case ISD::SETGT:
13637       case ISD::SETGE:
13638         Opcode = X86ISD::FMIN;
13639         break;
13640
13641       case ISD::SETULT:
13642         // Converting this to a max would handle NaNs incorrectly.
13643         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13644           break;
13645         Opcode = X86ISD::FMAX;
13646         break;
13647       case ISD::SETOLE:
13648         // Converting this to a max would handle comparisons between positive
13649         // and negative zero incorrectly, and swapping the operands would
13650         // cause it to handle NaNs incorrectly.
13651         if (!DAG.getTarget().Options.UnsafeFPMath &&
13652             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13653           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13654             break;
13655           std::swap(LHS, RHS);
13656         }
13657         Opcode = X86ISD::FMAX;
13658         break;
13659       case ISD::SETULE:
13660         // Converting this to a max would handle both negative zeros and NaNs
13661         // incorrectly, but we can swap the operands to fix both.
13662         std::swap(LHS, RHS);
13663       case ISD::SETOLT:
13664       case ISD::SETLT:
13665       case ISD::SETLE:
13666         Opcode = X86ISD::FMAX;
13667         break;
13668       }
13669     }
13670
13671     if (Opcode)
13672       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13673   }
13674
13675   // If this is a select between two integer constants, try to do some
13676   // optimizations.
13677   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13678     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13679       // Don't do this for crazy integer types.
13680       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13681         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13682         // so that TrueC (the true value) is larger than FalseC.
13683         bool NeedsCondInvert = false;
13684
13685         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13686             // Efficiently invertible.
13687             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13688              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13689               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13690           NeedsCondInvert = true;
13691           std::swap(TrueC, FalseC);
13692         }
13693
13694         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13695         if (FalseC->getAPIntValue() == 0 &&
13696             TrueC->getAPIntValue().isPowerOf2()) {
13697           if (NeedsCondInvert) // Invert the condition if needed.
13698             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13699                                DAG.getConstant(1, Cond.getValueType()));
13700
13701           // Zero extend the condition if needed.
13702           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13703
13704           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13705           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13706                              DAG.getConstant(ShAmt, MVT::i8));
13707         }
13708
13709         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13710         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13711           if (NeedsCondInvert) // Invert the condition if needed.
13712             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13713                                DAG.getConstant(1, Cond.getValueType()));
13714
13715           // Zero extend the condition if needed.
13716           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13717                              FalseC->getValueType(0), Cond);
13718           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13719                              SDValue(FalseC, 0));
13720         }
13721
13722         // Optimize cases that will turn into an LEA instruction.  This requires
13723         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13724         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13725           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13726           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13727
13728           bool isFastMultiplier = false;
13729           if (Diff < 10) {
13730             switch ((unsigned char)Diff) {
13731               default: break;
13732               case 1:  // result = add base, cond
13733               case 2:  // result = lea base(    , cond*2)
13734               case 3:  // result = lea base(cond, cond*2)
13735               case 4:  // result = lea base(    , cond*4)
13736               case 5:  // result = lea base(cond, cond*4)
13737               case 8:  // result = lea base(    , cond*8)
13738               case 9:  // result = lea base(cond, cond*8)
13739                 isFastMultiplier = true;
13740                 break;
13741             }
13742           }
13743
13744           if (isFastMultiplier) {
13745             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13746             if (NeedsCondInvert) // Invert the condition if needed.
13747               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13748                                  DAG.getConstant(1, Cond.getValueType()));
13749
13750             // Zero extend the condition if needed.
13751             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13752                                Cond);
13753             // Scale the condition by the difference.
13754             if (Diff != 1)
13755               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13756                                  DAG.getConstant(Diff, Cond.getValueType()));
13757
13758             // Add the base if non-zero.
13759             if (FalseC->getAPIntValue() != 0)
13760               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13761                                  SDValue(FalseC, 0));
13762             return Cond;
13763           }
13764         }
13765       }
13766   }
13767
13768   // Canonicalize max and min:
13769   // (x > y) ? x : y -> (x >= y) ? x : y
13770   // (x < y) ? x : y -> (x <= y) ? x : y
13771   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13772   // the need for an extra compare
13773   // against zero. e.g.
13774   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13775   // subl   %esi, %edi
13776   // testl  %edi, %edi
13777   // movl   $0, %eax
13778   // cmovgl %edi, %eax
13779   // =>
13780   // xorl   %eax, %eax
13781   // subl   %esi, $edi
13782   // cmovsl %eax, %edi
13783   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13784       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13785       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13786     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13787     switch (CC) {
13788     default: break;
13789     case ISD::SETLT:
13790     case ISD::SETGT: {
13791       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13792       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13793                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
13794       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13795     }
13796     }
13797   }
13798
13799   // If we know that this node is legal then we know that it is going to be
13800   // matched by one of the SSE/AVX BLEND instructions. These instructions only
13801   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13802   // to simplify previous instructions.
13803   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13804   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13805       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
13806     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13807
13808     // Don't optimize vector selects that map to mask-registers.
13809     if (BitWidth == 1)
13810       return SDValue();
13811
13812     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13813     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13814
13815     APInt KnownZero, KnownOne;
13816     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13817                                           DCI.isBeforeLegalizeOps());
13818     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13819         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13820       DCI.CommitTargetLoweringOpt(TLO);
13821   }
13822
13823   return SDValue();
13824 }
13825
13826 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13827 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13828                                   TargetLowering::DAGCombinerInfo &DCI) {
13829   DebugLoc DL = N->getDebugLoc();
13830
13831   // If the flag operand isn't dead, don't touch this CMOV.
13832   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13833     return SDValue();
13834
13835   SDValue FalseOp = N->getOperand(0);
13836   SDValue TrueOp = N->getOperand(1);
13837   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13838   SDValue Cond = N->getOperand(3);
13839   if (CC == X86::COND_E || CC == X86::COND_NE) {
13840     switch (Cond.getOpcode()) {
13841     default: break;
13842     case X86ISD::BSR:
13843     case X86ISD::BSF:
13844       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13845       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13846         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13847     }
13848   }
13849
13850   // If this is a select between two integer constants, try to do some
13851   // optimizations.  Note that the operands are ordered the opposite of SELECT
13852   // operands.
13853   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13854     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13855       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13856       // larger than FalseC (the false value).
13857       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13858         CC = X86::GetOppositeBranchCondition(CC);
13859         std::swap(TrueC, FalseC);
13860       }
13861
13862       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13863       // This is efficient for any integer data type (including i8/i16) and
13864       // shift amount.
13865       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13866         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13867                            DAG.getConstant(CC, MVT::i8), Cond);
13868
13869         // Zero extend the condition if needed.
13870         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13871
13872         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13873         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13874                            DAG.getConstant(ShAmt, MVT::i8));
13875         if (N->getNumValues() == 2)  // Dead flag value?
13876           return DCI.CombineTo(N, Cond, SDValue());
13877         return Cond;
13878       }
13879
13880       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13881       // for any integer data type, including i8/i16.
13882       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13883         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13884                            DAG.getConstant(CC, MVT::i8), Cond);
13885
13886         // Zero extend the condition if needed.
13887         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13888                            FalseC->getValueType(0), Cond);
13889         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13890                            SDValue(FalseC, 0));
13891
13892         if (N->getNumValues() == 2)  // Dead flag value?
13893           return DCI.CombineTo(N, Cond, SDValue());
13894         return Cond;
13895       }
13896
13897       // Optimize cases that will turn into an LEA instruction.  This requires
13898       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13899       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13900         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13901         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13902
13903         bool isFastMultiplier = false;
13904         if (Diff < 10) {
13905           switch ((unsigned char)Diff) {
13906           default: break;
13907           case 1:  // result = add base, cond
13908           case 2:  // result = lea base(    , cond*2)
13909           case 3:  // result = lea base(cond, cond*2)
13910           case 4:  // result = lea base(    , cond*4)
13911           case 5:  // result = lea base(cond, cond*4)
13912           case 8:  // result = lea base(    , cond*8)
13913           case 9:  // result = lea base(cond, cond*8)
13914             isFastMultiplier = true;
13915             break;
13916           }
13917         }
13918
13919         if (isFastMultiplier) {
13920           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13921           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13922                              DAG.getConstant(CC, MVT::i8), Cond);
13923           // Zero extend the condition if needed.
13924           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13925                              Cond);
13926           // Scale the condition by the difference.
13927           if (Diff != 1)
13928             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13929                                DAG.getConstant(Diff, Cond.getValueType()));
13930
13931           // Add the base if non-zero.
13932           if (FalseC->getAPIntValue() != 0)
13933             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13934                                SDValue(FalseC, 0));
13935           if (N->getNumValues() == 2)  // Dead flag value?
13936             return DCI.CombineTo(N, Cond, SDValue());
13937           return Cond;
13938         }
13939       }
13940     }
13941   }
13942   return SDValue();
13943 }
13944
13945
13946 /// PerformMulCombine - Optimize a single multiply with constant into two
13947 /// in order to implement it with two cheaper instructions, e.g.
13948 /// LEA + SHL, LEA + LEA.
13949 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13950                                  TargetLowering::DAGCombinerInfo &DCI) {
13951   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13952     return SDValue();
13953
13954   EVT VT = N->getValueType(0);
13955   if (VT != MVT::i64)
13956     return SDValue();
13957
13958   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13959   if (!C)
13960     return SDValue();
13961   uint64_t MulAmt = C->getZExtValue();
13962   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13963     return SDValue();
13964
13965   uint64_t MulAmt1 = 0;
13966   uint64_t MulAmt2 = 0;
13967   if ((MulAmt % 9) == 0) {
13968     MulAmt1 = 9;
13969     MulAmt2 = MulAmt / 9;
13970   } else if ((MulAmt % 5) == 0) {
13971     MulAmt1 = 5;
13972     MulAmt2 = MulAmt / 5;
13973   } else if ((MulAmt % 3) == 0) {
13974     MulAmt1 = 3;
13975     MulAmt2 = MulAmt / 3;
13976   }
13977   if (MulAmt2 &&
13978       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13979     DebugLoc DL = N->getDebugLoc();
13980
13981     if (isPowerOf2_64(MulAmt2) &&
13982         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13983       // If second multiplifer is pow2, issue it first. We want the multiply by
13984       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13985       // is an add.
13986       std::swap(MulAmt1, MulAmt2);
13987
13988     SDValue NewMul;
13989     if (isPowerOf2_64(MulAmt1))
13990       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13991                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13992     else
13993       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13994                            DAG.getConstant(MulAmt1, VT));
13995
13996     if (isPowerOf2_64(MulAmt2))
13997       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13998                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13999     else
14000       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14001                            DAG.getConstant(MulAmt2, VT));
14002
14003     // Do not add new nodes to DAG combiner worklist.
14004     DCI.CombineTo(N, NewMul, false);
14005   }
14006   return SDValue();
14007 }
14008
14009 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14010   SDValue N0 = N->getOperand(0);
14011   SDValue N1 = N->getOperand(1);
14012   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14013   EVT VT = N0.getValueType();
14014
14015   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14016   // since the result of setcc_c is all zero's or all ones.
14017   if (VT.isInteger() && !VT.isVector() &&
14018       N1C && N0.getOpcode() == ISD::AND &&
14019       N0.getOperand(1).getOpcode() == ISD::Constant) {
14020     SDValue N00 = N0.getOperand(0);
14021     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14022         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14023           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14024          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14025       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14026       APInt ShAmt = N1C->getAPIntValue();
14027       Mask = Mask.shl(ShAmt);
14028       if (Mask != 0)
14029         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14030                            N00, DAG.getConstant(Mask, VT));
14031     }
14032   }
14033
14034
14035   // Hardware support for vector shifts is sparse which makes us scalarize the
14036   // vector operations in many cases. Also, on sandybridge ADD is faster than
14037   // shl.
14038   // (shl V, 1) -> add V,V
14039   if (isSplatVector(N1.getNode())) {
14040     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14041     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14042     // We shift all of the values by one. In many cases we do not have
14043     // hardware support for this operation. This is better expressed as an ADD
14044     // of two values.
14045     if (N1C && (1 == N1C->getZExtValue())) {
14046       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14047     }
14048   }
14049
14050   return SDValue();
14051 }
14052
14053 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14054 ///                       when possible.
14055 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14056                                    TargetLowering::DAGCombinerInfo &DCI,
14057                                    const X86Subtarget *Subtarget) {
14058   EVT VT = N->getValueType(0);
14059   if (N->getOpcode() == ISD::SHL) {
14060     SDValue V = PerformSHLCombine(N, DAG);
14061     if (V.getNode()) return V;
14062   }
14063
14064   // On X86 with SSE2 support, we can transform this to a vector shift if
14065   // all elements are shifted by the same amount.  We can't do this in legalize
14066   // because the a constant vector is typically transformed to a constant pool
14067   // so we have no knowledge of the shift amount.
14068   if (!Subtarget->hasSSE2())
14069     return SDValue();
14070
14071   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14072       (!Subtarget->hasAVX2() ||
14073        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14074     return SDValue();
14075
14076   SDValue ShAmtOp = N->getOperand(1);
14077   EVT EltVT = VT.getVectorElementType();
14078   DebugLoc DL = N->getDebugLoc();
14079   SDValue BaseShAmt = SDValue();
14080   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14081     unsigned NumElts = VT.getVectorNumElements();
14082     unsigned i = 0;
14083     for (; i != NumElts; ++i) {
14084       SDValue Arg = ShAmtOp.getOperand(i);
14085       if (Arg.getOpcode() == ISD::UNDEF) continue;
14086       BaseShAmt = Arg;
14087       break;
14088     }
14089     // Handle the case where the build_vector is all undef
14090     // FIXME: Should DAG allow this?
14091     if (i == NumElts)
14092       return SDValue();
14093
14094     for (; i != NumElts; ++i) {
14095       SDValue Arg = ShAmtOp.getOperand(i);
14096       if (Arg.getOpcode() == ISD::UNDEF) continue;
14097       if (Arg != BaseShAmt) {
14098         return SDValue();
14099       }
14100     }
14101   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14102              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14103     SDValue InVec = ShAmtOp.getOperand(0);
14104     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14105       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14106       unsigned i = 0;
14107       for (; i != NumElts; ++i) {
14108         SDValue Arg = InVec.getOperand(i);
14109         if (Arg.getOpcode() == ISD::UNDEF) continue;
14110         BaseShAmt = Arg;
14111         break;
14112       }
14113     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14114        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14115          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14116          if (C->getZExtValue() == SplatIdx)
14117            BaseShAmt = InVec.getOperand(1);
14118        }
14119     }
14120     if (BaseShAmt.getNode() == 0) {
14121       // Don't create instructions with illegal types after legalize
14122       // types has run.
14123       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14124           !DCI.isBeforeLegalize())
14125         return SDValue();
14126
14127       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14128                               DAG.getIntPtrConstant(0));
14129     }
14130   } else
14131     return SDValue();
14132
14133   // The shift amount is an i32.
14134   if (EltVT.bitsGT(MVT::i32))
14135     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14136   else if (EltVT.bitsLT(MVT::i32))
14137     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14138
14139   // The shift amount is identical so we can do a vector shift.
14140   SDValue  ValOp = N->getOperand(0);
14141   switch (N->getOpcode()) {
14142   default:
14143     llvm_unreachable("Unknown shift opcode!");
14144   case ISD::SHL:
14145     switch (VT.getSimpleVT().SimpleTy) {
14146     default: return SDValue();
14147     case MVT::v2i64:
14148     case MVT::v4i32:
14149     case MVT::v8i16:
14150     case MVT::v4i64:
14151     case MVT::v8i32:
14152     case MVT::v16i16:
14153       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14154     }
14155   case ISD::SRA:
14156     switch (VT.getSimpleVT().SimpleTy) {
14157     default: return SDValue();
14158     case MVT::v4i32:
14159     case MVT::v8i16:
14160     case MVT::v8i32:
14161     case MVT::v16i16:
14162       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14163     }
14164   case ISD::SRL:
14165     switch (VT.getSimpleVT().SimpleTy) {
14166     default: return SDValue();
14167     case MVT::v2i64:
14168     case MVT::v4i32:
14169     case MVT::v8i16:
14170     case MVT::v4i64:
14171     case MVT::v8i32:
14172     case MVT::v16i16:
14173       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14174     }
14175   }
14176 }
14177
14178
14179 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14180 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14181 // and friends.  Likewise for OR -> CMPNEQSS.
14182 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14183                             TargetLowering::DAGCombinerInfo &DCI,
14184                             const X86Subtarget *Subtarget) {
14185   unsigned opcode;
14186
14187   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14188   // we're requiring SSE2 for both.
14189   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14190     SDValue N0 = N->getOperand(0);
14191     SDValue N1 = N->getOperand(1);
14192     SDValue CMP0 = N0->getOperand(1);
14193     SDValue CMP1 = N1->getOperand(1);
14194     DebugLoc DL = N->getDebugLoc();
14195
14196     // The SETCCs should both refer to the same CMP.
14197     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14198       return SDValue();
14199
14200     SDValue CMP00 = CMP0->getOperand(0);
14201     SDValue CMP01 = CMP0->getOperand(1);
14202     EVT     VT    = CMP00.getValueType();
14203
14204     if (VT == MVT::f32 || VT == MVT::f64) {
14205       bool ExpectingFlags = false;
14206       // Check for any users that want flags:
14207       for (SDNode::use_iterator UI = N->use_begin(),
14208              UE = N->use_end();
14209            !ExpectingFlags && UI != UE; ++UI)
14210         switch (UI->getOpcode()) {
14211         default:
14212         case ISD::BR_CC:
14213         case ISD::BRCOND:
14214         case ISD::SELECT:
14215           ExpectingFlags = true;
14216           break;
14217         case ISD::CopyToReg:
14218         case ISD::SIGN_EXTEND:
14219         case ISD::ZERO_EXTEND:
14220         case ISD::ANY_EXTEND:
14221           break;
14222         }
14223
14224       if (!ExpectingFlags) {
14225         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14226         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14227
14228         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14229           X86::CondCode tmp = cc0;
14230           cc0 = cc1;
14231           cc1 = tmp;
14232         }
14233
14234         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14235             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14236           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14237           X86ISD::NodeType NTOperator = is64BitFP ?
14238             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14239           // FIXME: need symbolic constants for these magic numbers.
14240           // See X86ATTInstPrinter.cpp:printSSECC().
14241           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14242           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14243                                               DAG.getConstant(x86cc, MVT::i8));
14244           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14245                                               OnesOrZeroesF);
14246           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14247                                       DAG.getConstant(1, MVT::i32));
14248           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14249           return OneBitOfTruth;
14250         }
14251       }
14252     }
14253   }
14254   return SDValue();
14255 }
14256
14257 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14258 /// so it can be folded inside ANDNP.
14259 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14260   EVT VT = N->getValueType(0);
14261
14262   // Match direct AllOnes for 128 and 256-bit vectors
14263   if (ISD::isBuildVectorAllOnes(N))
14264     return true;
14265
14266   // Look through a bit convert.
14267   if (N->getOpcode() == ISD::BITCAST)
14268     N = N->getOperand(0).getNode();
14269
14270   // Sometimes the operand may come from a insert_subvector building a 256-bit
14271   // allones vector
14272   if (VT.getSizeInBits() == 256 &&
14273       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14274     SDValue V1 = N->getOperand(0);
14275     SDValue V2 = N->getOperand(1);
14276
14277     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14278         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14279         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14280         ISD::isBuildVectorAllOnes(V2.getNode()))
14281       return true;
14282   }
14283
14284   return false;
14285 }
14286
14287 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14288                                  TargetLowering::DAGCombinerInfo &DCI,
14289                                  const X86Subtarget *Subtarget) {
14290   if (DCI.isBeforeLegalizeOps())
14291     return SDValue();
14292
14293   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14294   if (R.getNode())
14295     return R;
14296
14297   EVT VT = N->getValueType(0);
14298
14299   // Create ANDN, BLSI, and BLSR instructions
14300   // BLSI is X & (-X)
14301   // BLSR is X & (X-1)
14302   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14303     SDValue N0 = N->getOperand(0);
14304     SDValue N1 = N->getOperand(1);
14305     DebugLoc DL = N->getDebugLoc();
14306
14307     // Check LHS for not
14308     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14309       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14310     // Check RHS for not
14311     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14312       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14313
14314     // Check LHS for neg
14315     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14316         isZero(N0.getOperand(0)))
14317       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14318
14319     // Check RHS for neg
14320     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14321         isZero(N1.getOperand(0)))
14322       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14323
14324     // Check LHS for X-1
14325     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14326         isAllOnes(N0.getOperand(1)))
14327       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14328
14329     // Check RHS for X-1
14330     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14331         isAllOnes(N1.getOperand(1)))
14332       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14333
14334     return SDValue();
14335   }
14336
14337   // Want to form ANDNP nodes:
14338   // 1) In the hopes of then easily combining them with OR and AND nodes
14339   //    to form PBLEND/PSIGN.
14340   // 2) To match ANDN packed intrinsics
14341   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14342     return SDValue();
14343
14344   SDValue N0 = N->getOperand(0);
14345   SDValue N1 = N->getOperand(1);
14346   DebugLoc DL = N->getDebugLoc();
14347
14348   // Check LHS for vnot
14349   if (N0.getOpcode() == ISD::XOR &&
14350       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14351       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14352     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14353
14354   // Check RHS for vnot
14355   if (N1.getOpcode() == ISD::XOR &&
14356       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14357       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14358     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14359
14360   return SDValue();
14361 }
14362
14363 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14364                                 TargetLowering::DAGCombinerInfo &DCI,
14365                                 const X86Subtarget *Subtarget) {
14366   if (DCI.isBeforeLegalizeOps())
14367     return SDValue();
14368
14369   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14370   if (R.getNode())
14371     return R;
14372
14373   EVT VT = N->getValueType(0);
14374
14375   SDValue N0 = N->getOperand(0);
14376   SDValue N1 = N->getOperand(1);
14377
14378   // look for psign/blend
14379   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14380     if (!Subtarget->hasSSSE3() ||
14381         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14382       return SDValue();
14383
14384     // Canonicalize pandn to RHS
14385     if (N0.getOpcode() == X86ISD::ANDNP)
14386       std::swap(N0, N1);
14387     // or (and (m, y), (pandn m, x))
14388     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14389       SDValue Mask = N1.getOperand(0);
14390       SDValue X    = N1.getOperand(1);
14391       SDValue Y;
14392       if (N0.getOperand(0) == Mask)
14393         Y = N0.getOperand(1);
14394       if (N0.getOperand(1) == Mask)
14395         Y = N0.getOperand(0);
14396
14397       // Check to see if the mask appeared in both the AND and ANDNP and
14398       if (!Y.getNode())
14399         return SDValue();
14400
14401       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14402       // Look through mask bitcast.
14403       if (Mask.getOpcode() == ISD::BITCAST)
14404         Mask = Mask.getOperand(0);
14405       if (X.getOpcode() == ISD::BITCAST)
14406         X = X.getOperand(0);
14407       if (Y.getOpcode() == ISD::BITCAST)
14408         Y = Y.getOperand(0);
14409
14410       EVT MaskVT = Mask.getValueType();
14411
14412       // Validate that the Mask operand is a vector sra node.
14413       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14414       // there is no psrai.b
14415       if (Mask.getOpcode() != X86ISD::VSRAI)
14416         return SDValue();
14417
14418       // Check that the SRA is all signbits.
14419       SDValue SraC = Mask.getOperand(1);
14420       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14421       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14422       if ((SraAmt + 1) != EltBits)
14423         return SDValue();
14424
14425       DebugLoc DL = N->getDebugLoc();
14426
14427       // Now we know we at least have a plendvb with the mask val.  See if
14428       // we can form a psignb/w/d.
14429       // psign = x.type == y.type == mask.type && y = sub(0, x);
14430       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14431           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14432           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14433         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14434                "Unsupported VT for PSIGN");
14435         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14436         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14437       }
14438       // PBLENDVB only available on SSE 4.1
14439       if (!Subtarget->hasSSE41())
14440         return SDValue();
14441
14442       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14443
14444       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14445       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14446       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14447       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14448       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14449     }
14450   }
14451
14452   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14453     return SDValue();
14454
14455   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14456   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14457     std::swap(N0, N1);
14458   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14459     return SDValue();
14460   if (!N0.hasOneUse() || !N1.hasOneUse())
14461     return SDValue();
14462
14463   SDValue ShAmt0 = N0.getOperand(1);
14464   if (ShAmt0.getValueType() != MVT::i8)
14465     return SDValue();
14466   SDValue ShAmt1 = N1.getOperand(1);
14467   if (ShAmt1.getValueType() != MVT::i8)
14468     return SDValue();
14469   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14470     ShAmt0 = ShAmt0.getOperand(0);
14471   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14472     ShAmt1 = ShAmt1.getOperand(0);
14473
14474   DebugLoc DL = N->getDebugLoc();
14475   unsigned Opc = X86ISD::SHLD;
14476   SDValue Op0 = N0.getOperand(0);
14477   SDValue Op1 = N1.getOperand(0);
14478   if (ShAmt0.getOpcode() == ISD::SUB) {
14479     Opc = X86ISD::SHRD;
14480     std::swap(Op0, Op1);
14481     std::swap(ShAmt0, ShAmt1);
14482   }
14483
14484   unsigned Bits = VT.getSizeInBits();
14485   if (ShAmt1.getOpcode() == ISD::SUB) {
14486     SDValue Sum = ShAmt1.getOperand(0);
14487     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14488       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14489       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14490         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14491       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14492         return DAG.getNode(Opc, DL, VT,
14493                            Op0, Op1,
14494                            DAG.getNode(ISD::TRUNCATE, DL,
14495                                        MVT::i8, ShAmt0));
14496     }
14497   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14498     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14499     if (ShAmt0C &&
14500         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14501       return DAG.getNode(Opc, DL, VT,
14502                          N0.getOperand(0), N1.getOperand(0),
14503                          DAG.getNode(ISD::TRUNCATE, DL,
14504                                        MVT::i8, ShAmt0));
14505   }
14506
14507   return SDValue();
14508 }
14509
14510 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14511 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14512                                  TargetLowering::DAGCombinerInfo &DCI,
14513                                  const X86Subtarget *Subtarget) {
14514   if (DCI.isBeforeLegalizeOps())
14515     return SDValue();
14516
14517   EVT VT = N->getValueType(0);
14518
14519   if (VT != MVT::i32 && VT != MVT::i64)
14520     return SDValue();
14521
14522   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14523
14524   // Create BLSMSK instructions by finding X ^ (X-1)
14525   SDValue N0 = N->getOperand(0);
14526   SDValue N1 = N->getOperand(1);
14527   DebugLoc DL = N->getDebugLoc();
14528
14529   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14530       isAllOnes(N0.getOperand(1)))
14531     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14532
14533   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14534       isAllOnes(N1.getOperand(1)))
14535     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14536
14537   return SDValue();
14538 }
14539
14540 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14541 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14542                                    const X86Subtarget *Subtarget) {
14543   LoadSDNode *Ld = cast<LoadSDNode>(N);
14544   EVT RegVT = Ld->getValueType(0);
14545   EVT MemVT = Ld->getMemoryVT();
14546   DebugLoc dl = Ld->getDebugLoc();
14547   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14548
14549   ISD::LoadExtType Ext = Ld->getExtensionType();
14550
14551   // If this is a vector EXT Load then attempt to optimize it using a
14552   // shuffle. We need SSE4 for the shuffles.
14553   // TODO: It is possible to support ZExt by zeroing the undef values
14554   // during the shuffle phase or after the shuffle.
14555   if (RegVT.isVector() && RegVT.isInteger() &&
14556       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14557     assert(MemVT != RegVT && "Cannot extend to the same type");
14558     assert(MemVT.isVector() && "Must load a vector from memory");
14559
14560     unsigned NumElems = RegVT.getVectorNumElements();
14561     unsigned RegSz = RegVT.getSizeInBits();
14562     unsigned MemSz = MemVT.getSizeInBits();
14563     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14564     // All sizes must be a power of two
14565     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14566
14567     // Attempt to load the original value using a single load op.
14568     // Find a scalar type which is equal to the loaded word size.
14569     MVT SclrLoadTy = MVT::i8;
14570     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14571          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14572       MVT Tp = (MVT::SimpleValueType)tp;
14573       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
14574         SclrLoadTy = Tp;
14575         break;
14576       }
14577     }
14578
14579     // Proceed if a load word is found.
14580     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14581
14582     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14583       RegSz/SclrLoadTy.getSizeInBits());
14584
14585     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14586                                   RegSz/MemVT.getScalarType().getSizeInBits());
14587     // Can't shuffle using an illegal type.
14588     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14589
14590     // Perform a single load.
14591     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14592                                   Ld->getBasePtr(),
14593                                   Ld->getPointerInfo(), Ld->isVolatile(),
14594                                   Ld->isNonTemporal(), Ld->isInvariant(),
14595                                   Ld->getAlignment());
14596
14597     // Insert the word loaded into a vector.
14598     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14599       LoadUnitVecVT, ScalarLoad);
14600
14601     // Bitcast the loaded value to a vector of the original element type, in
14602     // the size of the target vector type.
14603     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT,
14604                                     ScalarInVector);
14605     unsigned SizeRatio = RegSz/MemSz;
14606
14607     // Redistribute the loaded elements into the different locations.
14608     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14609     for (unsigned i = 0; i != NumElems; ++i)
14610       ShuffleVec[i*SizeRatio] = i;
14611
14612     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14613                                          DAG.getUNDEF(WideVecVT),
14614                                          &ShuffleVec[0]);
14615
14616     // Bitcast to the requested type.
14617     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14618     // Replace the original load with the new sequence
14619     // and return the new chain.
14620     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14621     return SDValue(ScalarLoad.getNode(), 1);
14622   }
14623
14624   return SDValue();
14625 }
14626
14627 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14628 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14629                                    const X86Subtarget *Subtarget) {
14630   StoreSDNode *St = cast<StoreSDNode>(N);
14631   EVT VT = St->getValue().getValueType();
14632   EVT StVT = St->getMemoryVT();
14633   DebugLoc dl = St->getDebugLoc();
14634   SDValue StoredVal = St->getOperand(1);
14635   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14636
14637   // If we are saving a concatenation of two XMM registers, perform two stores.
14638   // On Sandy Bridge, 256-bit memory operations are executed by two
14639   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
14640   // memory  operation.
14641   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2() &&
14642       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14643       StoredVal.getNumOperands() == 2) {
14644     SDValue Value0 = StoredVal.getOperand(0);
14645     SDValue Value1 = StoredVal.getOperand(1);
14646
14647     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14648     SDValue Ptr0 = St->getBasePtr();
14649     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14650
14651     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14652                                 St->getPointerInfo(), St->isVolatile(),
14653                                 St->isNonTemporal(), St->getAlignment());
14654     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14655                                 St->getPointerInfo(), St->isVolatile(),
14656                                 St->isNonTemporal(), St->getAlignment());
14657     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14658   }
14659
14660   // Optimize trunc store (of multiple scalars) to shuffle and store.
14661   // First, pack all of the elements in one place. Next, store to memory
14662   // in fewer chunks.
14663   if (St->isTruncatingStore() && VT.isVector()) {
14664     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14665     unsigned NumElems = VT.getVectorNumElements();
14666     assert(StVT != VT && "Cannot truncate to the same type");
14667     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14668     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14669
14670     // From, To sizes and ElemCount must be pow of two
14671     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14672     // We are going to use the original vector elt for storing.
14673     // Accumulated smaller vector elements must be a multiple of the store size.
14674     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14675
14676     unsigned SizeRatio  = FromSz / ToSz;
14677
14678     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14679
14680     // Create a type on which we perform the shuffle
14681     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14682             StVT.getScalarType(), NumElems*SizeRatio);
14683
14684     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14685
14686     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14687     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14688     for (unsigned i = 0; i != NumElems; ++i)
14689       ShuffleVec[i] = i * SizeRatio;
14690
14691     // Can't shuffle using an illegal type
14692     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14693
14694     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14695                                          DAG.getUNDEF(WideVecVT),
14696                                          &ShuffleVec[0]);
14697     // At this point all of the data is stored at the bottom of the
14698     // register. We now need to save it to mem.
14699
14700     // Find the largest store unit
14701     MVT StoreType = MVT::i8;
14702     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14703          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14704       MVT Tp = (MVT::SimpleValueType)tp;
14705       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14706         StoreType = Tp;
14707     }
14708
14709     // Bitcast the original vector into a vector of store-size units
14710     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14711             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14712     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14713     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14714     SmallVector<SDValue, 8> Chains;
14715     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14716                                         TLI.getPointerTy());
14717     SDValue Ptr = St->getBasePtr();
14718
14719     // Perform one or more big stores into memory.
14720     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
14721       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14722                                    StoreType, ShuffWide,
14723                                    DAG.getIntPtrConstant(i));
14724       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14725                                 St->getPointerInfo(), St->isVolatile(),
14726                                 St->isNonTemporal(), St->getAlignment());
14727       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14728       Chains.push_back(Ch);
14729     }
14730
14731     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14732                                Chains.size());
14733   }
14734
14735
14736   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14737   // the FP state in cases where an emms may be missing.
14738   // A preferable solution to the general problem is to figure out the right
14739   // places to insert EMMS.  This qualifies as a quick hack.
14740
14741   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14742   if (VT.getSizeInBits() != 64)
14743     return SDValue();
14744
14745   const Function *F = DAG.getMachineFunction().getFunction();
14746   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14747   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14748                      && Subtarget->hasSSE2();
14749   if ((VT.isVector() ||
14750        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14751       isa<LoadSDNode>(St->getValue()) &&
14752       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14753       St->getChain().hasOneUse() && !St->isVolatile()) {
14754     SDNode* LdVal = St->getValue().getNode();
14755     LoadSDNode *Ld = 0;
14756     int TokenFactorIndex = -1;
14757     SmallVector<SDValue, 8> Ops;
14758     SDNode* ChainVal = St->getChain().getNode();
14759     // Must be a store of a load.  We currently handle two cases:  the load
14760     // is a direct child, and it's under an intervening TokenFactor.  It is
14761     // possible to dig deeper under nested TokenFactors.
14762     if (ChainVal == LdVal)
14763       Ld = cast<LoadSDNode>(St->getChain());
14764     else if (St->getValue().hasOneUse() &&
14765              ChainVal->getOpcode() == ISD::TokenFactor) {
14766       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14767         if (ChainVal->getOperand(i).getNode() == LdVal) {
14768           TokenFactorIndex = i;
14769           Ld = cast<LoadSDNode>(St->getValue());
14770         } else
14771           Ops.push_back(ChainVal->getOperand(i));
14772       }
14773     }
14774
14775     if (!Ld || !ISD::isNormalLoad(Ld))
14776       return SDValue();
14777
14778     // If this is not the MMX case, i.e. we are just turning i64 load/store
14779     // into f64 load/store, avoid the transformation if there are multiple
14780     // uses of the loaded value.
14781     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14782       return SDValue();
14783
14784     DebugLoc LdDL = Ld->getDebugLoc();
14785     DebugLoc StDL = N->getDebugLoc();
14786     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14787     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14788     // pair instead.
14789     if (Subtarget->is64Bit() || F64IsLegal) {
14790       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14791       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14792                                   Ld->getPointerInfo(), Ld->isVolatile(),
14793                                   Ld->isNonTemporal(), Ld->isInvariant(),
14794                                   Ld->getAlignment());
14795       SDValue NewChain = NewLd.getValue(1);
14796       if (TokenFactorIndex != -1) {
14797         Ops.push_back(NewChain);
14798         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14799                                Ops.size());
14800       }
14801       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14802                           St->getPointerInfo(),
14803                           St->isVolatile(), St->isNonTemporal(),
14804                           St->getAlignment());
14805     }
14806
14807     // Otherwise, lower to two pairs of 32-bit loads / stores.
14808     SDValue LoAddr = Ld->getBasePtr();
14809     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14810                                  DAG.getConstant(4, MVT::i32));
14811
14812     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14813                                Ld->getPointerInfo(),
14814                                Ld->isVolatile(), Ld->isNonTemporal(),
14815                                Ld->isInvariant(), Ld->getAlignment());
14816     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14817                                Ld->getPointerInfo().getWithOffset(4),
14818                                Ld->isVolatile(), Ld->isNonTemporal(),
14819                                Ld->isInvariant(),
14820                                MinAlign(Ld->getAlignment(), 4));
14821
14822     SDValue NewChain = LoLd.getValue(1);
14823     if (TokenFactorIndex != -1) {
14824       Ops.push_back(LoLd);
14825       Ops.push_back(HiLd);
14826       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14827                              Ops.size());
14828     }
14829
14830     LoAddr = St->getBasePtr();
14831     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14832                          DAG.getConstant(4, MVT::i32));
14833
14834     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14835                                 St->getPointerInfo(),
14836                                 St->isVolatile(), St->isNonTemporal(),
14837                                 St->getAlignment());
14838     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14839                                 St->getPointerInfo().getWithOffset(4),
14840                                 St->isVolatile(),
14841                                 St->isNonTemporal(),
14842                                 MinAlign(St->getAlignment(), 4));
14843     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14844   }
14845   return SDValue();
14846 }
14847
14848 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14849 /// and return the operands for the horizontal operation in LHS and RHS.  A
14850 /// horizontal operation performs the binary operation on successive elements
14851 /// of its first operand, then on successive elements of its second operand,
14852 /// returning the resulting values in a vector.  For example, if
14853 ///   A = < float a0, float a1, float a2, float a3 >
14854 /// and
14855 ///   B = < float b0, float b1, float b2, float b3 >
14856 /// then the result of doing a horizontal operation on A and B is
14857 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14858 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14859 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14860 /// set to A, RHS to B, and the routine returns 'true'.
14861 /// Note that the binary operation should have the property that if one of the
14862 /// operands is UNDEF then the result is UNDEF.
14863 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14864   // Look for the following pattern: if
14865   //   A = < float a0, float a1, float a2, float a3 >
14866   //   B = < float b0, float b1, float b2, float b3 >
14867   // and
14868   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14869   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14870   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14871   // which is A horizontal-op B.
14872
14873   // At least one of the operands should be a vector shuffle.
14874   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14875       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14876     return false;
14877
14878   EVT VT = LHS.getValueType();
14879
14880   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14881          "Unsupported vector type for horizontal add/sub");
14882
14883   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14884   // operate independently on 128-bit lanes.
14885   unsigned NumElts = VT.getVectorNumElements();
14886   unsigned NumLanes = VT.getSizeInBits()/128;
14887   unsigned NumLaneElts = NumElts / NumLanes;
14888   assert((NumLaneElts % 2 == 0) &&
14889          "Vector type should have an even number of elements in each lane");
14890   unsigned HalfLaneElts = NumLaneElts/2;
14891
14892   // View LHS in the form
14893   //   LHS = VECTOR_SHUFFLE A, B, LMask
14894   // If LHS is not a shuffle then pretend it is the shuffle
14895   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14896   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14897   // type VT.
14898   SDValue A, B;
14899   SmallVector<int, 16> LMask(NumElts);
14900   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14901     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14902       A = LHS.getOperand(0);
14903     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14904       B = LHS.getOperand(1);
14905     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
14906     std::copy(Mask.begin(), Mask.end(), LMask.begin());
14907   } else {
14908     if (LHS.getOpcode() != ISD::UNDEF)
14909       A = LHS;
14910     for (unsigned i = 0; i != NumElts; ++i)
14911       LMask[i] = i;
14912   }
14913
14914   // Likewise, view RHS in the form
14915   //   RHS = VECTOR_SHUFFLE C, D, RMask
14916   SDValue C, D;
14917   SmallVector<int, 16> RMask(NumElts);
14918   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14919     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14920       C = RHS.getOperand(0);
14921     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14922       D = RHS.getOperand(1);
14923     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
14924     std::copy(Mask.begin(), Mask.end(), RMask.begin());
14925   } else {
14926     if (RHS.getOpcode() != ISD::UNDEF)
14927       C = RHS;
14928     for (unsigned i = 0; i != NumElts; ++i)
14929       RMask[i] = i;
14930   }
14931
14932   // Check that the shuffles are both shuffling the same vectors.
14933   if (!(A == C && B == D) && !(A == D && B == C))
14934     return false;
14935
14936   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14937   if (!A.getNode() && !B.getNode())
14938     return false;
14939
14940   // If A and B occur in reverse order in RHS, then "swap" them (which means
14941   // rewriting the mask).
14942   if (A != C)
14943     CommuteVectorShuffleMask(RMask, NumElts);
14944
14945   // At this point LHS and RHS are equivalent to
14946   //   LHS = VECTOR_SHUFFLE A, B, LMask
14947   //   RHS = VECTOR_SHUFFLE A, B, RMask
14948   // Check that the masks correspond to performing a horizontal operation.
14949   for (unsigned i = 0; i != NumElts; ++i) {
14950     int LIdx = LMask[i], RIdx = RMask[i];
14951
14952     // Ignore any UNDEF components.
14953     if (LIdx < 0 || RIdx < 0 ||
14954         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14955         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14956       continue;
14957
14958     // Check that successive elements are being operated on.  If not, this is
14959     // not a horizontal operation.
14960     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14961     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14962     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14963     if (!(LIdx == Index && RIdx == Index + 1) &&
14964         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14965       return false;
14966   }
14967
14968   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14969   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14970   return true;
14971 }
14972
14973 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14974 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14975                                   const X86Subtarget *Subtarget) {
14976   EVT VT = N->getValueType(0);
14977   SDValue LHS = N->getOperand(0);
14978   SDValue RHS = N->getOperand(1);
14979
14980   // Try to synthesize horizontal adds from adds of shuffles.
14981   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14982        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14983       isHorizontalBinOp(LHS, RHS, true))
14984     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14985   return SDValue();
14986 }
14987
14988 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14989 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14990                                   const X86Subtarget *Subtarget) {
14991   EVT VT = N->getValueType(0);
14992   SDValue LHS = N->getOperand(0);
14993   SDValue RHS = N->getOperand(1);
14994
14995   // Try to synthesize horizontal subs from subs of shuffles.
14996   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14997        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14998       isHorizontalBinOp(LHS, RHS, false))
14999     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15000   return SDValue();
15001 }
15002
15003 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15004 /// X86ISD::FXOR nodes.
15005 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15006   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15007   // F[X]OR(0.0, x) -> x
15008   // F[X]OR(x, 0.0) -> x
15009   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15010     if (C->getValueAPF().isPosZero())
15011       return N->getOperand(1);
15012   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15013     if (C->getValueAPF().isPosZero())
15014       return N->getOperand(0);
15015   return SDValue();
15016 }
15017
15018 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15019 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15020   // FAND(0.0, x) -> 0.0
15021   // FAND(x, 0.0) -> 0.0
15022   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15023     if (C->getValueAPF().isPosZero())
15024       return N->getOperand(0);
15025   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15026     if (C->getValueAPF().isPosZero())
15027       return N->getOperand(1);
15028   return SDValue();
15029 }
15030
15031 static SDValue PerformBTCombine(SDNode *N,
15032                                 SelectionDAG &DAG,
15033                                 TargetLowering::DAGCombinerInfo &DCI) {
15034   // BT ignores high bits in the bit index operand.
15035   SDValue Op1 = N->getOperand(1);
15036   if (Op1.hasOneUse()) {
15037     unsigned BitWidth = Op1.getValueSizeInBits();
15038     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15039     APInt KnownZero, KnownOne;
15040     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15041                                           !DCI.isBeforeLegalizeOps());
15042     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15043     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15044         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15045       DCI.CommitTargetLoweringOpt(TLO);
15046   }
15047   return SDValue();
15048 }
15049
15050 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15051   SDValue Op = N->getOperand(0);
15052   if (Op.getOpcode() == ISD::BITCAST)
15053     Op = Op.getOperand(0);
15054   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15055   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15056       VT.getVectorElementType().getSizeInBits() ==
15057       OpVT.getVectorElementType().getSizeInBits()) {
15058     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15059   }
15060   return SDValue();
15061 }
15062
15063 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15064                                   TargetLowering::DAGCombinerInfo &DCI,
15065                                   const X86Subtarget *Subtarget) {
15066   if (!DCI.isBeforeLegalizeOps())
15067     return SDValue();
15068
15069   if (!Subtarget->hasAVX())
15070     return SDValue();
15071
15072   EVT VT = N->getValueType(0);
15073   SDValue Op = N->getOperand(0);
15074   EVT OpVT = Op.getValueType();
15075   DebugLoc dl = N->getDebugLoc();
15076
15077   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15078       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15079
15080     if (Subtarget->hasAVX2())
15081       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15082
15083     // Optimize vectors in AVX mode
15084     // Sign extend  v8i16 to v8i32 and
15085     //              v4i32 to v4i64
15086     //
15087     // Divide input vector into two parts
15088     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15089     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15090     // concat the vectors to original VT
15091
15092     unsigned NumElems = OpVT.getVectorNumElements();
15093     SmallVector<int,8> ShufMask1(NumElems, -1);
15094     for (unsigned i = 0; i != NumElems/2; ++i)
15095       ShufMask1[i] = i;
15096
15097     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15098                                         &ShufMask1[0]);
15099
15100     SmallVector<int,8> ShufMask2(NumElems, -1);
15101     for (unsigned i = 0; i != NumElems/2; ++i)
15102       ShufMask2[i] = i + NumElems/2;
15103
15104     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15105                                         &ShufMask2[0]);
15106
15107     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15108                                   VT.getVectorNumElements()/2);
15109
15110     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15111     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15112
15113     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15114   }
15115   return SDValue();
15116 }
15117
15118 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15119                                   TargetLowering::DAGCombinerInfo &DCI,
15120                                   const X86Subtarget *Subtarget) {
15121   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15122   //           (and (i32 x86isd::setcc_carry), 1)
15123   // This eliminates the zext. This transformation is necessary because
15124   // ISD::SETCC is always legalized to i8.
15125   DebugLoc dl = N->getDebugLoc();
15126   SDValue N0 = N->getOperand(0);
15127   EVT VT = N->getValueType(0);
15128   EVT OpVT = N0.getValueType();
15129
15130   if (N0.getOpcode() == ISD::AND &&
15131       N0.hasOneUse() &&
15132       N0.getOperand(0).hasOneUse()) {
15133     SDValue N00 = N0.getOperand(0);
15134     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15135       return SDValue();
15136     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15137     if (!C || C->getZExtValue() != 1)
15138       return SDValue();
15139     return DAG.getNode(ISD::AND, dl, VT,
15140                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15141                                    N00.getOperand(0), N00.getOperand(1)),
15142                        DAG.getConstant(1, VT));
15143   }
15144
15145   // Optimize vectors in AVX mode:
15146   //
15147   //   v8i16 -> v8i32
15148   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15149   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15150   //   Concat upper and lower parts.
15151   //
15152   //   v4i32 -> v4i64
15153   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15154   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15155   //   Concat upper and lower parts.
15156   //
15157   if (!DCI.isBeforeLegalizeOps())
15158     return SDValue();
15159
15160   if (!Subtarget->hasAVX())
15161     return SDValue();
15162
15163   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15164       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15165
15166     if (Subtarget->hasAVX2())
15167       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15168
15169     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15170     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15171     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15172
15173     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15174                                VT.getVectorNumElements()/2);
15175
15176     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15177     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15178
15179     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15180   }
15181
15182   return SDValue();
15183 }
15184
15185 // Optimize x == -y --> x+y == 0
15186 //          x != -y --> x+y != 0
15187 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15188   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15189   SDValue LHS = N->getOperand(0);
15190   SDValue RHS = N->getOperand(1); 
15191
15192   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15193     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15194       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15195         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15196                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15197         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15198                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15199       }
15200   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15201     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15202       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15203         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15204                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15205         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15206                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15207       }
15208   return SDValue();
15209 }
15210
15211 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15212 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15213   unsigned X86CC = N->getConstantOperandVal(0);
15214   SDValue EFLAG = N->getOperand(1);
15215   DebugLoc DL = N->getDebugLoc();
15216
15217   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15218   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15219   // cases.
15220   if (X86CC == X86::COND_B)
15221     return DAG.getNode(ISD::AND, DL, MVT::i8,
15222                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15223                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
15224                        DAG.getConstant(1, MVT::i8));
15225
15226   return SDValue();
15227 }
15228
15229 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15230   SDValue Op0 = N->getOperand(0);
15231   EVT InVT = Op0->getValueType(0);
15232
15233   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15234   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15235     DebugLoc dl = N->getDebugLoc();
15236     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15237     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15238     // Notice that we use SINT_TO_FP because we know that the high bits
15239     // are zero and SINT_TO_FP is better supported by the hardware.
15240     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15241   }
15242
15243   return SDValue();
15244 }
15245
15246 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15247                                         const X86TargetLowering *XTLI) {
15248   SDValue Op0 = N->getOperand(0);
15249   EVT InVT = Op0->getValueType(0);
15250
15251   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15252   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15253     DebugLoc dl = N->getDebugLoc();
15254     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15255     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15256     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15257   }
15258
15259   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15260   // a 32-bit target where SSE doesn't support i64->FP operations.
15261   if (Op0.getOpcode() == ISD::LOAD) {
15262     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15263     EVT VT = Ld->getValueType(0);
15264     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15265         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15266         !XTLI->getSubtarget()->is64Bit() &&
15267         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15268       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15269                                           Ld->getChain(), Op0, DAG);
15270       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15271       return FILDChain;
15272     }
15273   }
15274   return SDValue();
15275 }
15276
15277 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15278   EVT VT = N->getValueType(0);
15279
15280   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15281   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15282     DebugLoc dl = N->getDebugLoc();
15283     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15284     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15285     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15286   }
15287
15288   return SDValue();
15289 }
15290
15291 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15292 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15293                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15294   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15295   // the result is either zero or one (depending on the input carry bit).
15296   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15297   if (X86::isZeroNode(N->getOperand(0)) &&
15298       X86::isZeroNode(N->getOperand(1)) &&
15299       // We don't have a good way to replace an EFLAGS use, so only do this when
15300       // dead right now.
15301       SDValue(N, 1).use_empty()) {
15302     DebugLoc DL = N->getDebugLoc();
15303     EVT VT = N->getValueType(0);
15304     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15305     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15306                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15307                                            DAG.getConstant(X86::COND_B,MVT::i8),
15308                                            N->getOperand(2)),
15309                                DAG.getConstant(1, VT));
15310     return DCI.CombineTo(N, Res1, CarryOut);
15311   }
15312
15313   return SDValue();
15314 }
15315
15316 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15317 //      (add Y, (setne X, 0)) -> sbb -1, Y
15318 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15319 //      (sub (setne X, 0), Y) -> adc -1, Y
15320 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15321   DebugLoc DL = N->getDebugLoc();
15322
15323   // Look through ZExts.
15324   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15325   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15326     return SDValue();
15327
15328   SDValue SetCC = Ext.getOperand(0);
15329   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15330     return SDValue();
15331
15332   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15333   if (CC != X86::COND_E && CC != X86::COND_NE)
15334     return SDValue();
15335
15336   SDValue Cmp = SetCC.getOperand(1);
15337   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15338       !X86::isZeroNode(Cmp.getOperand(1)) ||
15339       !Cmp.getOperand(0).getValueType().isInteger())
15340     return SDValue();
15341
15342   SDValue CmpOp0 = Cmp.getOperand(0);
15343   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15344                                DAG.getConstant(1, CmpOp0.getValueType()));
15345
15346   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15347   if (CC == X86::COND_NE)
15348     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15349                        DL, OtherVal.getValueType(), OtherVal,
15350                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15351   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15352                      DL, OtherVal.getValueType(), OtherVal,
15353                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15354 }
15355
15356 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15357 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15358                                  const X86Subtarget *Subtarget) {
15359   EVT VT = N->getValueType(0);
15360   SDValue Op0 = N->getOperand(0);
15361   SDValue Op1 = N->getOperand(1);
15362
15363   // Try to synthesize horizontal adds from adds of shuffles.
15364   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15365        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15366       isHorizontalBinOp(Op0, Op1, true))
15367     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15368
15369   return OptimizeConditionalInDecrement(N, DAG);
15370 }
15371
15372 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15373                                  const X86Subtarget *Subtarget) {
15374   SDValue Op0 = N->getOperand(0);
15375   SDValue Op1 = N->getOperand(1);
15376
15377   // X86 can't encode an immediate LHS of a sub. See if we can push the
15378   // negation into a preceding instruction.
15379   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15380     // If the RHS of the sub is a XOR with one use and a constant, invert the
15381     // immediate. Then add one to the LHS of the sub so we can turn
15382     // X-Y -> X+~Y+1, saving one register.
15383     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15384         isa<ConstantSDNode>(Op1.getOperand(1))) {
15385       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15386       EVT VT = Op0.getValueType();
15387       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15388                                    Op1.getOperand(0),
15389                                    DAG.getConstant(~XorC, VT));
15390       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15391                          DAG.getConstant(C->getAPIntValue()+1, VT));
15392     }
15393   }
15394
15395   // Try to synthesize horizontal adds from adds of shuffles.
15396   EVT VT = N->getValueType(0);
15397   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15398        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15399       isHorizontalBinOp(Op0, Op1, true))
15400     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15401
15402   return OptimizeConditionalInDecrement(N, DAG);
15403 }
15404
15405 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15406                                              DAGCombinerInfo &DCI) const {
15407   SelectionDAG &DAG = DCI.DAG;
15408   switch (N->getOpcode()) {
15409   default: break;
15410   case ISD::EXTRACT_VECTOR_ELT:
15411     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15412   case ISD::VSELECT:
15413   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15414   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
15415   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
15416   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
15417   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
15418   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
15419   case ISD::SHL:
15420   case ISD::SRA:
15421   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
15422   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
15423   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
15424   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
15425   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
15426   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
15427   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
15428   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
15429   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
15430   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
15431   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
15432   case X86ISD::FXOR:
15433   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
15434   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
15435   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
15436   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
15437   case ISD::ANY_EXTEND:
15438   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
15439   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
15440   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
15441   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
15442   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
15443   case X86ISD::SHUFP:       // Handle all target specific shuffles
15444   case X86ISD::PALIGN:
15445   case X86ISD::UNPCKH:
15446   case X86ISD::UNPCKL:
15447   case X86ISD::MOVHLPS:
15448   case X86ISD::MOVLHPS:
15449   case X86ISD::PSHUFD:
15450   case X86ISD::PSHUFHW:
15451   case X86ISD::PSHUFLW:
15452   case X86ISD::MOVSS:
15453   case X86ISD::MOVSD:
15454   case X86ISD::VPERMILP:
15455   case X86ISD::VPERM2X128:
15456   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
15457   }
15458
15459   return SDValue();
15460 }
15461
15462 /// isTypeDesirableForOp - Return true if the target has native support for
15463 /// the specified value type and it is 'desirable' to use the type for the
15464 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
15465 /// instruction encodings are longer and some i16 instructions are slow.
15466 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
15467   if (!isTypeLegal(VT))
15468     return false;
15469   if (VT != MVT::i16)
15470     return true;
15471
15472   switch (Opc) {
15473   default:
15474     return true;
15475   case ISD::LOAD:
15476   case ISD::SIGN_EXTEND:
15477   case ISD::ZERO_EXTEND:
15478   case ISD::ANY_EXTEND:
15479   case ISD::SHL:
15480   case ISD::SRL:
15481   case ISD::SUB:
15482   case ISD::ADD:
15483   case ISD::MUL:
15484   case ISD::AND:
15485   case ISD::OR:
15486   case ISD::XOR:
15487     return false;
15488   }
15489 }
15490
15491 /// IsDesirableToPromoteOp - This method query the target whether it is
15492 /// beneficial for dag combiner to promote the specified node. If true, it
15493 /// should return the desired promotion type by reference.
15494 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
15495   EVT VT = Op.getValueType();
15496   if (VT != MVT::i16)
15497     return false;
15498
15499   bool Promote = false;
15500   bool Commute = false;
15501   switch (Op.getOpcode()) {
15502   default: break;
15503   case ISD::LOAD: {
15504     LoadSDNode *LD = cast<LoadSDNode>(Op);
15505     // If the non-extending load has a single use and it's not live out, then it
15506     // might be folded.
15507     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
15508                                                      Op.hasOneUse()*/) {
15509       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15510              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
15511         // The only case where we'd want to promote LOAD (rather then it being
15512         // promoted as an operand is when it's only use is liveout.
15513         if (UI->getOpcode() != ISD::CopyToReg)
15514           return false;
15515       }
15516     }
15517     Promote = true;
15518     break;
15519   }
15520   case ISD::SIGN_EXTEND:
15521   case ISD::ZERO_EXTEND:
15522   case ISD::ANY_EXTEND:
15523     Promote = true;
15524     break;
15525   case ISD::SHL:
15526   case ISD::SRL: {
15527     SDValue N0 = Op.getOperand(0);
15528     // Look out for (store (shl (load), x)).
15529     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15530       return false;
15531     Promote = true;
15532     break;
15533   }
15534   case ISD::ADD:
15535   case ISD::MUL:
15536   case ISD::AND:
15537   case ISD::OR:
15538   case ISD::XOR:
15539     Commute = true;
15540     // fallthrough
15541   case ISD::SUB: {
15542     SDValue N0 = Op.getOperand(0);
15543     SDValue N1 = Op.getOperand(1);
15544     if (!Commute && MayFoldLoad(N1))
15545       return false;
15546     // Avoid disabling potential load folding opportunities.
15547     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15548       return false;
15549     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15550       return false;
15551     Promote = true;
15552   }
15553   }
15554
15555   PVT = MVT::i32;
15556   return Promote;
15557 }
15558
15559 //===----------------------------------------------------------------------===//
15560 //                           X86 Inline Assembly Support
15561 //===----------------------------------------------------------------------===//
15562
15563 namespace {
15564   // Helper to match a string separated by whitespace.
15565   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15566     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15567
15568     for (unsigned i = 0, e = args.size(); i != e; ++i) {
15569       StringRef piece(*args[i]);
15570       if (!s.startswith(piece)) // Check if the piece matches.
15571         return false;
15572
15573       s = s.substr(piece.size());
15574       StringRef::size_type pos = s.find_first_not_of(" \t");
15575       if (pos == 0) // We matched a prefix.
15576         return false;
15577
15578       s = s.substr(pos);
15579     }
15580
15581     return s.empty();
15582   }
15583   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15584 }
15585
15586 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15587   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15588
15589   std::string AsmStr = IA->getAsmString();
15590
15591   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15592   if (!Ty || Ty->getBitWidth() % 16 != 0)
15593     return false;
15594
15595   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15596   SmallVector<StringRef, 4> AsmPieces;
15597   SplitString(AsmStr, AsmPieces, ";\n");
15598
15599   switch (AsmPieces.size()) {
15600   default: return false;
15601   case 1:
15602     // FIXME: this should verify that we are targeting a 486 or better.  If not,
15603     // we will turn this bswap into something that will be lowered to logical
15604     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
15605     // lower so don't worry about this.
15606     // bswap $0
15607     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15608         matchAsm(AsmPieces[0], "bswapl", "$0") ||
15609         matchAsm(AsmPieces[0], "bswapq", "$0") ||
15610         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15611         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15612         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15613       // No need to check constraints, nothing other than the equivalent of
15614       // "=r,0" would be valid here.
15615       return IntrinsicLowering::LowerToByteSwap(CI);
15616     }
15617
15618     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15619     if (CI->getType()->isIntegerTy(16) &&
15620         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15621         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15622          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15623       AsmPieces.clear();
15624       const std::string &ConstraintsStr = IA->getConstraintString();
15625       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15626       std::sort(AsmPieces.begin(), AsmPieces.end());
15627       if (AsmPieces.size() == 4 &&
15628           AsmPieces[0] == "~{cc}" &&
15629           AsmPieces[1] == "~{dirflag}" &&
15630           AsmPieces[2] == "~{flags}" &&
15631           AsmPieces[3] == "~{fpsr}")
15632       return IntrinsicLowering::LowerToByteSwap(CI);
15633     }
15634     break;
15635   case 3:
15636     if (CI->getType()->isIntegerTy(32) &&
15637         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15638         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15639         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15640         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15641       AsmPieces.clear();
15642       const std::string &ConstraintsStr = IA->getConstraintString();
15643       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15644       std::sort(AsmPieces.begin(), AsmPieces.end());
15645       if (AsmPieces.size() == 4 &&
15646           AsmPieces[0] == "~{cc}" &&
15647           AsmPieces[1] == "~{dirflag}" &&
15648           AsmPieces[2] == "~{flags}" &&
15649           AsmPieces[3] == "~{fpsr}")
15650         return IntrinsicLowering::LowerToByteSwap(CI);
15651     }
15652
15653     if (CI->getType()->isIntegerTy(64)) {
15654       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15655       if (Constraints.size() >= 2 &&
15656           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15657           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15658         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15659         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15660             matchAsm(AsmPieces[1], "bswap", "%edx") &&
15661             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15662           return IntrinsicLowering::LowerToByteSwap(CI);
15663       }
15664     }
15665     break;
15666   }
15667   return false;
15668 }
15669
15670
15671
15672 /// getConstraintType - Given a constraint letter, return the type of
15673 /// constraint it is for this target.
15674 X86TargetLowering::ConstraintType
15675 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15676   if (Constraint.size() == 1) {
15677     switch (Constraint[0]) {
15678     case 'R':
15679     case 'q':
15680     case 'Q':
15681     case 'f':
15682     case 't':
15683     case 'u':
15684     case 'y':
15685     case 'x':
15686     case 'Y':
15687     case 'l':
15688       return C_RegisterClass;
15689     case 'a':
15690     case 'b':
15691     case 'c':
15692     case 'd':
15693     case 'S':
15694     case 'D':
15695     case 'A':
15696       return C_Register;
15697     case 'I':
15698     case 'J':
15699     case 'K':
15700     case 'L':
15701     case 'M':
15702     case 'N':
15703     case 'G':
15704     case 'C':
15705     case 'e':
15706     case 'Z':
15707       return C_Other;
15708     default:
15709       break;
15710     }
15711   }
15712   return TargetLowering::getConstraintType(Constraint);
15713 }
15714
15715 /// Examine constraint type and operand type and determine a weight value.
15716 /// This object must already have been set up with the operand type
15717 /// and the current alternative constraint selected.
15718 TargetLowering::ConstraintWeight
15719   X86TargetLowering::getSingleConstraintMatchWeight(
15720     AsmOperandInfo &info, const char *constraint) const {
15721   ConstraintWeight weight = CW_Invalid;
15722   Value *CallOperandVal = info.CallOperandVal;
15723     // If we don't have a value, we can't do a match,
15724     // but allow it at the lowest weight.
15725   if (CallOperandVal == NULL)
15726     return CW_Default;
15727   Type *type = CallOperandVal->getType();
15728   // Look at the constraint type.
15729   switch (*constraint) {
15730   default:
15731     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15732   case 'R':
15733   case 'q':
15734   case 'Q':
15735   case 'a':
15736   case 'b':
15737   case 'c':
15738   case 'd':
15739   case 'S':
15740   case 'D':
15741   case 'A':
15742     if (CallOperandVal->getType()->isIntegerTy())
15743       weight = CW_SpecificReg;
15744     break;
15745   case 'f':
15746   case 't':
15747   case 'u':
15748       if (type->isFloatingPointTy())
15749         weight = CW_SpecificReg;
15750       break;
15751   case 'y':
15752       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15753         weight = CW_SpecificReg;
15754       break;
15755   case 'x':
15756   case 'Y':
15757     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15758         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15759       weight = CW_Register;
15760     break;
15761   case 'I':
15762     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15763       if (C->getZExtValue() <= 31)
15764         weight = CW_Constant;
15765     }
15766     break;
15767   case 'J':
15768     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15769       if (C->getZExtValue() <= 63)
15770         weight = CW_Constant;
15771     }
15772     break;
15773   case 'K':
15774     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15775       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15776         weight = CW_Constant;
15777     }
15778     break;
15779   case 'L':
15780     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15781       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15782         weight = CW_Constant;
15783     }
15784     break;
15785   case 'M':
15786     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15787       if (C->getZExtValue() <= 3)
15788         weight = CW_Constant;
15789     }
15790     break;
15791   case 'N':
15792     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15793       if (C->getZExtValue() <= 0xff)
15794         weight = CW_Constant;
15795     }
15796     break;
15797   case 'G':
15798   case 'C':
15799     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15800       weight = CW_Constant;
15801     }
15802     break;
15803   case 'e':
15804     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15805       if ((C->getSExtValue() >= -0x80000000LL) &&
15806           (C->getSExtValue() <= 0x7fffffffLL))
15807         weight = CW_Constant;
15808     }
15809     break;
15810   case 'Z':
15811     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15812       if (C->getZExtValue() <= 0xffffffff)
15813         weight = CW_Constant;
15814     }
15815     break;
15816   }
15817   return weight;
15818 }
15819
15820 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15821 /// with another that has more specific requirements based on the type of the
15822 /// corresponding operand.
15823 const char *X86TargetLowering::
15824 LowerXConstraint(EVT ConstraintVT) const {
15825   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15826   // 'f' like normal targets.
15827   if (ConstraintVT.isFloatingPoint()) {
15828     if (Subtarget->hasSSE2())
15829       return "Y";
15830     if (Subtarget->hasSSE1())
15831       return "x";
15832   }
15833
15834   return TargetLowering::LowerXConstraint(ConstraintVT);
15835 }
15836
15837 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15838 /// vector.  If it is invalid, don't add anything to Ops.
15839 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15840                                                      std::string &Constraint,
15841                                                      std::vector<SDValue>&Ops,
15842                                                      SelectionDAG &DAG) const {
15843   SDValue Result(0, 0);
15844
15845   // Only support length 1 constraints for now.
15846   if (Constraint.length() > 1) return;
15847
15848   char ConstraintLetter = Constraint[0];
15849   switch (ConstraintLetter) {
15850   default: break;
15851   case 'I':
15852     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15853       if (C->getZExtValue() <= 31) {
15854         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15855         break;
15856       }
15857     }
15858     return;
15859   case 'J':
15860     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15861       if (C->getZExtValue() <= 63) {
15862         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15863         break;
15864       }
15865     }
15866     return;
15867   case 'K':
15868     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15869       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15870         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15871         break;
15872       }
15873     }
15874     return;
15875   case 'N':
15876     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15877       if (C->getZExtValue() <= 255) {
15878         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15879         break;
15880       }
15881     }
15882     return;
15883   case 'e': {
15884     // 32-bit signed value
15885     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15886       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15887                                            C->getSExtValue())) {
15888         // Widen to 64 bits here to get it sign extended.
15889         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15890         break;
15891       }
15892     // FIXME gcc accepts some relocatable values here too, but only in certain
15893     // memory models; it's complicated.
15894     }
15895     return;
15896   }
15897   case 'Z': {
15898     // 32-bit unsigned value
15899     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15900       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15901                                            C->getZExtValue())) {
15902         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15903         break;
15904       }
15905     }
15906     // FIXME gcc accepts some relocatable values here too, but only in certain
15907     // memory models; it's complicated.
15908     return;
15909   }
15910   case 'i': {
15911     // Literal immediates are always ok.
15912     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15913       // Widen to 64 bits here to get it sign extended.
15914       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15915       break;
15916     }
15917
15918     // In any sort of PIC mode addresses need to be computed at runtime by
15919     // adding in a register or some sort of table lookup.  These can't
15920     // be used as immediates.
15921     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15922       return;
15923
15924     // If we are in non-pic codegen mode, we allow the address of a global (with
15925     // an optional displacement) to be used with 'i'.
15926     GlobalAddressSDNode *GA = 0;
15927     int64_t Offset = 0;
15928
15929     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15930     while (1) {
15931       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15932         Offset += GA->getOffset();
15933         break;
15934       } else if (Op.getOpcode() == ISD::ADD) {
15935         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15936           Offset += C->getZExtValue();
15937           Op = Op.getOperand(0);
15938           continue;
15939         }
15940       } else if (Op.getOpcode() == ISD::SUB) {
15941         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15942           Offset += -C->getZExtValue();
15943           Op = Op.getOperand(0);
15944           continue;
15945         }
15946       }
15947
15948       // Otherwise, this isn't something we can handle, reject it.
15949       return;
15950     }
15951
15952     const GlobalValue *GV = GA->getGlobal();
15953     // If we require an extra load to get this address, as in PIC mode, we
15954     // can't accept it.
15955     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15956                                                         getTargetMachine())))
15957       return;
15958
15959     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15960                                         GA->getValueType(0), Offset);
15961     break;
15962   }
15963   }
15964
15965   if (Result.getNode()) {
15966     Ops.push_back(Result);
15967     return;
15968   }
15969   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15970 }
15971
15972 std::pair<unsigned, const TargetRegisterClass*>
15973 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15974                                                 EVT VT) const {
15975   // First, see if this is a constraint that directly corresponds to an LLVM
15976   // register class.
15977   if (Constraint.size() == 1) {
15978     // GCC Constraint Letters
15979     switch (Constraint[0]) {
15980     default: break;
15981       // TODO: Slight differences here in allocation order and leaving
15982       // RIP in the class. Do they matter any more here than they do
15983       // in the normal allocation?
15984     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15985       if (Subtarget->is64Bit()) {
15986         if (VT == MVT::i32 || VT == MVT::f32)
15987           return std::make_pair(0U, &X86::GR32RegClass);
15988         if (VT == MVT::i16)
15989           return std::make_pair(0U, &X86::GR16RegClass);
15990         if (VT == MVT::i8 || VT == MVT::i1)
15991           return std::make_pair(0U, &X86::GR8RegClass);
15992         if (VT == MVT::i64 || VT == MVT::f64)
15993           return std::make_pair(0U, &X86::GR64RegClass);
15994         break;
15995       }
15996       // 32-bit fallthrough
15997     case 'Q':   // Q_REGS
15998       if (VT == MVT::i32 || VT == MVT::f32)
15999         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16000       if (VT == MVT::i16)
16001         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16002       if (VT == MVT::i8 || VT == MVT::i1)
16003         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16004       if (VT == MVT::i64)
16005         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16006       break;
16007     case 'r':   // GENERAL_REGS
16008     case 'l':   // INDEX_REGS
16009       if (VT == MVT::i8 || VT == MVT::i1)
16010         return std::make_pair(0U, &X86::GR8RegClass);
16011       if (VT == MVT::i16)
16012         return std::make_pair(0U, &X86::GR16RegClass);
16013       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16014         return std::make_pair(0U, &X86::GR32RegClass);
16015       return std::make_pair(0U, &X86::GR64RegClass);
16016     case 'R':   // LEGACY_REGS
16017       if (VT == MVT::i8 || VT == MVT::i1)
16018         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16019       if (VT == MVT::i16)
16020         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16021       if (VT == MVT::i32 || !Subtarget->is64Bit())
16022         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16023       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16024     case 'f':  // FP Stack registers.
16025       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16026       // value to the correct fpstack register class.
16027       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16028         return std::make_pair(0U, &X86::RFP32RegClass);
16029       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16030         return std::make_pair(0U, &X86::RFP64RegClass);
16031       return std::make_pair(0U, &X86::RFP80RegClass);
16032     case 'y':   // MMX_REGS if MMX allowed.
16033       if (!Subtarget->hasMMX()) break;
16034       return std::make_pair(0U, &X86::VR64RegClass);
16035     case 'Y':   // SSE_REGS if SSE2 allowed
16036       if (!Subtarget->hasSSE2()) break;
16037       // FALL THROUGH.
16038     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16039       if (!Subtarget->hasSSE1()) break;
16040
16041       switch (VT.getSimpleVT().SimpleTy) {
16042       default: break;
16043       // Scalar SSE types.
16044       case MVT::f32:
16045       case MVT::i32:
16046         return std::make_pair(0U, &X86::FR32RegClass);
16047       case MVT::f64:
16048       case MVT::i64:
16049         return std::make_pair(0U, &X86::FR64RegClass);
16050       // Vector types.
16051       case MVT::v16i8:
16052       case MVT::v8i16:
16053       case MVT::v4i32:
16054       case MVT::v2i64:
16055       case MVT::v4f32:
16056       case MVT::v2f64:
16057         return std::make_pair(0U, &X86::VR128RegClass);
16058       // AVX types.
16059       case MVT::v32i8:
16060       case MVT::v16i16:
16061       case MVT::v8i32:
16062       case MVT::v4i64:
16063       case MVT::v8f32:
16064       case MVT::v4f64:
16065         return std::make_pair(0U, &X86::VR256RegClass);
16066       }
16067       break;
16068     }
16069   }
16070
16071   // Use the default implementation in TargetLowering to convert the register
16072   // constraint into a member of a register class.
16073   std::pair<unsigned, const TargetRegisterClass*> Res;
16074   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16075
16076   // Not found as a standard register?
16077   if (Res.second == 0) {
16078     // Map st(0) -> st(7) -> ST0
16079     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16080         tolower(Constraint[1]) == 's' &&
16081         tolower(Constraint[2]) == 't' &&
16082         Constraint[3] == '(' &&
16083         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16084         Constraint[5] == ')' &&
16085         Constraint[6] == '}') {
16086
16087       Res.first = X86::ST0+Constraint[4]-'0';
16088       Res.second = &X86::RFP80RegClass;
16089       return Res;
16090     }
16091
16092     // GCC allows "st(0)" to be called just plain "st".
16093     if (StringRef("{st}").equals_lower(Constraint)) {
16094       Res.first = X86::ST0;
16095       Res.second = &X86::RFP80RegClass;
16096       return Res;
16097     }
16098
16099     // flags -> EFLAGS
16100     if (StringRef("{flags}").equals_lower(Constraint)) {
16101       Res.first = X86::EFLAGS;
16102       Res.second = &X86::CCRRegClass;
16103       return Res;
16104     }
16105
16106     // 'A' means EAX + EDX.
16107     if (Constraint == "A") {
16108       Res.first = X86::EAX;
16109       Res.second = &X86::GR32_ADRegClass;
16110       return Res;
16111     }
16112     return Res;
16113   }
16114
16115   // Otherwise, check to see if this is a register class of the wrong value
16116   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16117   // turn into {ax},{dx}.
16118   if (Res.second->hasType(VT))
16119     return Res;   // Correct type already, nothing to do.
16120
16121   // All of the single-register GCC register classes map their values onto
16122   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16123   // really want an 8-bit or 32-bit register, map to the appropriate register
16124   // class and return the appropriate register.
16125   if (Res.second == &X86::GR16RegClass) {
16126     if (VT == MVT::i8) {
16127       unsigned DestReg = 0;
16128       switch (Res.first) {
16129       default: break;
16130       case X86::AX: DestReg = X86::AL; break;
16131       case X86::DX: DestReg = X86::DL; break;
16132       case X86::CX: DestReg = X86::CL; break;
16133       case X86::BX: DestReg = X86::BL; break;
16134       }
16135       if (DestReg) {
16136         Res.first = DestReg;
16137         Res.second = &X86::GR8RegClass;
16138       }
16139     } else if (VT == MVT::i32) {
16140       unsigned DestReg = 0;
16141       switch (Res.first) {
16142       default: break;
16143       case X86::AX: DestReg = X86::EAX; break;
16144       case X86::DX: DestReg = X86::EDX; break;
16145       case X86::CX: DestReg = X86::ECX; break;
16146       case X86::BX: DestReg = X86::EBX; break;
16147       case X86::SI: DestReg = X86::ESI; break;
16148       case X86::DI: DestReg = X86::EDI; break;
16149       case X86::BP: DestReg = X86::EBP; break;
16150       case X86::SP: DestReg = X86::ESP; break;
16151       }
16152       if (DestReg) {
16153         Res.first = DestReg;
16154         Res.second = &X86::GR32RegClass;
16155       }
16156     } else if (VT == MVT::i64) {
16157       unsigned DestReg = 0;
16158       switch (Res.first) {
16159       default: break;
16160       case X86::AX: DestReg = X86::RAX; break;
16161       case X86::DX: DestReg = X86::RDX; break;
16162       case X86::CX: DestReg = X86::RCX; break;
16163       case X86::BX: DestReg = X86::RBX; break;
16164       case X86::SI: DestReg = X86::RSI; break;
16165       case X86::DI: DestReg = X86::RDI; break;
16166       case X86::BP: DestReg = X86::RBP; break;
16167       case X86::SP: DestReg = X86::RSP; break;
16168       }
16169       if (DestReg) {
16170         Res.first = DestReg;
16171         Res.second = &X86::GR64RegClass;
16172       }
16173     }
16174   } else if (Res.second == &X86::FR32RegClass ||
16175              Res.second == &X86::FR64RegClass ||
16176              Res.second == &X86::VR128RegClass) {
16177     // Handle references to XMM physical registers that got mapped into the
16178     // wrong class.  This can happen with constraints like {xmm0} where the
16179     // target independent register mapper will just pick the first match it can
16180     // find, ignoring the required type.
16181     if (VT == MVT::f32)
16182       Res.second = &X86::FR32RegClass;
16183     else if (VT == MVT::f64)
16184       Res.second = &X86::FR64RegClass;
16185     else if (X86::VR128RegClass.hasType(VT))
16186       Res.second = &X86::VR128RegClass;
16187   }
16188
16189   return Res;
16190 }