This patch optimizes shuffle instruction - generates 2 instructions instead of 4.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "X86.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference.  Idx is an index in the 128 bits we
64 /// want.  It need not be aligned to a 128-bit bounday.  That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67                                    SelectionDAG &DAG, DebugLoc dl) {
68   EVT VT = Vec.getValueType();
69   assert(VT.is256BitVector() && "Unexpected vector size!");
70   EVT ElVT = VT.getVectorElementType();
71   unsigned Factor = VT.getSizeInBits()/128;
72   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                   VT.getVectorNumElements()/Factor);
74
75   // Extract from UNDEF is UNDEF.
76   if (Vec.getOpcode() == ISD::UNDEF)
77     return DAG.getUNDEF(ResultVT);
78
79   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80   // we can match to VEXTRACTF128.
81   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83   // This is the index of the first element of the 128-bit chunk
84   // we want.
85   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                                * ElemsPerChunk);
87
88   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
89   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
90                                VecIdx);
91
92   return Result;
93 }
94
95 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference.  Idx is an index in the 128 bits
98 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101                                   unsigned IdxVal, SelectionDAG &DAG,
102                                   DebugLoc dl) {
103   // Inserting UNDEF is Result
104   if (Vec.getOpcode() == ISD::UNDEF)
105     return Result;
106
107   EVT VT = Vec.getValueType();
108   assert(VT.is128BitVector() && "Unexpected vector size!");
109
110   EVT ElVT = VT.getVectorElementType();
111   EVT ResultVT = Result.getValueType();
112
113   // Insert the relevant 128 bits.
114   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
115
116   // This is the index of the first element of the 128-bit chunk
117   // we want.
118   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
119                                * ElemsPerChunk);
120
121   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
122   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
123                      VecIdx);
124 }
125
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131                                    unsigned NumElems, SelectionDAG &DAG,
132                                    DebugLoc dl) {
133   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
135 }
136
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139   bool is64Bit = Subtarget->is64Bit();
140
141   if (Subtarget->isTargetEnvMacho()) {
142     if (is64Bit)
143       return new X86_64MachoTargetObjectFile();
144     return new TargetLoweringObjectFileMachO();
145   }
146
147   if (Subtarget->isTargetLinux())
148     return new X86LinuxTargetObjectFile();
149   if (Subtarget->isTargetELF())
150     return new TargetLoweringObjectFileELF();
151   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152     return new TargetLoweringObjectFileCOFF();
153   llvm_unreachable("unknown subtarget type");
154 }
155
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157   : TargetLowering(TM, createTLOF(TM)) {
158   Subtarget = &TM.getSubtarget<X86Subtarget>();
159   X86ScalarSSEf64 = Subtarget->hasSSE2();
160   X86ScalarSSEf32 = Subtarget->hasSSE1();
161   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
162
163   RegInfo = TM.getRegisterInfo();
164   TD = getTargetData();
165
166   // Set up the TargetLowering object.
167   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168
169   // X86 is weird, it always uses i8 for shift amounts and setcc results.
170   setBooleanContents(ZeroOrOneBooleanContent);
171   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174   // For 64-bit since we have so many registers use the ILP scheduler, for
175   // 32-bit code use the register pressure specific scheduling.
176   // For Atom, always use ILP scheduling.
177   if (Subtarget->isAtom())
178     setSchedulingPreference(Sched::ILP);
179   else if (Subtarget->is64Bit())
180     setSchedulingPreference(Sched::ILP);
181   else
182     setSchedulingPreference(Sched::RegPressure);
183   setStackPointerRegisterToSaveRestore(X86StackPtr);
184
185   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
186     // Setup Windows compiler runtime calls.
187     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
188     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
189     setLibcallName(RTLIB::SREM_I64, "_allrem");
190     setLibcallName(RTLIB::UREM_I64, "_aullrem");
191     setLibcallName(RTLIB::MUL_I64, "_allmul");
192     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
193     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
194     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
195     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
196     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
197
198     // The _ftol2 runtime function has an unusual calling conv, which
199     // is modeled by a special pseudo-instruction.
200     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
201     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
202     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
203     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
204   }
205
206   if (Subtarget->isTargetDarwin()) {
207     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
208     setUseUnderscoreSetJmp(false);
209     setUseUnderscoreLongJmp(false);
210   } else if (Subtarget->isTargetMingw()) {
211     // MS runtime is weird: it exports _setjmp, but longjmp!
212     setUseUnderscoreSetJmp(true);
213     setUseUnderscoreLongJmp(false);
214   } else {
215     setUseUnderscoreSetJmp(true);
216     setUseUnderscoreLongJmp(true);
217   }
218
219   // Set up the register classes.
220   addRegisterClass(MVT::i8, &X86::GR8RegClass);
221   addRegisterClass(MVT::i16, &X86::GR16RegClass);
222   addRegisterClass(MVT::i32, &X86::GR32RegClass);
223   if (Subtarget->is64Bit())
224     addRegisterClass(MVT::i64, &X86::GR64RegClass);
225
226   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
227
228   // We don't accept any truncstore of integer registers.
229   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
230   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
231   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
232   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
233   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
234   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
235
236   // SETOEQ and SETUNE require checking two conditions.
237   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
238   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
239   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
240   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
241   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
242   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
243
244   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
245   // operation.
246   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
247   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
248   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
249
250   if (Subtarget->is64Bit()) {
251     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
252     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
253   } else if (!TM.Options.UseSoftFloat) {
254     // We have an algorithm for SSE2->double, and we turn this into a
255     // 64-bit FILD followed by conditional FADD for other targets.
256     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
257     // We have an algorithm for SSE2, and we turn this into a 64-bit
258     // FILD for other targets.
259     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
260   }
261
262   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
263   // this operation.
264   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
265   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
266
267   if (!TM.Options.UseSoftFloat) {
268     // SSE has no i16 to fp conversion, only i32
269     if (X86ScalarSSEf32) {
270       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
271       // f32 and f64 cases are Legal, f80 case is not
272       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
273     } else {
274       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
275       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
276     }
277   } else {
278     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
279     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
280   }
281
282   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
283   // are Legal, f80 is custom lowered.
284   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
285   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
286
287   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
288   // this operation.
289   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
290   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
291
292   if (X86ScalarSSEf32) {
293     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
294     // f32 and f64 cases are Legal, f80 case is not
295     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
296   } else {
297     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
298     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
299   }
300
301   // Handle FP_TO_UINT by promoting the destination to a larger signed
302   // conversion.
303   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
304   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
305   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
306
307   if (Subtarget->is64Bit()) {
308     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
309     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
310   } else if (!TM.Options.UseSoftFloat) {
311     // Since AVX is a superset of SSE3, only check for SSE here.
312     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
313       // Expand FP_TO_UINT into a select.
314       // FIXME: We would like to use a Custom expander here eventually to do
315       // the optimal thing for SSE vs. the default expansion in the legalizer.
316       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
317     else
318       // With SSE3 we can use fisttpll to convert to a signed i64; without
319       // SSE, we're stuck with a fistpll.
320       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
321   }
322
323   if (isTargetFTOL()) {
324     // Use the _ftol2 runtime function, which has a pseudo-instruction
325     // to handle its weird calling convention.
326     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
327   }
328
329   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330   if (!X86ScalarSSEf64) {
331     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
332     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
333     if (Subtarget->is64Bit()) {
334       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
335       // Without SSE, i64->f64 goes through memory.
336       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
337     }
338   }
339
340   // Scalar integer divide and remainder are lowered to use operations that
341   // produce two results, to match the available instructions. This exposes
342   // the two-result form to trivial CSE, which is able to combine x/y and x%y
343   // into a single instruction.
344   //
345   // Scalar integer multiply-high is also lowered to use two-result
346   // operations, to match the available instructions. However, plain multiply
347   // (low) operations are left as Legal, as there are single-result
348   // instructions for this in x86. Using the two-result multiply instructions
349   // when both high and low results are needed must be arranged by dagcombine.
350   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
351     MVT VT = IntVTs[i];
352     setOperationAction(ISD::MULHS, VT, Expand);
353     setOperationAction(ISD::MULHU, VT, Expand);
354     setOperationAction(ISD::SDIV, VT, Expand);
355     setOperationAction(ISD::UDIV, VT, Expand);
356     setOperationAction(ISD::SREM, VT, Expand);
357     setOperationAction(ISD::UREM, VT, Expand);
358
359     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360     setOperationAction(ISD::ADDC, VT, Custom);
361     setOperationAction(ISD::ADDE, VT, Custom);
362     setOperationAction(ISD::SUBC, VT, Custom);
363     setOperationAction(ISD::SUBE, VT, Custom);
364   }
365
366   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
367   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
368   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
369   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
370   if (Subtarget->is64Bit())
371     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
374   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
375   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
376   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
378   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
379   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
380
381   // Promote the i8 variants and force them on up to i32 which has a shorter
382   // encoding.
383   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
384   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
385   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
386   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
387   if (Subtarget->hasBMI()) {
388     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
389     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
390     if (Subtarget->is64Bit())
391       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
392   } else {
393     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
394     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
397   }
398
399   if (Subtarget->hasLZCNT()) {
400     // When promoting the i8 variants, force them to i32 for a shorter
401     // encoding.
402     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
403     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
404     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
405     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
406     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
407     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
408     if (Subtarget->is64Bit())
409       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
410   } else {
411     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
412     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
413     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
414     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
415     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
416     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
417     if (Subtarget->is64Bit()) {
418       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
419       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
420     }
421   }
422
423   if (Subtarget->hasPOPCNT()) {
424     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
425   } else {
426     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
427     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
428     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
429     if (Subtarget->is64Bit())
430       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
431   }
432
433   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
434   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
435
436   // These should be promoted to a larger select which is supported.
437   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
438   // X86 wants to expand cmov itself.
439   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
440   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
441   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
442   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
443   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
445   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
446   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
447   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
448   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
451   if (Subtarget->is64Bit()) {
452     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
453     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
454   }
455   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
456
457   // Darwin ABI issue.
458   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
459   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
460   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
461   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
462   if (Subtarget->is64Bit())
463     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
464   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
465   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
466   if (Subtarget->is64Bit()) {
467     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
468     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
469     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
470     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
471     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
472   }
473   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
474   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
475   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
476   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
477   if (Subtarget->is64Bit()) {
478     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
479     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
480     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
481   }
482
483   if (Subtarget->hasSSE1())
484     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
485
486   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
487   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
488
489   // On X86 and X86-64, atomic operations are lowered to locked instructions.
490   // Locked instructions, in turn, have implicit fence semantics (all memory
491   // operations are flushed before issuing the locked instruction, and they
492   // are not buffered), so we can fold away the common pattern of
493   // fence-atomic-fence.
494   setShouldFoldAtomicFences(true);
495
496   // Expand certain atomics
497   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
498     MVT VT = IntVTs[i];
499     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
500     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
501     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
502   }
503
504   if (!Subtarget->is64Bit()) {
505     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
513   }
514
515   if (Subtarget->hasCmpxchg16b()) {
516     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
517   }
518
519   // FIXME - use subtarget debug flags
520   if (!Subtarget->isTargetDarwin() &&
521       !Subtarget->isTargetELF() &&
522       !Subtarget->isTargetCygMing()) {
523     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
524   }
525
526   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
527   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
528   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
529   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
530   if (Subtarget->is64Bit()) {
531     setExceptionPointerRegister(X86::RAX);
532     setExceptionSelectorRegister(X86::RDX);
533   } else {
534     setExceptionPointerRegister(X86::EAX);
535     setExceptionSelectorRegister(X86::EDX);
536   }
537   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
538   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
539
540   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
541   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
542
543   setOperationAction(ISD::TRAP, MVT::Other, Legal);
544
545   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
546   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
547   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
548   if (Subtarget->is64Bit()) {
549     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
550     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
551   } else {
552     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
553     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
554   }
555
556   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
557   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
558
559   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
560     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
561                        MVT::i64 : MVT::i32, Custom);
562   else if (TM.Options.EnableSegmentedStacks)
563     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
564                        MVT::i64 : MVT::i32, Custom);
565   else
566     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
567                        MVT::i64 : MVT::i32, Expand);
568
569   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
570     // f32 and f64 use SSE.
571     // Set up the FP register classes.
572     addRegisterClass(MVT::f32, &X86::FR32RegClass);
573     addRegisterClass(MVT::f64, &X86::FR64RegClass);
574
575     // Use ANDPD to simulate FABS.
576     setOperationAction(ISD::FABS , MVT::f64, Custom);
577     setOperationAction(ISD::FABS , MVT::f32, Custom);
578
579     // Use XORP to simulate FNEG.
580     setOperationAction(ISD::FNEG , MVT::f64, Custom);
581     setOperationAction(ISD::FNEG , MVT::f32, Custom);
582
583     // Use ANDPD and ORPD to simulate FCOPYSIGN.
584     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
585     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
586
587     // Lower this to FGETSIGNx86 plus an AND.
588     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
589     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
590
591     // We don't support sin/cos/fmod
592     setOperationAction(ISD::FSIN , MVT::f64, Expand);
593     setOperationAction(ISD::FCOS , MVT::f64, Expand);
594     setOperationAction(ISD::FSIN , MVT::f32, Expand);
595     setOperationAction(ISD::FCOS , MVT::f32, Expand);
596
597     // Expand FP immediates into loads from the stack, except for the special
598     // cases we handle.
599     addLegalFPImmediate(APFloat(+0.0)); // xorpd
600     addLegalFPImmediate(APFloat(+0.0f)); // xorps
601   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
602     // Use SSE for f32, x87 for f64.
603     // Set up the FP register classes.
604     addRegisterClass(MVT::f32, &X86::FR32RegClass);
605     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
606
607     // Use ANDPS to simulate FABS.
608     setOperationAction(ISD::FABS , MVT::f32, Custom);
609
610     // Use XORP to simulate FNEG.
611     setOperationAction(ISD::FNEG , MVT::f32, Custom);
612
613     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
614
615     // Use ANDPS and ORPS to simulate FCOPYSIGN.
616     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
617     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
618
619     // We don't support sin/cos/fmod
620     setOperationAction(ISD::FSIN , MVT::f32, Expand);
621     setOperationAction(ISD::FCOS , MVT::f32, Expand);
622
623     // Special cases we handle for FP constants.
624     addLegalFPImmediate(APFloat(+0.0f)); // xorps
625     addLegalFPImmediate(APFloat(+0.0)); // FLD0
626     addLegalFPImmediate(APFloat(+1.0)); // FLD1
627     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
628     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
629
630     if (!TM.Options.UnsafeFPMath) {
631       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
632       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
633     }
634   } else if (!TM.Options.UseSoftFloat) {
635     // f32 and f64 in x87.
636     // Set up the FP register classes.
637     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
638     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
639
640     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
641     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
642     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
643     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
644
645     if (!TM.Options.UnsafeFPMath) {
646       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
647       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
648     }
649     addLegalFPImmediate(APFloat(+0.0)); // FLD0
650     addLegalFPImmediate(APFloat(+1.0)); // FLD1
651     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
652     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
653     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
654     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
655     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
656     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
657   }
658
659   // We don't support FMA.
660   setOperationAction(ISD::FMA, MVT::f64, Expand);
661   setOperationAction(ISD::FMA, MVT::f32, Expand);
662
663   // Long double always uses X87.
664   if (!TM.Options.UseSoftFloat) {
665     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
666     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
667     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
668     {
669       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
670       addLegalFPImmediate(TmpFlt);  // FLD0
671       TmpFlt.changeSign();
672       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
673
674       bool ignored;
675       APFloat TmpFlt2(+1.0);
676       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
677                       &ignored);
678       addLegalFPImmediate(TmpFlt2);  // FLD1
679       TmpFlt2.changeSign();
680       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
681     }
682
683     if (!TM.Options.UnsafeFPMath) {
684       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
685       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
686     }
687
688     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
689     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
690     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
691     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
692     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
693     setOperationAction(ISD::FMA, MVT::f80, Expand);
694   }
695
696   // Always use a library call for pow.
697   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
698   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
699   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
700
701   setOperationAction(ISD::FLOG, MVT::f80, Expand);
702   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
703   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
704   setOperationAction(ISD::FEXP, MVT::f80, Expand);
705   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
706
707   // First set operation action for all vector types to either promote
708   // (for widening) or expand (for scalarization). Then we will selectively
709   // turn on ones that can be effectively codegen'd.
710   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
711            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
712     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
727     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
729     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
730     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
765     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
770     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
771              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
772       setTruncStoreAction((MVT::SimpleValueType)VT,
773                           (MVT::SimpleValueType)InnerVT, Expand);
774     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
775     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
776     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
777   }
778
779   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
780   // with -msoft-float, disable use of MMX as well.
781   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
782     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
783     // No operations on x86mmx supported, everything uses intrinsics.
784   }
785
786   // MMX-sized vectors (other than x86mmx) are expected to be expanded
787   // into smaller operations.
788   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
789   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
790   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
791   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
792   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
793   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
794   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
795   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
796   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
797   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
798   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
799   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
800   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
801   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
802   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
803   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
804   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
805   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
806   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
807   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
808   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
809   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
810   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
811   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
812   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
813   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
814   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
815   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
816   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
817
818   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
819     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
820
821     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
822     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
823     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
824     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
825     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
826     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
827     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
828     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
829     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
830     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
831     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
832   }
833
834   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
835     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
836
837     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
838     // registers cannot be used even for integer operations.
839     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
840     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
841     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
842     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
843
844     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
845     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
846     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
847     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
848     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
849     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
850     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
851     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
852     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
853     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
854     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
855     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
856     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
857     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
858     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
859     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
860
861     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
862     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
863     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
864     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
865
866     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
867     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
868     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
869     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
870     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
871
872     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
873     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
874       MVT 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,       VT, Custom);
882       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
883       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
884     }
885
886     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
887     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
888     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
889     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
891     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
892
893     if (Subtarget->is64Bit()) {
894       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
895       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
896     }
897
898     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
899     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
900       MVT VT = (MVT::SimpleValueType)i;
901
902       // Do not attempt to promote non-128-bit vectors
903       if (!VT.is128BitVector())
904         continue;
905
906       setOperationAction(ISD::AND,    VT, Promote);
907       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
908       setOperationAction(ISD::OR,     VT, Promote);
909       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
910       setOperationAction(ISD::XOR,    VT, Promote);
911       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
912       setOperationAction(ISD::LOAD,   VT, Promote);
913       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
914       setOperationAction(ISD::SELECT, VT, Promote);
915       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
916     }
917
918     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
919
920     // Custom lower v2i64 and v2f64 selects.
921     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
922     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
923     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
924     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
925
926     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
927     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
928   }
929
930   if (Subtarget->hasSSE41()) {
931     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
932     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
933     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
934     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
935     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
936     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
937     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
938     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
939     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
940     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
941
942     // FIXME: Do we need to handle scalar-to-vector here?
943     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
944
945     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
946     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
947     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
948     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
949     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
950
951     // i8 and i16 vectors are custom , because the source register and source
952     // source memory operand types are not the same width.  f32 vectors are
953     // custom since the immediate controlling the insert encodes additional
954     // information.
955     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
956     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
957     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
958     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
959
960     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
961     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
962     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
963     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
964
965     // FIXME: these should be Legal but thats only for the case where
966     // the index is constant.  For now custom expand to deal with that.
967     if (Subtarget->is64Bit()) {
968       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
969       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
970     }
971   }
972
973   if (Subtarget->hasSSE2()) {
974     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
975     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
976
977     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
978     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
979
980     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
981     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
982
983     if (Subtarget->hasAVX2()) {
984       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
985       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
986
987       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
988       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
989
990       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
991     } else {
992       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
993       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
994
995       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
996       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
997
998       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
999     }
1000   }
1001
1002   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1003     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1004     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1005     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1006     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1007     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1008     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1009
1010     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1011     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1012     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1013
1014     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1015     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1016     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1017     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1018     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1019     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1020
1021     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1022     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1023     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1024     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1025     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1026     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1027
1028     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1029     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1030     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1031
1032     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1033     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1034
1035     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1036     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1037
1038     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1039     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1040
1041     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1042     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1043     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1044     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1045
1046     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1047     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1048     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1049
1050     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1051     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1052     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1053     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1054
1055     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1056       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1057       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1058       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1059       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1060       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1061       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1062     }
1063
1064     if (Subtarget->hasAVX2()) {
1065       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1066       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1067       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1068       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1069
1070       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1071       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1072       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1073       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1074
1075       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1076       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1077       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1078       // Don't lower v32i8 because there is no 128-bit byte mul
1079
1080       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1081
1082       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1083       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1084
1085       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1086       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1087
1088       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1089     } else {
1090       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1091       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1092       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1093       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1094
1095       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1096       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1097       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1098       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1099
1100       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1101       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1102       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1103       // Don't lower v32i8 because there is no 128-bit byte mul
1104
1105       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1106       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1107
1108       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1109       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1110
1111       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1112     }
1113
1114     // Custom lower several nodes for 256-bit types.
1115     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1116              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1117       MVT VT = (MVT::SimpleValueType)i;
1118
1119       // Extract subvector is special because the value type
1120       // (result) is 128-bit but the source is 256-bit wide.
1121       if (VT.is128BitVector())
1122         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1123
1124       // Do not attempt to custom lower other non-256-bit vectors
1125       if (!VT.is256BitVector())
1126         continue;
1127
1128       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1129       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1130       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1131       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1132       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1133       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1134       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1135     }
1136
1137     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1138     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1139       MVT VT = (MVT::SimpleValueType)i;
1140
1141       // Do not attempt to promote non-256-bit vectors
1142       if (!VT.is256BitVector())
1143         continue;
1144
1145       setOperationAction(ISD::AND,    VT, Promote);
1146       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1147       setOperationAction(ISD::OR,     VT, Promote);
1148       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1149       setOperationAction(ISD::XOR,    VT, Promote);
1150       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1151       setOperationAction(ISD::LOAD,   VT, Promote);
1152       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1153       setOperationAction(ISD::SELECT, VT, Promote);
1154       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1155     }
1156   }
1157
1158   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1159   // of this type with custom code.
1160   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1161            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1162     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1163                        Custom);
1164   }
1165
1166   // We want to custom lower some of our intrinsics.
1167   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1168   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1169
1170
1171   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1172   // handle type legalization for these operations here.
1173   //
1174   // FIXME: We really should do custom legalization for addition and
1175   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1176   // than generic legalization for 64-bit multiplication-with-overflow, though.
1177   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1178     // Add/Sub/Mul with overflow operations are custom lowered.
1179     MVT VT = IntVTs[i];
1180     setOperationAction(ISD::SADDO, VT, Custom);
1181     setOperationAction(ISD::UADDO, VT, Custom);
1182     setOperationAction(ISD::SSUBO, VT, Custom);
1183     setOperationAction(ISD::USUBO, VT, Custom);
1184     setOperationAction(ISD::SMULO, VT, Custom);
1185     setOperationAction(ISD::UMULO, VT, Custom);
1186   }
1187
1188   // There are no 8-bit 3-address imul/mul instructions
1189   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1190   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1191
1192   if (!Subtarget->is64Bit()) {
1193     // These libcalls are not available in 32-bit.
1194     setLibcallName(RTLIB::SHL_I128, 0);
1195     setLibcallName(RTLIB::SRL_I128, 0);
1196     setLibcallName(RTLIB::SRA_I128, 0);
1197   }
1198
1199   // We have target-specific dag combine patterns for the following nodes:
1200   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1201   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1202   setTargetDAGCombine(ISD::VSELECT);
1203   setTargetDAGCombine(ISD::SELECT);
1204   setTargetDAGCombine(ISD::SHL);
1205   setTargetDAGCombine(ISD::SRA);
1206   setTargetDAGCombine(ISD::SRL);
1207   setTargetDAGCombine(ISD::OR);
1208   setTargetDAGCombine(ISD::AND);
1209   setTargetDAGCombine(ISD::ADD);
1210   setTargetDAGCombine(ISD::FADD);
1211   setTargetDAGCombine(ISD::FSUB);
1212   setTargetDAGCombine(ISD::FMA);
1213   setTargetDAGCombine(ISD::SUB);
1214   setTargetDAGCombine(ISD::LOAD);
1215   setTargetDAGCombine(ISD::STORE);
1216   setTargetDAGCombine(ISD::ZERO_EXTEND);
1217   setTargetDAGCombine(ISD::ANY_EXTEND);
1218   setTargetDAGCombine(ISD::SIGN_EXTEND);
1219   setTargetDAGCombine(ISD::TRUNCATE);
1220   setTargetDAGCombine(ISD::UINT_TO_FP);
1221   setTargetDAGCombine(ISD::SINT_TO_FP);
1222   setTargetDAGCombine(ISD::SETCC);
1223   setTargetDAGCombine(ISD::FP_TO_SINT);
1224   if (Subtarget->is64Bit())
1225     setTargetDAGCombine(ISD::MUL);
1226   setTargetDAGCombine(ISD::XOR);
1227
1228   computeRegisterProperties();
1229
1230   // On Darwin, -Os means optimize for size without hurting performance,
1231   // do not reduce the limit.
1232   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1233   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1234   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1235   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1236   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1237   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1238   setPrefLoopAlignment(4); // 2^4 bytes.
1239   benefitFromCodePlacementOpt = true;
1240
1241   // Predictable cmov don't hurt on atom because it's in-order.
1242   predictableSelectIsExpensive = !Subtarget->isAtom();
1243
1244   setPrefFunctionAlignment(4); // 2^4 bytes.
1245 }
1246
1247
1248 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1249   if (!VT.isVector()) return MVT::i8;
1250   return VT.changeVectorElementTypeToInteger();
1251 }
1252
1253
1254 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1255 /// the desired ByVal argument alignment.
1256 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1257   if (MaxAlign == 16)
1258     return;
1259   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1260     if (VTy->getBitWidth() == 128)
1261       MaxAlign = 16;
1262   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1263     unsigned EltAlign = 0;
1264     getMaxByValAlign(ATy->getElementType(), EltAlign);
1265     if (EltAlign > MaxAlign)
1266       MaxAlign = EltAlign;
1267   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1268     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1269       unsigned EltAlign = 0;
1270       getMaxByValAlign(STy->getElementType(i), EltAlign);
1271       if (EltAlign > MaxAlign)
1272         MaxAlign = EltAlign;
1273       if (MaxAlign == 16)
1274         break;
1275     }
1276   }
1277 }
1278
1279 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1280 /// function arguments in the caller parameter area. For X86, aggregates
1281 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1282 /// are at 4-byte boundaries.
1283 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1284   if (Subtarget->is64Bit()) {
1285     // Max of 8 and alignment of type.
1286     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1287     if (TyAlign > 8)
1288       return TyAlign;
1289     return 8;
1290   }
1291
1292   unsigned Align = 4;
1293   if (Subtarget->hasSSE1())
1294     getMaxByValAlign(Ty, Align);
1295   return Align;
1296 }
1297
1298 /// getOptimalMemOpType - Returns the target specific optimal type for load
1299 /// and store operations as a result of memset, memcpy, and memmove
1300 /// lowering. If DstAlign is zero that means it's safe to destination
1301 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1302 /// means there isn't a need to check it against alignment requirement,
1303 /// probably because the source does not need to be loaded. If
1304 /// 'IsZeroVal' is true, that means it's safe to return a
1305 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1306 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1307 /// constant so it does not need to be loaded.
1308 /// It returns EVT::Other if the type should be determined using generic
1309 /// target-independent logic.
1310 EVT
1311 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1312                                        unsigned DstAlign, unsigned SrcAlign,
1313                                        bool IsZeroVal,
1314                                        bool MemcpyStrSrc,
1315                                        MachineFunction &MF) const {
1316   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1317   // linux.  This is because the stack realignment code can't handle certain
1318   // cases like PR2962.  This should be removed when PR2962 is fixed.
1319   const Function *F = MF.getFunction();
1320   if (IsZeroVal &&
1321       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1322     if (Size >= 16 &&
1323         (Subtarget->isUnalignedMemAccessFast() ||
1324          ((DstAlign == 0 || DstAlign >= 16) &&
1325           (SrcAlign == 0 || SrcAlign >= 16))) &&
1326         Subtarget->getStackAlignment() >= 16) {
1327       if (Subtarget->getStackAlignment() >= 32) {
1328         if (Subtarget->hasAVX2())
1329           return MVT::v8i32;
1330         if (Subtarget->hasAVX())
1331           return MVT::v8f32;
1332       }
1333       if (Subtarget->hasSSE2())
1334         return MVT::v4i32;
1335       if (Subtarget->hasSSE1())
1336         return MVT::v4f32;
1337     } else if (!MemcpyStrSrc && Size >= 8 &&
1338                !Subtarget->is64Bit() &&
1339                Subtarget->getStackAlignment() >= 8 &&
1340                Subtarget->hasSSE2()) {
1341       // Do not use f64 to lower memcpy if source is string constant. It's
1342       // better to use i32 to avoid the loads.
1343       return MVT::f64;
1344     }
1345   }
1346   if (Subtarget->is64Bit() && Size >= 8)
1347     return MVT::i64;
1348   return MVT::i32;
1349 }
1350
1351 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1352 /// current function.  The returned value is a member of the
1353 /// MachineJumpTableInfo::JTEntryKind enum.
1354 unsigned X86TargetLowering::getJumpTableEncoding() const {
1355   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1356   // symbol.
1357   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1358       Subtarget->isPICStyleGOT())
1359     return MachineJumpTableInfo::EK_Custom32;
1360
1361   // Otherwise, use the normal jump table encoding heuristics.
1362   return TargetLowering::getJumpTableEncoding();
1363 }
1364
1365 const MCExpr *
1366 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1367                                              const MachineBasicBlock *MBB,
1368                                              unsigned uid,MCContext &Ctx) const{
1369   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1370          Subtarget->isPICStyleGOT());
1371   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1372   // entries.
1373   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1374                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1375 }
1376
1377 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1378 /// jumptable.
1379 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1380                                                     SelectionDAG &DAG) const {
1381   if (!Subtarget->is64Bit())
1382     // This doesn't have DebugLoc associated with it, but is not really the
1383     // same as a Register.
1384     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1385   return Table;
1386 }
1387
1388 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1389 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1390 /// MCExpr.
1391 const MCExpr *X86TargetLowering::
1392 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1393                              MCContext &Ctx) const {
1394   // X86-64 uses RIP relative addressing based on the jump table label.
1395   if (Subtarget->isPICStyleRIPRel())
1396     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1397
1398   // Otherwise, the reference is relative to the PIC base.
1399   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1400 }
1401
1402 // FIXME: Why this routine is here? Move to RegInfo!
1403 std::pair<const TargetRegisterClass*, uint8_t>
1404 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1405   const TargetRegisterClass *RRC = 0;
1406   uint8_t Cost = 1;
1407   switch (VT.getSimpleVT().SimpleTy) {
1408   default:
1409     return TargetLowering::findRepresentativeClass(VT);
1410   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1411     RRC = Subtarget->is64Bit() ?
1412       (const TargetRegisterClass*)&X86::GR64RegClass :
1413       (const TargetRegisterClass*)&X86::GR32RegClass;
1414     break;
1415   case MVT::x86mmx:
1416     RRC = &X86::VR64RegClass;
1417     break;
1418   case MVT::f32: case MVT::f64:
1419   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1420   case MVT::v4f32: case MVT::v2f64:
1421   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1422   case MVT::v4f64:
1423     RRC = &X86::VR128RegClass;
1424     break;
1425   }
1426   return std::make_pair(RRC, Cost);
1427 }
1428
1429 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1430                                                unsigned &Offset) const {
1431   if (!Subtarget->isTargetLinux())
1432     return false;
1433
1434   if (Subtarget->is64Bit()) {
1435     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1436     Offset = 0x28;
1437     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1438       AddressSpace = 256;
1439     else
1440       AddressSpace = 257;
1441   } else {
1442     // %gs:0x14 on i386
1443     Offset = 0x14;
1444     AddressSpace = 256;
1445   }
1446   return true;
1447 }
1448
1449
1450 //===----------------------------------------------------------------------===//
1451 //               Return Value Calling Convention Implementation
1452 //===----------------------------------------------------------------------===//
1453
1454 #include "X86GenCallingConv.inc"
1455
1456 bool
1457 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1458                                   MachineFunction &MF, bool isVarArg,
1459                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1460                         LLVMContext &Context) const {
1461   SmallVector<CCValAssign, 16> RVLocs;
1462   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1463                  RVLocs, Context);
1464   return CCInfo.CheckReturn(Outs, RetCC_X86);
1465 }
1466
1467 SDValue
1468 X86TargetLowering::LowerReturn(SDValue Chain,
1469                                CallingConv::ID CallConv, bool isVarArg,
1470                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1471                                const SmallVectorImpl<SDValue> &OutVals,
1472                                DebugLoc dl, SelectionDAG &DAG) const {
1473   MachineFunction &MF = DAG.getMachineFunction();
1474   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1475
1476   SmallVector<CCValAssign, 16> RVLocs;
1477   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1478                  RVLocs, *DAG.getContext());
1479   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1480
1481   // Add the regs to the liveout set for the function.
1482   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1483   for (unsigned i = 0; i != RVLocs.size(); ++i)
1484     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1485       MRI.addLiveOut(RVLocs[i].getLocReg());
1486
1487   SDValue Flag;
1488
1489   SmallVector<SDValue, 6> RetOps;
1490   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1491   // Operand #1 = Bytes To Pop
1492   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1493                    MVT::i16));
1494
1495   // Copy the result values into the output registers.
1496   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1497     CCValAssign &VA = RVLocs[i];
1498     assert(VA.isRegLoc() && "Can only return in registers!");
1499     SDValue ValToCopy = OutVals[i];
1500     EVT ValVT = ValToCopy.getValueType();
1501
1502     // Promote values to the appropriate types
1503     if (VA.getLocInfo() == CCValAssign::SExt)
1504       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1505     else if (VA.getLocInfo() == CCValAssign::ZExt)
1506       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1507     else if (VA.getLocInfo() == CCValAssign::AExt)
1508       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1509     else if (VA.getLocInfo() == CCValAssign::BCvt)
1510       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1511
1512     // If this is x86-64, and we disabled SSE, we can't return FP values,
1513     // or SSE or MMX vectors.
1514     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1515          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1516           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1517       report_fatal_error("SSE register return with SSE disabled");
1518     }
1519     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1520     // llvm-gcc has never done it right and no one has noticed, so this
1521     // should be OK for now.
1522     if (ValVT == MVT::f64 &&
1523         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1524       report_fatal_error("SSE2 register return with SSE2 disabled");
1525
1526     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1527     // the RET instruction and handled by the FP Stackifier.
1528     if (VA.getLocReg() == X86::ST0 ||
1529         VA.getLocReg() == X86::ST1) {
1530       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1531       // change the value to the FP stack register class.
1532       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1533         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1534       RetOps.push_back(ValToCopy);
1535       // Don't emit a copytoreg.
1536       continue;
1537     }
1538
1539     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1540     // which is returned in RAX / RDX.
1541     if (Subtarget->is64Bit()) {
1542       if (ValVT == MVT::x86mmx) {
1543         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1544           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1545           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1546                                   ValToCopy);
1547           // If we don't have SSE2 available, convert to v4f32 so the generated
1548           // register is legal.
1549           if (!Subtarget->hasSSE2())
1550             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1551         }
1552       }
1553     }
1554
1555     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1556     Flag = Chain.getValue(1);
1557   }
1558
1559   // The x86-64 ABI for returning structs by value requires that we copy
1560   // the sret argument into %rax for the return. We saved the argument into
1561   // a virtual register in the entry block, so now we copy the value out
1562   // and into %rax.
1563   if (Subtarget->is64Bit() &&
1564       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1565     MachineFunction &MF = DAG.getMachineFunction();
1566     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1567     unsigned Reg = FuncInfo->getSRetReturnReg();
1568     assert(Reg &&
1569            "SRetReturnReg should have been set in LowerFormalArguments().");
1570     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1571
1572     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1573     Flag = Chain.getValue(1);
1574
1575     // RAX now acts like a return value.
1576     MRI.addLiveOut(X86::RAX);
1577   }
1578
1579   RetOps[0] = Chain;  // Update chain.
1580
1581   // Add the flag if we have it.
1582   if (Flag.getNode())
1583     RetOps.push_back(Flag);
1584
1585   return DAG.getNode(X86ISD::RET_FLAG, dl,
1586                      MVT::Other, &RetOps[0], RetOps.size());
1587 }
1588
1589 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1590   if (N->getNumValues() != 1)
1591     return false;
1592   if (!N->hasNUsesOfValue(1, 0))
1593     return false;
1594
1595   SDValue TCChain = Chain;
1596   SDNode *Copy = *N->use_begin();
1597   if (Copy->getOpcode() == ISD::CopyToReg) {
1598     // If the copy has a glue operand, we conservatively assume it isn't safe to
1599     // perform a tail call.
1600     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1601       return false;
1602     TCChain = Copy->getOperand(0);
1603   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1604     return false;
1605
1606   bool HasRet = false;
1607   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1608        UI != UE; ++UI) {
1609     if (UI->getOpcode() != X86ISD::RET_FLAG)
1610       return false;
1611     HasRet = true;
1612   }
1613
1614   if (!HasRet)
1615     return false;
1616
1617   Chain = TCChain;
1618   return true;
1619 }
1620
1621 EVT
1622 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1623                                             ISD::NodeType ExtendKind) const {
1624   MVT ReturnMVT;
1625   // TODO: Is this also valid on 32-bit?
1626   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1627     ReturnMVT = MVT::i8;
1628   else
1629     ReturnMVT = MVT::i32;
1630
1631   EVT MinVT = getRegisterType(Context, ReturnMVT);
1632   return VT.bitsLT(MinVT) ? MinVT : VT;
1633 }
1634
1635 /// LowerCallResult - Lower the result values of a call into the
1636 /// appropriate copies out of appropriate physical registers.
1637 ///
1638 SDValue
1639 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1640                                    CallingConv::ID CallConv, bool isVarArg,
1641                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1642                                    DebugLoc dl, SelectionDAG &DAG,
1643                                    SmallVectorImpl<SDValue> &InVals) const {
1644
1645   // Assign locations to each value returned by this call.
1646   SmallVector<CCValAssign, 16> RVLocs;
1647   bool Is64Bit = Subtarget->is64Bit();
1648   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1649                  getTargetMachine(), RVLocs, *DAG.getContext());
1650   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1651
1652   // Copy all of the result registers out of their specified physreg.
1653   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1654     CCValAssign &VA = RVLocs[i];
1655     EVT CopyVT = VA.getValVT();
1656
1657     // If this is x86-64, and we disabled SSE, we can't return FP values
1658     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1659         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1660       report_fatal_error("SSE register return with SSE disabled");
1661     }
1662
1663     SDValue Val;
1664
1665     // If this is a call to a function that returns an fp value on the floating
1666     // point stack, we must guarantee the value is popped from the stack, so
1667     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1668     // if the return value is not used. We use the FpPOP_RETVAL instruction
1669     // instead.
1670     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1671       // If we prefer to use the value in xmm registers, copy it out as f80 and
1672       // use a truncate to move it from fp stack reg to xmm reg.
1673       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1674       SDValue Ops[] = { Chain, InFlag };
1675       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1676                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1677       Val = Chain.getValue(0);
1678
1679       // Round the f80 to the right size, which also moves it to the appropriate
1680       // xmm register.
1681       if (CopyVT != VA.getValVT())
1682         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1683                           // This truncation won't change the value.
1684                           DAG.getIntPtrConstant(1));
1685     } else {
1686       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1687                                  CopyVT, InFlag).getValue(1);
1688       Val = Chain.getValue(0);
1689     }
1690     InFlag = Chain.getValue(2);
1691     InVals.push_back(Val);
1692   }
1693
1694   return Chain;
1695 }
1696
1697
1698 //===----------------------------------------------------------------------===//
1699 //                C & StdCall & Fast Calling Convention implementation
1700 //===----------------------------------------------------------------------===//
1701 //  StdCall calling convention seems to be standard for many Windows' API
1702 //  routines and around. It differs from C calling convention just a little:
1703 //  callee should clean up the stack, not caller. Symbols should be also
1704 //  decorated in some fancy way :) It doesn't support any vector arguments.
1705 //  For info on fast calling convention see Fast Calling Convention (tail call)
1706 //  implementation LowerX86_32FastCCCallTo.
1707
1708 /// CallIsStructReturn - Determines whether a call uses struct return
1709 /// semantics.
1710 enum StructReturnType {
1711   NotStructReturn,
1712   RegStructReturn,
1713   StackStructReturn
1714 };
1715 static StructReturnType
1716 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1717   if (Outs.empty())
1718     return NotStructReturn;
1719
1720   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1721   if (!Flags.isSRet())
1722     return NotStructReturn;
1723   if (Flags.isInReg())
1724     return RegStructReturn;
1725   return StackStructReturn;
1726 }
1727
1728 /// ArgsAreStructReturn - Determines whether a function uses struct
1729 /// return semantics.
1730 static StructReturnType
1731 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1732   if (Ins.empty())
1733     return NotStructReturn;
1734
1735   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1736   if (!Flags.isSRet())
1737     return NotStructReturn;
1738   if (Flags.isInReg())
1739     return RegStructReturn;
1740   return StackStructReturn;
1741 }
1742
1743 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1744 /// by "Src" to address "Dst" with size and alignment information specified by
1745 /// the specific parameter attribute. The copy will be passed as a byval
1746 /// function parameter.
1747 static SDValue
1748 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1749                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1750                           DebugLoc dl) {
1751   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1752
1753   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1754                        /*isVolatile*/false, /*AlwaysInline=*/true,
1755                        MachinePointerInfo(), MachinePointerInfo());
1756 }
1757
1758 /// IsTailCallConvention - Return true if the calling convention is one that
1759 /// supports tail call optimization.
1760 static bool IsTailCallConvention(CallingConv::ID CC) {
1761   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1762 }
1763
1764 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1765   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1766     return false;
1767
1768   CallSite CS(CI);
1769   CallingConv::ID CalleeCC = CS.getCallingConv();
1770   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1771     return false;
1772
1773   return true;
1774 }
1775
1776 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1777 /// a tailcall target by changing its ABI.
1778 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1779                                    bool GuaranteedTailCallOpt) {
1780   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1781 }
1782
1783 SDValue
1784 X86TargetLowering::LowerMemArgument(SDValue Chain,
1785                                     CallingConv::ID CallConv,
1786                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1787                                     DebugLoc dl, SelectionDAG &DAG,
1788                                     const CCValAssign &VA,
1789                                     MachineFrameInfo *MFI,
1790                                     unsigned i) const {
1791   // Create the nodes corresponding to a load from this parameter slot.
1792   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1793   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1794                               getTargetMachine().Options.GuaranteedTailCallOpt);
1795   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1796   EVT ValVT;
1797
1798   // If value is passed by pointer we have address passed instead of the value
1799   // itself.
1800   if (VA.getLocInfo() == CCValAssign::Indirect)
1801     ValVT = VA.getLocVT();
1802   else
1803     ValVT = VA.getValVT();
1804
1805   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1806   // changed with more analysis.
1807   // In case of tail call optimization mark all arguments mutable. Since they
1808   // could be overwritten by lowering of arguments in case of a tail call.
1809   if (Flags.isByVal()) {
1810     unsigned Bytes = Flags.getByValSize();
1811     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1812     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1813     return DAG.getFrameIndex(FI, getPointerTy());
1814   } else {
1815     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1816                                     VA.getLocMemOffset(), isImmutable);
1817     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1818     return DAG.getLoad(ValVT, dl, Chain, FIN,
1819                        MachinePointerInfo::getFixedStack(FI),
1820                        false, false, false, 0);
1821   }
1822 }
1823
1824 SDValue
1825 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1826                                         CallingConv::ID CallConv,
1827                                         bool isVarArg,
1828                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1829                                         DebugLoc dl,
1830                                         SelectionDAG &DAG,
1831                                         SmallVectorImpl<SDValue> &InVals)
1832                                           const {
1833   MachineFunction &MF = DAG.getMachineFunction();
1834   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1835
1836   const Function* Fn = MF.getFunction();
1837   if (Fn->hasExternalLinkage() &&
1838       Subtarget->isTargetCygMing() &&
1839       Fn->getName() == "main")
1840     FuncInfo->setForceFramePointer(true);
1841
1842   MachineFrameInfo *MFI = MF.getFrameInfo();
1843   bool Is64Bit = Subtarget->is64Bit();
1844   bool IsWindows = Subtarget->isTargetWindows();
1845   bool IsWin64 = Subtarget->isTargetWin64();
1846
1847   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1848          "Var args not supported with calling convention fastcc or ghc");
1849
1850   // Assign locations to all of the incoming arguments.
1851   SmallVector<CCValAssign, 16> ArgLocs;
1852   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1853                  ArgLocs, *DAG.getContext());
1854
1855   // Allocate shadow area for Win64
1856   if (IsWin64) {
1857     CCInfo.AllocateStack(32, 8);
1858   }
1859
1860   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1861
1862   unsigned LastVal = ~0U;
1863   SDValue ArgValue;
1864   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1865     CCValAssign &VA = ArgLocs[i];
1866     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1867     // places.
1868     assert(VA.getValNo() != LastVal &&
1869            "Don't support value assigned to multiple locs yet");
1870     (void)LastVal;
1871     LastVal = VA.getValNo();
1872
1873     if (VA.isRegLoc()) {
1874       EVT RegVT = VA.getLocVT();
1875       const TargetRegisterClass *RC;
1876       if (RegVT == MVT::i32)
1877         RC = &X86::GR32RegClass;
1878       else if (Is64Bit && RegVT == MVT::i64)
1879         RC = &X86::GR64RegClass;
1880       else if (RegVT == MVT::f32)
1881         RC = &X86::FR32RegClass;
1882       else if (RegVT == MVT::f64)
1883         RC = &X86::FR64RegClass;
1884       else if (RegVT.is256BitVector())
1885         RC = &X86::VR256RegClass;
1886       else if (RegVT.is128BitVector())
1887         RC = &X86::VR128RegClass;
1888       else if (RegVT == MVT::x86mmx)
1889         RC = &X86::VR64RegClass;
1890       else
1891         llvm_unreachable("Unknown argument type!");
1892
1893       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1894       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1895
1896       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1897       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1898       // right size.
1899       if (VA.getLocInfo() == CCValAssign::SExt)
1900         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1901                                DAG.getValueType(VA.getValVT()));
1902       else if (VA.getLocInfo() == CCValAssign::ZExt)
1903         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1904                                DAG.getValueType(VA.getValVT()));
1905       else if (VA.getLocInfo() == CCValAssign::BCvt)
1906         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1907
1908       if (VA.isExtInLoc()) {
1909         // Handle MMX values passed in XMM regs.
1910         if (RegVT.isVector()) {
1911           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1912                                  ArgValue);
1913         } else
1914           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1915       }
1916     } else {
1917       assert(VA.isMemLoc());
1918       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1919     }
1920
1921     // If value is passed via pointer - do a load.
1922     if (VA.getLocInfo() == CCValAssign::Indirect)
1923       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1924                              MachinePointerInfo(), false, false, false, 0);
1925
1926     InVals.push_back(ArgValue);
1927   }
1928
1929   // The x86-64 ABI for returning structs by value requires that we copy
1930   // the sret argument into %rax for the return. Save the argument into
1931   // a virtual register so that we can access it from the return points.
1932   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1933     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1934     unsigned Reg = FuncInfo->getSRetReturnReg();
1935     if (!Reg) {
1936       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1937       FuncInfo->setSRetReturnReg(Reg);
1938     }
1939     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1940     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1941   }
1942
1943   unsigned StackSize = CCInfo.getNextStackOffset();
1944   // Align stack specially for tail calls.
1945   if (FuncIsMadeTailCallSafe(CallConv,
1946                              MF.getTarget().Options.GuaranteedTailCallOpt))
1947     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1948
1949   // If the function takes variable number of arguments, make a frame index for
1950   // the start of the first vararg value... for expansion of llvm.va_start.
1951   if (isVarArg) {
1952     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1953                     CallConv != CallingConv::X86_ThisCall)) {
1954       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1955     }
1956     if (Is64Bit) {
1957       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1958
1959       // FIXME: We should really autogenerate these arrays
1960       static const uint16_t GPR64ArgRegsWin64[] = {
1961         X86::RCX, X86::RDX, X86::R8,  X86::R9
1962       };
1963       static const uint16_t GPR64ArgRegs64Bit[] = {
1964         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1965       };
1966       static const uint16_t XMMArgRegs64Bit[] = {
1967         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1968         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1969       };
1970       const uint16_t *GPR64ArgRegs;
1971       unsigned NumXMMRegs = 0;
1972
1973       if (IsWin64) {
1974         // The XMM registers which might contain var arg parameters are shadowed
1975         // in their paired GPR.  So we only need to save the GPR to their home
1976         // slots.
1977         TotalNumIntRegs = 4;
1978         GPR64ArgRegs = GPR64ArgRegsWin64;
1979       } else {
1980         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1981         GPR64ArgRegs = GPR64ArgRegs64Bit;
1982
1983         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1984                                                 TotalNumXMMRegs);
1985       }
1986       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1987                                                        TotalNumIntRegs);
1988
1989       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1990       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1991              "SSE register cannot be used when SSE is disabled!");
1992       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1993                NoImplicitFloatOps) &&
1994              "SSE register cannot be used when SSE is disabled!");
1995       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1996           !Subtarget->hasSSE1())
1997         // Kernel mode asks for SSE to be disabled, so don't push them
1998         // on the stack.
1999         TotalNumXMMRegs = 0;
2000
2001       if (IsWin64) {
2002         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2003         // Get to the caller-allocated home save location.  Add 8 to account
2004         // for the return address.
2005         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2006         FuncInfo->setRegSaveFrameIndex(
2007           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2008         // Fixup to set vararg frame on shadow area (4 x i64).
2009         if (NumIntRegs < 4)
2010           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2011       } else {
2012         // For X86-64, if there are vararg parameters that are passed via
2013         // registers, then we must store them to their spots on the stack so
2014         // they may be loaded by deferencing the result of va_next.
2015         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2016         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2017         FuncInfo->setRegSaveFrameIndex(
2018           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2019                                false));
2020       }
2021
2022       // Store the integer parameter registers.
2023       SmallVector<SDValue, 8> MemOps;
2024       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2025                                         getPointerTy());
2026       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2027       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2028         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2029                                   DAG.getIntPtrConstant(Offset));
2030         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2031                                      &X86::GR64RegClass);
2032         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2033         SDValue Store =
2034           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2035                        MachinePointerInfo::getFixedStack(
2036                          FuncInfo->getRegSaveFrameIndex(), Offset),
2037                        false, false, 0);
2038         MemOps.push_back(Store);
2039         Offset += 8;
2040       }
2041
2042       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2043         // Now store the XMM (fp + vector) parameter registers.
2044         SmallVector<SDValue, 11> SaveXMMOps;
2045         SaveXMMOps.push_back(Chain);
2046
2047         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2048         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2049         SaveXMMOps.push_back(ALVal);
2050
2051         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2052                                FuncInfo->getRegSaveFrameIndex()));
2053         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2054                                FuncInfo->getVarArgsFPOffset()));
2055
2056         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2057           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2058                                        &X86::VR128RegClass);
2059           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2060           SaveXMMOps.push_back(Val);
2061         }
2062         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2063                                      MVT::Other,
2064                                      &SaveXMMOps[0], SaveXMMOps.size()));
2065       }
2066
2067       if (!MemOps.empty())
2068         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2069                             &MemOps[0], MemOps.size());
2070     }
2071   }
2072
2073   // Some CCs need callee pop.
2074   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2075                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2076     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2077   } else {
2078     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2079     // If this is an sret function, the return should pop the hidden pointer.
2080     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2081         argsAreStructReturn(Ins) == StackStructReturn)
2082       FuncInfo->setBytesToPopOnReturn(4);
2083   }
2084
2085   if (!Is64Bit) {
2086     // RegSaveFrameIndex is X86-64 only.
2087     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2088     if (CallConv == CallingConv::X86_FastCall ||
2089         CallConv == CallingConv::X86_ThisCall)
2090       // fastcc functions can't have varargs.
2091       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2092   }
2093
2094   FuncInfo->setArgumentStackSize(StackSize);
2095
2096   return Chain;
2097 }
2098
2099 SDValue
2100 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2101                                     SDValue StackPtr, SDValue Arg,
2102                                     DebugLoc dl, SelectionDAG &DAG,
2103                                     const CCValAssign &VA,
2104                                     ISD::ArgFlagsTy Flags) const {
2105   unsigned LocMemOffset = VA.getLocMemOffset();
2106   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2107   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2108   if (Flags.isByVal())
2109     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2110
2111   return DAG.getStore(Chain, dl, Arg, PtrOff,
2112                       MachinePointerInfo::getStack(LocMemOffset),
2113                       false, false, 0);
2114 }
2115
2116 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2117 /// optimization is performed and it is required.
2118 SDValue
2119 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2120                                            SDValue &OutRetAddr, SDValue Chain,
2121                                            bool IsTailCall, bool Is64Bit,
2122                                            int FPDiff, DebugLoc dl) const {
2123   // Adjust the Return address stack slot.
2124   EVT VT = getPointerTy();
2125   OutRetAddr = getReturnAddressFrameIndex(DAG);
2126
2127   // Load the "old" Return address.
2128   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2129                            false, false, false, 0);
2130   return SDValue(OutRetAddr.getNode(), 1);
2131 }
2132
2133 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2134 /// optimization is performed and it is required (FPDiff!=0).
2135 static SDValue
2136 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2137                          SDValue Chain, SDValue RetAddrFrIdx,
2138                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2139   // Store the return address to the appropriate stack slot.
2140   if (!FPDiff) return Chain;
2141   // Calculate the new stack slot for the return address.
2142   int SlotSize = Is64Bit ? 8 : 4;
2143   int NewReturnAddrFI =
2144     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2145   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2146   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2147   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2148                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2149                        false, false, 0);
2150   return Chain;
2151 }
2152
2153 SDValue
2154 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2155                              SmallVectorImpl<SDValue> &InVals) const {
2156   SelectionDAG &DAG                     = CLI.DAG;
2157   DebugLoc &dl                          = CLI.DL;
2158   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2159   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2160   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2161   SDValue Chain                         = CLI.Chain;
2162   SDValue Callee                        = CLI.Callee;
2163   CallingConv::ID CallConv              = CLI.CallConv;
2164   bool &isTailCall                      = CLI.IsTailCall;
2165   bool isVarArg                         = CLI.IsVarArg;
2166
2167   MachineFunction &MF = DAG.getMachineFunction();
2168   bool Is64Bit        = Subtarget->is64Bit();
2169   bool IsWin64        = Subtarget->isTargetWin64();
2170   bool IsWindows      = Subtarget->isTargetWindows();
2171   StructReturnType SR = callIsStructReturn(Outs);
2172   bool IsSibcall      = false;
2173
2174   if (MF.getTarget().Options.DisableTailCalls)
2175     isTailCall = false;
2176
2177   if (isTailCall) {
2178     // Check if it's really possible to do a tail call.
2179     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2180                     isVarArg, SR != NotStructReturn,
2181                     MF.getFunction()->hasStructRetAttr(),
2182                     Outs, OutVals, Ins, DAG);
2183
2184     // Sibcalls are automatically detected tailcalls which do not require
2185     // ABI changes.
2186     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2187       IsSibcall = true;
2188
2189     if (isTailCall)
2190       ++NumTailCalls;
2191   }
2192
2193   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2194          "Var args not supported with calling convention fastcc or ghc");
2195
2196   // Analyze operands of the call, assigning locations to each operand.
2197   SmallVector<CCValAssign, 16> ArgLocs;
2198   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2199                  ArgLocs, *DAG.getContext());
2200
2201   // Allocate shadow area for Win64
2202   if (IsWin64) {
2203     CCInfo.AllocateStack(32, 8);
2204   }
2205
2206   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2207
2208   // Get a count of how many bytes are to be pushed on the stack.
2209   unsigned NumBytes = CCInfo.getNextStackOffset();
2210   if (IsSibcall)
2211     // This is a sibcall. The memory operands are available in caller's
2212     // own caller's stack.
2213     NumBytes = 0;
2214   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2215            IsTailCallConvention(CallConv))
2216     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2217
2218   int FPDiff = 0;
2219   if (isTailCall && !IsSibcall) {
2220     // Lower arguments at fp - stackoffset + fpdiff.
2221     unsigned NumBytesCallerPushed =
2222       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2223     FPDiff = NumBytesCallerPushed - NumBytes;
2224
2225     // Set the delta of movement of the returnaddr stackslot.
2226     // But only set if delta is greater than previous delta.
2227     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2228       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2229   }
2230
2231   if (!IsSibcall)
2232     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2233
2234   SDValue RetAddrFrIdx;
2235   // Load return address for tail calls.
2236   if (isTailCall && FPDiff)
2237     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2238                                     Is64Bit, FPDiff, dl);
2239
2240   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2241   SmallVector<SDValue, 8> MemOpChains;
2242   SDValue StackPtr;
2243
2244   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2245   // of tail call optimization arguments are handle later.
2246   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2247     CCValAssign &VA = ArgLocs[i];
2248     EVT RegVT = VA.getLocVT();
2249     SDValue Arg = OutVals[i];
2250     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2251     bool isByVal = Flags.isByVal();
2252
2253     // Promote the value if needed.
2254     switch (VA.getLocInfo()) {
2255     default: llvm_unreachable("Unknown loc info!");
2256     case CCValAssign::Full: break;
2257     case CCValAssign::SExt:
2258       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2259       break;
2260     case CCValAssign::ZExt:
2261       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2262       break;
2263     case CCValAssign::AExt:
2264       if (RegVT.is128BitVector()) {
2265         // Special case: passing MMX values in XMM registers.
2266         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2267         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2268         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2269       } else
2270         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2271       break;
2272     case CCValAssign::BCvt:
2273       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2274       break;
2275     case CCValAssign::Indirect: {
2276       // Store the argument.
2277       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2278       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2279       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2280                            MachinePointerInfo::getFixedStack(FI),
2281                            false, false, 0);
2282       Arg = SpillSlot;
2283       break;
2284     }
2285     }
2286
2287     if (VA.isRegLoc()) {
2288       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2289       if (isVarArg && IsWin64) {
2290         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2291         // shadow reg if callee is a varargs function.
2292         unsigned ShadowReg = 0;
2293         switch (VA.getLocReg()) {
2294         case X86::XMM0: ShadowReg = X86::RCX; break;
2295         case X86::XMM1: ShadowReg = X86::RDX; break;
2296         case X86::XMM2: ShadowReg = X86::R8; break;
2297         case X86::XMM3: ShadowReg = X86::R9; break;
2298         }
2299         if (ShadowReg)
2300           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2301       }
2302     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2303       assert(VA.isMemLoc());
2304       if (StackPtr.getNode() == 0)
2305         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2306       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2307                                              dl, DAG, VA, Flags));
2308     }
2309   }
2310
2311   if (!MemOpChains.empty())
2312     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2313                         &MemOpChains[0], MemOpChains.size());
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       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2320                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2321     } else {
2322       // If we are tail calling and generating PIC/GOT style code load the
2323       // address of the callee into ECX. The value in ecx is used as target of
2324       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2325       // for tail calls on PIC/GOT architectures. Normally we would just put the
2326       // address of GOT into ebx and then call target@PLT. But for tail calls
2327       // ebx would be restored (since ebx is callee saved) before jumping to the
2328       // target@PLT.
2329
2330       // Note: The actual moving to ECX is done further down.
2331       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2332       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2333           !G->getGlobal()->hasProtectedVisibility())
2334         Callee = LowerGlobalAddress(Callee, DAG);
2335       else if (isa<ExternalSymbolSDNode>(Callee))
2336         Callee = LowerExternalSymbol(Callee, DAG);
2337     }
2338   }
2339
2340   if (Is64Bit && isVarArg && !IsWin64) {
2341     // From AMD64 ABI document:
2342     // For calls that may call functions that use varargs or stdargs
2343     // (prototype-less calls or calls to functions containing ellipsis (...) in
2344     // the declaration) %al is used as hidden argument to specify the number
2345     // of SSE registers used. The contents of %al do not need to match exactly
2346     // the number of registers, but must be an ubound on the number of SSE
2347     // registers used and is in the range 0 - 8 inclusive.
2348
2349     // Count the number of XMM registers allocated.
2350     static const uint16_t XMMArgRegs[] = {
2351       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2352       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2353     };
2354     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2355     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2356            && "SSE registers cannot be used when SSE is disabled");
2357
2358     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2359                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2360   }
2361
2362   // For tail calls lower the arguments to the 'real' stack slot.
2363   if (isTailCall) {
2364     // Force all the incoming stack arguments to be loaded from the stack
2365     // before any new outgoing arguments are stored to the stack, because the
2366     // outgoing stack slots may alias the incoming argument stack slots, and
2367     // the alias isn't otherwise explicit. This is slightly more conservative
2368     // than necessary, because it means that each store effectively depends
2369     // on every argument instead of just those arguments it would clobber.
2370     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2371
2372     SmallVector<SDValue, 8> MemOpChains2;
2373     SDValue FIN;
2374     int FI = 0;
2375     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2376       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2377         CCValAssign &VA = ArgLocs[i];
2378         if (VA.isRegLoc())
2379           continue;
2380         assert(VA.isMemLoc());
2381         SDValue Arg = OutVals[i];
2382         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2383         // Create frame index.
2384         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2385         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2386         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2387         FIN = DAG.getFrameIndex(FI, getPointerTy());
2388
2389         if (Flags.isByVal()) {
2390           // Copy relative to framepointer.
2391           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2392           if (StackPtr.getNode() == 0)
2393             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2394                                           getPointerTy());
2395           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2396
2397           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2398                                                            ArgChain,
2399                                                            Flags, DAG, dl));
2400         } else {
2401           // Store relative to framepointer.
2402           MemOpChains2.push_back(
2403             DAG.getStore(ArgChain, dl, Arg, FIN,
2404                          MachinePointerInfo::getFixedStack(FI),
2405                          false, false, 0));
2406         }
2407       }
2408     }
2409
2410     if (!MemOpChains2.empty())
2411       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2412                           &MemOpChains2[0], MemOpChains2.size());
2413
2414     // Store the return address to the appropriate stack slot.
2415     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2416                                      FPDiff, dl);
2417   }
2418
2419   // Build a sequence of copy-to-reg nodes chained together with token chain
2420   // and flag operands which copy the outgoing args into registers.
2421   SDValue InFlag;
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
2428   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2429     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2430     // In the 64-bit large code model, we have to make all calls
2431     // through a register, since the call instruction's 32-bit
2432     // pc-relative offset may not be large enough to hold the whole
2433     // address.
2434   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2435     // If the callee is a GlobalAddress node (quite common, every direct call
2436     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2437     // it.
2438
2439     // We should use extra load for direct calls to dllimported functions in
2440     // non-JIT mode.
2441     const GlobalValue *GV = G->getGlobal();
2442     if (!GV->hasDLLImportLinkage()) {
2443       unsigned char OpFlags = 0;
2444       bool ExtraLoad = false;
2445       unsigned WrapperKind = ISD::DELETED_NODE;
2446
2447       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2448       // external symbols most go through the PLT in PIC mode.  If the symbol
2449       // has hidden or protected visibility, or if it is static or local, then
2450       // we don't need to use the PLT - we can directly call it.
2451       if (Subtarget->isTargetELF() &&
2452           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2453           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2454         OpFlags = X86II::MO_PLT;
2455       } else if (Subtarget->isPICStyleStubAny() &&
2456                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2457                  (!Subtarget->getTargetTriple().isMacOSX() ||
2458                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2459         // PC-relative references to external symbols should go through $stub,
2460         // unless we're building with the leopard linker or later, which
2461         // automatically synthesizes these stubs.
2462         OpFlags = X86II::MO_DARWIN_STUB;
2463       } else if (Subtarget->isPICStyleRIPRel() &&
2464                  isa<Function>(GV) &&
2465                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2466         // If the function is marked as non-lazy, generate an indirect call
2467         // which loads from the GOT directly. This avoids runtime overhead
2468         // at the cost of eager binding (and one extra byte of encoding).
2469         OpFlags = X86II::MO_GOTPCREL;
2470         WrapperKind = X86ISD::WrapperRIP;
2471         ExtraLoad = true;
2472       }
2473
2474       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2475                                           G->getOffset(), OpFlags);
2476
2477       // Add a wrapper if needed.
2478       if (WrapperKind != ISD::DELETED_NODE)
2479         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2480       // Add extra indirection if needed.
2481       if (ExtraLoad)
2482         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2483                              MachinePointerInfo::getGOT(),
2484                              false, false, false, 0);
2485     }
2486   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2487     unsigned char OpFlags = 0;
2488
2489     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2490     // external symbols should go through the PLT.
2491     if (Subtarget->isTargetELF() &&
2492         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2493       OpFlags = X86II::MO_PLT;
2494     } else if (Subtarget->isPICStyleStubAny() &&
2495                (!Subtarget->getTargetTriple().isMacOSX() ||
2496                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2497       // PC-relative references to external symbols should go through $stub,
2498       // unless we're building with the leopard linker or later, which
2499       // automatically synthesizes these stubs.
2500       OpFlags = X86II::MO_DARWIN_STUB;
2501     }
2502
2503     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2504                                          OpFlags);
2505   }
2506
2507   // Returns a chain & a flag for retval copy to use.
2508   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2509   SmallVector<SDValue, 8> Ops;
2510
2511   if (!IsSibcall && isTailCall) {
2512     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2513                            DAG.getIntPtrConstant(0, true), InFlag);
2514     InFlag = Chain.getValue(1);
2515   }
2516
2517   Ops.push_back(Chain);
2518   Ops.push_back(Callee);
2519
2520   if (isTailCall)
2521     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2522
2523   // Add argument registers to the end of the list so that they are known live
2524   // into the call.
2525   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2526     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2527                                   RegsToPass[i].second.getValueType()));
2528
2529   // Add a register mask operand representing the call-preserved registers.
2530   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2531   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2532   assert(Mask && "Missing call preserved mask for calling convention");
2533   Ops.push_back(DAG.getRegisterMask(Mask));
2534
2535   if (InFlag.getNode())
2536     Ops.push_back(InFlag);
2537
2538   if (isTailCall) {
2539     // We used to do:
2540     //// If this is the first return lowered for this function, add the regs
2541     //// to the liveout set for the function.
2542     // This isn't right, although it's probably harmless on x86; liveouts
2543     // should be computed from returns not tail calls.  Consider a void
2544     // function making a tail call to a function returning int.
2545     return DAG.getNode(X86ISD::TC_RETURN, dl,
2546                        NodeTys, &Ops[0], Ops.size());
2547   }
2548
2549   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2550   InFlag = Chain.getValue(1);
2551
2552   // Create the CALLSEQ_END node.
2553   unsigned NumBytesForCalleeToPush;
2554   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2555                        getTargetMachine().Options.GuaranteedTailCallOpt))
2556     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2557   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2558            SR == StackStructReturn)
2559     // If this is a call to a struct-return function, the callee
2560     // pops the hidden struct pointer, so we have to push it back.
2561     // This is common for Darwin/X86, Linux & Mingw32 targets.
2562     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2563     NumBytesForCalleeToPush = 4;
2564   else
2565     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2566
2567   // Returns a flag for retval copy to use.
2568   if (!IsSibcall) {
2569     Chain = DAG.getCALLSEQ_END(Chain,
2570                                DAG.getIntPtrConstant(NumBytes, true),
2571                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2572                                                      true),
2573                                InFlag);
2574     InFlag = Chain.getValue(1);
2575   }
2576
2577   // Handle result values, copying them out of physregs into vregs that we
2578   // return.
2579   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2580                          Ins, dl, DAG, InVals);
2581 }
2582
2583
2584 //===----------------------------------------------------------------------===//
2585 //                Fast Calling Convention (tail call) implementation
2586 //===----------------------------------------------------------------------===//
2587
2588 //  Like std call, callee cleans arguments, convention except that ECX is
2589 //  reserved for storing the tail called function address. Only 2 registers are
2590 //  free for argument passing (inreg). Tail call optimization is performed
2591 //  provided:
2592 //                * tailcallopt is enabled
2593 //                * caller/callee are fastcc
2594 //  On X86_64 architecture with GOT-style position independent code only local
2595 //  (within module) calls are supported at the moment.
2596 //  To keep the stack aligned according to platform abi the function
2597 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2598 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2599 //  If a tail called function callee has more arguments than the caller the
2600 //  caller needs to make sure that there is room to move the RETADDR to. This is
2601 //  achieved by reserving an area the size of the argument delta right after the
2602 //  original REtADDR, but before the saved framepointer or the spilled registers
2603 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2604 //  stack layout:
2605 //    arg1
2606 //    arg2
2607 //    RETADDR
2608 //    [ new RETADDR
2609 //      move area ]
2610 //    (possible EBP)
2611 //    ESI
2612 //    EDI
2613 //    local1 ..
2614
2615 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2616 /// for a 16 byte align requirement.
2617 unsigned
2618 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2619                                                SelectionDAG& DAG) const {
2620   MachineFunction &MF = DAG.getMachineFunction();
2621   const TargetMachine &TM = MF.getTarget();
2622   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2623   unsigned StackAlignment = TFI.getStackAlignment();
2624   uint64_t AlignMask = StackAlignment - 1;
2625   int64_t Offset = StackSize;
2626   uint64_t SlotSize = TD->getPointerSize();
2627   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2628     // Number smaller than 12 so just add the difference.
2629     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2630   } else {
2631     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2632     Offset = ((~AlignMask) & Offset) + StackAlignment +
2633       (StackAlignment-SlotSize);
2634   }
2635   return Offset;
2636 }
2637
2638 /// MatchingStackOffset - Return true if the given stack call argument is
2639 /// already available in the same position (relatively) of the caller's
2640 /// incoming argument stack.
2641 static
2642 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2643                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2644                          const X86InstrInfo *TII) {
2645   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2646   int FI = INT_MAX;
2647   if (Arg.getOpcode() == ISD::CopyFromReg) {
2648     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2649     if (!TargetRegisterInfo::isVirtualRegister(VR))
2650       return false;
2651     MachineInstr *Def = MRI->getVRegDef(VR);
2652     if (!Def)
2653       return false;
2654     if (!Flags.isByVal()) {
2655       if (!TII->isLoadFromStackSlot(Def, FI))
2656         return false;
2657     } else {
2658       unsigned Opcode = Def->getOpcode();
2659       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2660           Def->getOperand(1).isFI()) {
2661         FI = Def->getOperand(1).getIndex();
2662         Bytes = Flags.getByValSize();
2663       } else
2664         return false;
2665     }
2666   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2667     if (Flags.isByVal())
2668       // ByVal argument is passed in as a pointer but it's now being
2669       // dereferenced. e.g.
2670       // define @foo(%struct.X* %A) {
2671       //   tail call @bar(%struct.X* byval %A)
2672       // }
2673       return false;
2674     SDValue Ptr = Ld->getBasePtr();
2675     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2676     if (!FINode)
2677       return false;
2678     FI = FINode->getIndex();
2679   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2680     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2681     FI = FINode->getIndex();
2682     Bytes = Flags.getByValSize();
2683   } else
2684     return false;
2685
2686   assert(FI != INT_MAX);
2687   if (!MFI->isFixedObjectIndex(FI))
2688     return false;
2689   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2690 }
2691
2692 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2693 /// for tail call optimization. Targets which want to do tail call
2694 /// optimization should implement this function.
2695 bool
2696 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2697                                                      CallingConv::ID CalleeCC,
2698                                                      bool isVarArg,
2699                                                      bool isCalleeStructRet,
2700                                                      bool isCallerStructRet,
2701                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2702                                     const SmallVectorImpl<SDValue> &OutVals,
2703                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2704                                                      SelectionDAG& DAG) const {
2705   if (!IsTailCallConvention(CalleeCC) &&
2706       CalleeCC != CallingConv::C)
2707     return false;
2708
2709   // If -tailcallopt is specified, make fastcc functions tail-callable.
2710   const MachineFunction &MF = DAG.getMachineFunction();
2711   const Function *CallerF = DAG.getMachineFunction().getFunction();
2712   CallingConv::ID CallerCC = CallerF->getCallingConv();
2713   bool CCMatch = CallerCC == CalleeCC;
2714
2715   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2716     if (IsTailCallConvention(CalleeCC) && CCMatch)
2717       return true;
2718     return false;
2719   }
2720
2721   // Look for obvious safe cases to perform tail call optimization that do not
2722   // require ABI changes. This is what gcc calls sibcall.
2723
2724   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2725   // emit a special epilogue.
2726   if (RegInfo->needsStackRealignment(MF))
2727     return false;
2728
2729   // Also avoid sibcall optimization if either caller or callee uses struct
2730   // return semantics.
2731   if (isCalleeStructRet || isCallerStructRet)
2732     return false;
2733
2734   // An stdcall caller is expected to clean up its arguments; the callee
2735   // isn't going to do that.
2736   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2737     return false;
2738
2739   // Do not sibcall optimize vararg calls unless all arguments are passed via
2740   // registers.
2741   if (isVarArg && !Outs.empty()) {
2742
2743     // Optimizing for varargs on Win64 is unlikely to be safe without
2744     // additional testing.
2745     if (Subtarget->isTargetWin64())
2746       return false;
2747
2748     SmallVector<CCValAssign, 16> ArgLocs;
2749     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2750                    getTargetMachine(), ArgLocs, *DAG.getContext());
2751
2752     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2753     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2754       if (!ArgLocs[i].isRegLoc())
2755         return false;
2756   }
2757
2758   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2759   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2760   // this into a sibcall.
2761   bool Unused = false;
2762   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2763     if (!Ins[i].Used) {
2764       Unused = true;
2765       break;
2766     }
2767   }
2768   if (Unused) {
2769     SmallVector<CCValAssign, 16> RVLocs;
2770     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2771                    getTargetMachine(), RVLocs, *DAG.getContext());
2772     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2773     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2774       CCValAssign &VA = RVLocs[i];
2775       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2776         return false;
2777     }
2778   }
2779
2780   // If the calling conventions do not match, then we'd better make sure the
2781   // results are returned in the same way as what the caller expects.
2782   if (!CCMatch) {
2783     SmallVector<CCValAssign, 16> RVLocs1;
2784     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2785                     getTargetMachine(), RVLocs1, *DAG.getContext());
2786     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2787
2788     SmallVector<CCValAssign, 16> RVLocs2;
2789     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2790                     getTargetMachine(), RVLocs2, *DAG.getContext());
2791     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2792
2793     if (RVLocs1.size() != RVLocs2.size())
2794       return false;
2795     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2796       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2797         return false;
2798       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2799         return false;
2800       if (RVLocs1[i].isRegLoc()) {
2801         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2802           return false;
2803       } else {
2804         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2805           return false;
2806       }
2807     }
2808   }
2809
2810   // If the callee takes no arguments then go on to check the results of the
2811   // call.
2812   if (!Outs.empty()) {
2813     // Check if stack adjustment is needed. For now, do not do this if any
2814     // argument is passed on the stack.
2815     SmallVector<CCValAssign, 16> ArgLocs;
2816     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2817                    getTargetMachine(), ArgLocs, *DAG.getContext());
2818
2819     // Allocate shadow area for Win64
2820     if (Subtarget->isTargetWin64()) {
2821       CCInfo.AllocateStack(32, 8);
2822     }
2823
2824     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2825     if (CCInfo.getNextStackOffset()) {
2826       MachineFunction &MF = DAG.getMachineFunction();
2827       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2828         return false;
2829
2830       // Check if the arguments are already laid out in the right way as
2831       // the caller's fixed stack objects.
2832       MachineFrameInfo *MFI = MF.getFrameInfo();
2833       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2834       const X86InstrInfo *TII =
2835         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2836       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2837         CCValAssign &VA = ArgLocs[i];
2838         SDValue Arg = OutVals[i];
2839         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2840         if (VA.getLocInfo() == CCValAssign::Indirect)
2841           return false;
2842         if (!VA.isRegLoc()) {
2843           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2844                                    MFI, MRI, TII))
2845             return false;
2846         }
2847       }
2848     }
2849
2850     // If the tailcall address may be in a register, then make sure it's
2851     // possible to register allocate for it. In 32-bit, the call address can
2852     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2853     // callee-saved registers are restored. These happen to be the same
2854     // registers used to pass 'inreg' arguments so watch out for those.
2855     if (!Subtarget->is64Bit() &&
2856         !isa<GlobalAddressSDNode>(Callee) &&
2857         !isa<ExternalSymbolSDNode>(Callee)) {
2858       unsigned NumInRegs = 0;
2859       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2860         CCValAssign &VA = ArgLocs[i];
2861         if (!VA.isRegLoc())
2862           continue;
2863         unsigned Reg = VA.getLocReg();
2864         switch (Reg) {
2865         default: break;
2866         case X86::EAX: case X86::EDX: case X86::ECX:
2867           if (++NumInRegs == 3)
2868             return false;
2869           break;
2870         }
2871       }
2872     }
2873   }
2874
2875   return true;
2876 }
2877
2878 FastISel *
2879 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2880                                   const TargetLibraryInfo *libInfo) const {
2881   return X86::createFastISel(funcInfo, libInfo);
2882 }
2883
2884
2885 //===----------------------------------------------------------------------===//
2886 //                           Other Lowering Hooks
2887 //===----------------------------------------------------------------------===//
2888
2889 static bool MayFoldLoad(SDValue Op) {
2890   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2891 }
2892
2893 static bool MayFoldIntoStore(SDValue Op) {
2894   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2895 }
2896
2897 static bool isTargetShuffle(unsigned Opcode) {
2898   switch(Opcode) {
2899   default: return false;
2900   case X86ISD::PSHUFD:
2901   case X86ISD::PSHUFHW:
2902   case X86ISD::PSHUFLW:
2903   case X86ISD::SHUFP:
2904   case X86ISD::PALIGN:
2905   case X86ISD::MOVLHPS:
2906   case X86ISD::MOVLHPD:
2907   case X86ISD::MOVHLPS:
2908   case X86ISD::MOVLPS:
2909   case X86ISD::MOVLPD:
2910   case X86ISD::MOVSHDUP:
2911   case X86ISD::MOVSLDUP:
2912   case X86ISD::MOVDDUP:
2913   case X86ISD::MOVSS:
2914   case X86ISD::MOVSD:
2915   case X86ISD::UNPCKL:
2916   case X86ISD::UNPCKH:
2917   case X86ISD::VPERMILP:
2918   case X86ISD::VPERM2X128:
2919   case X86ISD::VPERMI:
2920     return true;
2921   }
2922 }
2923
2924 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2925                                     SDValue V1, SelectionDAG &DAG) {
2926   switch(Opc) {
2927   default: llvm_unreachable("Unknown x86 shuffle node");
2928   case X86ISD::MOVSHDUP:
2929   case X86ISD::MOVSLDUP:
2930   case X86ISD::MOVDDUP:
2931     return DAG.getNode(Opc, dl, VT, V1);
2932   }
2933 }
2934
2935 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2936                                     SDValue V1, unsigned TargetMask,
2937                                     SelectionDAG &DAG) {
2938   switch(Opc) {
2939   default: llvm_unreachable("Unknown x86 shuffle node");
2940   case X86ISD::PSHUFD:
2941   case X86ISD::PSHUFHW:
2942   case X86ISD::PSHUFLW:
2943   case X86ISD::VPERMILP:
2944   case X86ISD::VPERMI:
2945     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2946   }
2947 }
2948
2949 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2950                                     SDValue V1, SDValue V2, unsigned TargetMask,
2951                                     SelectionDAG &DAG) {
2952   switch(Opc) {
2953   default: llvm_unreachable("Unknown x86 shuffle node");
2954   case X86ISD::PALIGN:
2955   case X86ISD::SHUFP:
2956   case X86ISD::VPERM2X128:
2957     return DAG.getNode(Opc, dl, VT, V1, V2,
2958                        DAG.getConstant(TargetMask, MVT::i8));
2959   }
2960 }
2961
2962 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2963                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2964   switch(Opc) {
2965   default: llvm_unreachable("Unknown x86 shuffle node");
2966   case X86ISD::MOVLHPS:
2967   case X86ISD::MOVLHPD:
2968   case X86ISD::MOVHLPS:
2969   case X86ISD::MOVLPS:
2970   case X86ISD::MOVLPD:
2971   case X86ISD::MOVSS:
2972   case X86ISD::MOVSD:
2973   case X86ISD::UNPCKL:
2974   case X86ISD::UNPCKH:
2975     return DAG.getNode(Opc, dl, VT, V1, V2);
2976   }
2977 }
2978
2979 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2980   MachineFunction &MF = DAG.getMachineFunction();
2981   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2982   int ReturnAddrIndex = FuncInfo->getRAIndex();
2983
2984   if (ReturnAddrIndex == 0) {
2985     // Set up a frame object for the return address.
2986     uint64_t SlotSize = TD->getPointerSize();
2987     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2988                                                            false);
2989     FuncInfo->setRAIndex(ReturnAddrIndex);
2990   }
2991
2992   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2993 }
2994
2995
2996 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2997                                        bool hasSymbolicDisplacement) {
2998   // Offset should fit into 32 bit immediate field.
2999   if (!isInt<32>(Offset))
3000     return false;
3001
3002   // If we don't have a symbolic displacement - we don't have any extra
3003   // restrictions.
3004   if (!hasSymbolicDisplacement)
3005     return true;
3006
3007   // FIXME: Some tweaks might be needed for medium code model.
3008   if (M != CodeModel::Small && M != CodeModel::Kernel)
3009     return false;
3010
3011   // For small code model we assume that latest object is 16MB before end of 31
3012   // bits boundary. We may also accept pretty large negative constants knowing
3013   // that all objects are in the positive half of address space.
3014   if (M == CodeModel::Small && Offset < 16*1024*1024)
3015     return true;
3016
3017   // For kernel code model we know that all object resist in the negative half
3018   // of 32bits address space. We may not accept negative offsets, since they may
3019   // be just off and we may accept pretty large positive ones.
3020   if (M == CodeModel::Kernel && Offset > 0)
3021     return true;
3022
3023   return false;
3024 }
3025
3026 /// isCalleePop - Determines whether the callee is required to pop its
3027 /// own arguments. Callee pop is necessary to support tail calls.
3028 bool X86::isCalleePop(CallingConv::ID CallingConv,
3029                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3030   if (IsVarArg)
3031     return false;
3032
3033   switch (CallingConv) {
3034   default:
3035     return false;
3036   case CallingConv::X86_StdCall:
3037     return !is64Bit;
3038   case CallingConv::X86_FastCall:
3039     return !is64Bit;
3040   case CallingConv::X86_ThisCall:
3041     return !is64Bit;
3042   case CallingConv::Fast:
3043     return TailCallOpt;
3044   case CallingConv::GHC:
3045     return TailCallOpt;
3046   }
3047 }
3048
3049 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3050 /// specific condition code, returning the condition code and the LHS/RHS of the
3051 /// comparison to make.
3052 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3053                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3054   if (!isFP) {
3055     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3056       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3057         // X > -1   -> X == 0, jump !sign.
3058         RHS = DAG.getConstant(0, RHS.getValueType());
3059         return X86::COND_NS;
3060       }
3061       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3062         // X < 0   -> X == 0, jump on sign.
3063         return X86::COND_S;
3064       }
3065       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3066         // X < 1   -> X <= 0
3067         RHS = DAG.getConstant(0, RHS.getValueType());
3068         return X86::COND_LE;
3069       }
3070     }
3071
3072     switch (SetCCOpcode) {
3073     default: llvm_unreachable("Invalid integer condition!");
3074     case ISD::SETEQ:  return X86::COND_E;
3075     case ISD::SETGT:  return X86::COND_G;
3076     case ISD::SETGE:  return X86::COND_GE;
3077     case ISD::SETLT:  return X86::COND_L;
3078     case ISD::SETLE:  return X86::COND_LE;
3079     case ISD::SETNE:  return X86::COND_NE;
3080     case ISD::SETULT: return X86::COND_B;
3081     case ISD::SETUGT: return X86::COND_A;
3082     case ISD::SETULE: return X86::COND_BE;
3083     case ISD::SETUGE: return X86::COND_AE;
3084     }
3085   }
3086
3087   // First determine if it is required or is profitable to flip the operands.
3088
3089   // If LHS is a foldable load, but RHS is not, flip the condition.
3090   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3091       !ISD::isNON_EXTLoad(RHS.getNode())) {
3092     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3093     std::swap(LHS, RHS);
3094   }
3095
3096   switch (SetCCOpcode) {
3097   default: break;
3098   case ISD::SETOLT:
3099   case ISD::SETOLE:
3100   case ISD::SETUGT:
3101   case ISD::SETUGE:
3102     std::swap(LHS, RHS);
3103     break;
3104   }
3105
3106   // On a floating point condition, the flags are set as follows:
3107   // ZF  PF  CF   op
3108   //  0 | 0 | 0 | X > Y
3109   //  0 | 0 | 1 | X < Y
3110   //  1 | 0 | 0 | X == Y
3111   //  1 | 1 | 1 | unordered
3112   switch (SetCCOpcode) {
3113   default: llvm_unreachable("Condcode should be pre-legalized away");
3114   case ISD::SETUEQ:
3115   case ISD::SETEQ:   return X86::COND_E;
3116   case ISD::SETOLT:              // flipped
3117   case ISD::SETOGT:
3118   case ISD::SETGT:   return X86::COND_A;
3119   case ISD::SETOLE:              // flipped
3120   case ISD::SETOGE:
3121   case ISD::SETGE:   return X86::COND_AE;
3122   case ISD::SETUGT:              // flipped
3123   case ISD::SETULT:
3124   case ISD::SETLT:   return X86::COND_B;
3125   case ISD::SETUGE:              // flipped
3126   case ISD::SETULE:
3127   case ISD::SETLE:   return X86::COND_BE;
3128   case ISD::SETONE:
3129   case ISD::SETNE:   return X86::COND_NE;
3130   case ISD::SETUO:   return X86::COND_P;
3131   case ISD::SETO:    return X86::COND_NP;
3132   case ISD::SETOEQ:
3133   case ISD::SETUNE:  return X86::COND_INVALID;
3134   }
3135 }
3136
3137 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3138 /// code. Current x86 isa includes the following FP cmov instructions:
3139 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3140 static bool hasFPCMov(unsigned X86CC) {
3141   switch (X86CC) {
3142   default:
3143     return false;
3144   case X86::COND_B:
3145   case X86::COND_BE:
3146   case X86::COND_E:
3147   case X86::COND_P:
3148   case X86::COND_A:
3149   case X86::COND_AE:
3150   case X86::COND_NE:
3151   case X86::COND_NP:
3152     return true;
3153   }
3154 }
3155
3156 /// isFPImmLegal - Returns true if the target can instruction select the
3157 /// specified FP immediate natively. If false, the legalizer will
3158 /// materialize the FP immediate as a load from a constant pool.
3159 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3160   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3161     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3162       return true;
3163   }
3164   return false;
3165 }
3166
3167 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3168 /// the specified range (L, H].
3169 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3170   return (Val < 0) || (Val >= Low && Val < Hi);
3171 }
3172
3173 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3174 /// specified value.
3175 static bool isUndefOrEqual(int Val, int CmpVal) {
3176   if (Val < 0 || Val == CmpVal)
3177     return true;
3178   return false;
3179 }
3180
3181 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3182 /// from position Pos and ending in Pos+Size, falls within the specified
3183 /// sequential range (L, L+Pos]. or is undef.
3184 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3185                                        unsigned Pos, unsigned Size, int Low) {
3186   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3187     if (!isUndefOrEqual(Mask[i], Low))
3188       return false;
3189   return true;
3190 }
3191
3192 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3193 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3194 /// the second operand.
3195 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3196   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3197     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3198   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3199     return (Mask[0] < 2 && Mask[1] < 2);
3200   return false;
3201 }
3202
3203 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3204 /// is suitable for input to PSHUFHW.
3205 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3206   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3207     return false;
3208
3209   // Lower quadword copied in order or undef.
3210   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3211     return false;
3212
3213   // Upper quadword shuffled.
3214   for (unsigned i = 4; i != 8; ++i)
3215     if (!isUndefOrInRange(Mask[i], 4, 8))
3216       return false;
3217
3218   if (VT == MVT::v16i16) {
3219     // Lower quadword copied in order or undef.
3220     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3221       return false;
3222
3223     // Upper quadword shuffled.
3224     for (unsigned i = 12; i != 16; ++i)
3225       if (!isUndefOrInRange(Mask[i], 12, 16))
3226         return false;
3227   }
3228
3229   return true;
3230 }
3231
3232 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3233 /// is suitable for input to PSHUFLW.
3234 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3235   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3236     return false;
3237
3238   // Upper quadword copied in order.
3239   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3240     return false;
3241
3242   // Lower quadword shuffled.
3243   for (unsigned i = 0; i != 4; ++i)
3244     if (!isUndefOrInRange(Mask[i], 0, 4))
3245       return false;
3246
3247   if (VT == MVT::v16i16) {
3248     // Upper quadword copied in order.
3249     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3250       return false;
3251
3252     // Lower quadword shuffled.
3253     for (unsigned i = 8; i != 12; ++i)
3254       if (!isUndefOrInRange(Mask[i], 8, 12))
3255         return false;
3256   }
3257
3258   return true;
3259 }
3260
3261 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3262 /// is suitable for input to PALIGNR.
3263 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3264                           const X86Subtarget *Subtarget) {
3265   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3266       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3267     return false;
3268
3269   unsigned NumElts = VT.getVectorNumElements();
3270   unsigned NumLanes = VT.getSizeInBits()/128;
3271   unsigned NumLaneElts = NumElts/NumLanes;
3272
3273   // Do not handle 64-bit element shuffles with palignr.
3274   if (NumLaneElts == 2)
3275     return false;
3276
3277   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3278     unsigned i;
3279     for (i = 0; i != NumLaneElts; ++i) {
3280       if (Mask[i+l] >= 0)
3281         break;
3282     }
3283
3284     // Lane is all undef, go to next lane
3285     if (i == NumLaneElts)
3286       continue;
3287
3288     int Start = Mask[i+l];
3289
3290     // Make sure its in this lane in one of the sources
3291     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3292         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3293       return false;
3294
3295     // If not lane 0, then we must match lane 0
3296     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3297       return false;
3298
3299     // Correct second source to be contiguous with first source
3300     if (Start >= (int)NumElts)
3301       Start -= NumElts - NumLaneElts;
3302
3303     // Make sure we're shifting in the right direction.
3304     if (Start <= (int)(i+l))
3305       return false;
3306
3307     Start -= i;
3308
3309     // Check the rest of the elements to see if they are consecutive.
3310     for (++i; i != NumLaneElts; ++i) {
3311       int Idx = Mask[i+l];
3312
3313       // Make sure its in this lane
3314       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3315           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3316         return false;
3317
3318       // If not lane 0, then we must match lane 0
3319       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3320         return false;
3321
3322       if (Idx >= (int)NumElts)
3323         Idx -= NumElts - NumLaneElts;
3324
3325       if (!isUndefOrEqual(Idx, Start+i))
3326         return false;
3327
3328     }
3329   }
3330
3331   return true;
3332 }
3333
3334 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3335 /// the two vector operands have swapped position.
3336 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3337                                      unsigned NumElems) {
3338   for (unsigned i = 0; i != NumElems; ++i) {
3339     int idx = Mask[i];
3340     if (idx < 0)
3341       continue;
3342     else if (idx < (int)NumElems)
3343       Mask[i] = idx + NumElems;
3344     else
3345       Mask[i] = idx - NumElems;
3346   }
3347 }
3348
3349 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3350 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3351 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3352 /// reverse of what x86 shuffles want.
3353 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3354                         bool Commuted = false) {
3355   if (!HasAVX && VT.getSizeInBits() == 256)
3356     return false;
3357
3358   unsigned NumElems = VT.getVectorNumElements();
3359   unsigned NumLanes = VT.getSizeInBits()/128;
3360   unsigned NumLaneElems = NumElems/NumLanes;
3361
3362   if (NumLaneElems != 2 && NumLaneElems != 4)
3363     return false;
3364
3365   // VSHUFPSY divides the resulting vector into 4 chunks.
3366   // The sources are also splitted into 4 chunks, and each destination
3367   // chunk must come from a different source chunk.
3368   //
3369   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3370   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3371   //
3372   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3373   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3374   //
3375   // VSHUFPDY divides the resulting vector into 4 chunks.
3376   // The sources are also splitted into 4 chunks, and each destination
3377   // chunk must come from a different source chunk.
3378   //
3379   //  SRC1 =>      X3       X2       X1       X0
3380   //  SRC2 =>      Y3       Y2       Y1       Y0
3381   //
3382   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3383   //
3384   unsigned HalfLaneElems = NumLaneElems/2;
3385   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3386     for (unsigned i = 0; i != NumLaneElems; ++i) {
3387       int Idx = Mask[i+l];
3388       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3389       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3390         return false;
3391       // For VSHUFPSY, the mask of the second half must be the same as the
3392       // first but with the appropriate offsets. This works in the same way as
3393       // VPERMILPS works with masks.
3394       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3395         continue;
3396       if (!isUndefOrEqual(Idx, Mask[i]+l))
3397         return false;
3398     }
3399   }
3400
3401   return true;
3402 }
3403
3404 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3405 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3406 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3407   if (!VT.is128BitVector())
3408     return false;
3409
3410   unsigned NumElems = VT.getVectorNumElements();
3411
3412   if (NumElems != 4)
3413     return false;
3414
3415   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3416   return isUndefOrEqual(Mask[0], 6) &&
3417          isUndefOrEqual(Mask[1], 7) &&
3418          isUndefOrEqual(Mask[2], 2) &&
3419          isUndefOrEqual(Mask[3], 3);
3420 }
3421
3422 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3423 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3424 /// <2, 3, 2, 3>
3425 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3426   if (!VT.is128BitVector())
3427     return false;
3428
3429   unsigned NumElems = VT.getVectorNumElements();
3430
3431   if (NumElems != 4)
3432     return false;
3433
3434   return isUndefOrEqual(Mask[0], 2) &&
3435          isUndefOrEqual(Mask[1], 3) &&
3436          isUndefOrEqual(Mask[2], 2) &&
3437          isUndefOrEqual(Mask[3], 3);
3438 }
3439
3440 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3441 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3442 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3443   if (!VT.is128BitVector())
3444     return false;
3445
3446   unsigned NumElems = VT.getVectorNumElements();
3447
3448   if (NumElems != 2 && NumElems != 4)
3449     return false;
3450
3451   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3452     if (!isUndefOrEqual(Mask[i], i + NumElems))
3453       return false;
3454
3455   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3456     if (!isUndefOrEqual(Mask[i], i))
3457       return false;
3458
3459   return true;
3460 }
3461
3462 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3463 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3464 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3465   if (!VT.is128BitVector())
3466     return false;
3467
3468   unsigned NumElems = VT.getVectorNumElements();
3469
3470   if (NumElems != 2 && NumElems != 4)
3471     return false;
3472
3473   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3474     if (!isUndefOrEqual(Mask[i], i))
3475       return false;
3476
3477   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3478     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3479       return false;
3480
3481   return true;
3482 }
3483
3484 //
3485 // Some special combinations that can be optimized.
3486 //
3487 static
3488 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3489                                SelectionDAG &DAG) {
3490   EVT VT = SVOp->getValueType(0);
3491   DebugLoc dl = SVOp->getDebugLoc();
3492
3493   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3494     return SDValue();
3495
3496   ArrayRef<int> Mask = SVOp->getMask();
3497
3498   // These are the special masks that may be optimized.
3499   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3500   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3501   bool MatchEvenMask = true;
3502   bool MatchOddMask  = true;
3503   for (int i=0; i<8; ++i) {
3504     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3505       MatchEvenMask = false;
3506     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3507       MatchOddMask = false;
3508   }
3509
3510   if (!MatchEvenMask && !MatchOddMask)
3511     return SDValue();
3512   
3513   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3514
3515   SDValue Op0 = SVOp->getOperand(0);
3516   SDValue Op1 = SVOp->getOperand(1);
3517
3518   if (MatchEvenMask) {
3519     // Shift the second operand right to 32 bits.
3520     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3521     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3522   } else {
3523     // Shift the first operand left to 32 bits.
3524     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3525     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3526   }
3527   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3528   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3529 }
3530
3531 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3532 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3533 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3534                          bool HasAVX2, bool V2IsSplat = false) {
3535   unsigned NumElts = VT.getVectorNumElements();
3536
3537   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3538          "Unsupported vector type for unpckh");
3539
3540   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3541       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3542     return false;
3543
3544   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3545   // independently on 128-bit lanes.
3546   unsigned NumLanes = VT.getSizeInBits()/128;
3547   unsigned NumLaneElts = NumElts/NumLanes;
3548
3549   for (unsigned l = 0; l != NumLanes; ++l) {
3550     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3551          i != (l+1)*NumLaneElts;
3552          i += 2, ++j) {
3553       int BitI  = Mask[i];
3554       int BitI1 = Mask[i+1];
3555       if (!isUndefOrEqual(BitI, j))
3556         return false;
3557       if (V2IsSplat) {
3558         if (!isUndefOrEqual(BitI1, NumElts))
3559           return false;
3560       } else {
3561         if (!isUndefOrEqual(BitI1, j + NumElts))
3562           return false;
3563       }
3564     }
3565   }
3566
3567   return true;
3568 }
3569
3570 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3571 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3572 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3573                          bool HasAVX2, bool V2IsSplat = false) {
3574   unsigned NumElts = VT.getVectorNumElements();
3575
3576   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3577          "Unsupported vector type for unpckh");
3578
3579   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3580       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3581     return false;
3582
3583   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3584   // independently on 128-bit lanes.
3585   unsigned NumLanes = VT.getSizeInBits()/128;
3586   unsigned NumLaneElts = NumElts/NumLanes;
3587
3588   for (unsigned l = 0; l != NumLanes; ++l) {
3589     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3590          i != (l+1)*NumLaneElts; i += 2, ++j) {
3591       int BitI  = Mask[i];
3592       int BitI1 = Mask[i+1];
3593       if (!isUndefOrEqual(BitI, j))
3594         return false;
3595       if (V2IsSplat) {
3596         if (isUndefOrEqual(BitI1, NumElts))
3597           return false;
3598       } else {
3599         if (!isUndefOrEqual(BitI1, j+NumElts))
3600           return false;
3601       }
3602     }
3603   }
3604   return true;
3605 }
3606
3607 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3608 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3609 /// <0, 0, 1, 1>
3610 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3611                                   bool HasAVX2) {
3612   unsigned NumElts = VT.getVectorNumElements();
3613
3614   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3615          "Unsupported vector type for unpckh");
3616
3617   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3618       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3619     return false;
3620
3621   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3622   // FIXME: Need a better way to get rid of this, there's no latency difference
3623   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3624   // the former later. We should also remove the "_undef" special mask.
3625   if (NumElts == 4 && VT.getSizeInBits() == 256)
3626     return false;
3627
3628   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3629   // independently on 128-bit lanes.
3630   unsigned NumLanes = VT.getSizeInBits()/128;
3631   unsigned NumLaneElts = NumElts/NumLanes;
3632
3633   for (unsigned l = 0; l != NumLanes; ++l) {
3634     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3635          i != (l+1)*NumLaneElts;
3636          i += 2, ++j) {
3637       int BitI  = Mask[i];
3638       int BitI1 = Mask[i+1];
3639
3640       if (!isUndefOrEqual(BitI, j))
3641         return false;
3642       if (!isUndefOrEqual(BitI1, j))
3643         return false;
3644     }
3645   }
3646
3647   return true;
3648 }
3649
3650 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3651 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3652 /// <2, 2, 3, 3>
3653 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3654   unsigned NumElts = VT.getVectorNumElements();
3655
3656   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3657          "Unsupported vector type for unpckh");
3658
3659   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3660       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3661     return false;
3662
3663   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3664   // independently on 128-bit lanes.
3665   unsigned NumLanes = VT.getSizeInBits()/128;
3666   unsigned NumLaneElts = NumElts/NumLanes;
3667
3668   for (unsigned l = 0; l != NumLanes; ++l) {
3669     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3670          i != (l+1)*NumLaneElts; i += 2, ++j) {
3671       int BitI  = Mask[i];
3672       int BitI1 = Mask[i+1];
3673       if (!isUndefOrEqual(BitI, j))
3674         return false;
3675       if (!isUndefOrEqual(BitI1, j))
3676         return false;
3677     }
3678   }
3679   return true;
3680 }
3681
3682 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3683 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3684 /// MOVSD, and MOVD, i.e. setting the lowest element.
3685 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3686   if (VT.getVectorElementType().getSizeInBits() < 32)
3687     return false;
3688   if (!VT.is128BitVector())
3689     return false;
3690
3691   unsigned NumElts = VT.getVectorNumElements();
3692
3693   if (!isUndefOrEqual(Mask[0], NumElts))
3694     return false;
3695
3696   for (unsigned i = 1; i != NumElts; ++i)
3697     if (!isUndefOrEqual(Mask[i], i))
3698       return false;
3699
3700   return true;
3701 }
3702
3703 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3704 /// as permutations between 128-bit chunks or halves. As an example: this
3705 /// shuffle bellow:
3706 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3707 /// The first half comes from the second half of V1 and the second half from the
3708 /// the second half of V2.
3709 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3710   if (!HasAVX || !VT.is256BitVector())
3711     return false;
3712
3713   // The shuffle result is divided into half A and half B. In total the two
3714   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3715   // B must come from C, D, E or F.
3716   unsigned HalfSize = VT.getVectorNumElements()/2;
3717   bool MatchA = false, MatchB = false;
3718
3719   // Check if A comes from one of C, D, E, F.
3720   for (unsigned Half = 0; Half != 4; ++Half) {
3721     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3722       MatchA = true;
3723       break;
3724     }
3725   }
3726
3727   // Check if B comes from one of C, D, E, F.
3728   for (unsigned Half = 0; Half != 4; ++Half) {
3729     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3730       MatchB = true;
3731       break;
3732     }
3733   }
3734
3735   return MatchA && MatchB;
3736 }
3737
3738 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3739 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3740 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3741   EVT VT = SVOp->getValueType(0);
3742
3743   unsigned HalfSize = VT.getVectorNumElements()/2;
3744
3745   unsigned FstHalf = 0, SndHalf = 0;
3746   for (unsigned i = 0; i < HalfSize; ++i) {
3747     if (SVOp->getMaskElt(i) > 0) {
3748       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3749       break;
3750     }
3751   }
3752   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3753     if (SVOp->getMaskElt(i) > 0) {
3754       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3755       break;
3756     }
3757   }
3758
3759   return (FstHalf | (SndHalf << 4));
3760 }
3761
3762 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3763 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3764 /// Note that VPERMIL mask matching is different depending whether theunderlying
3765 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3766 /// to the same elements of the low, but to the higher half of the source.
3767 /// In VPERMILPD the two lanes could be shuffled independently of each other
3768 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3769 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3770   if (!HasAVX)
3771     return false;
3772
3773   unsigned NumElts = VT.getVectorNumElements();
3774   // Only match 256-bit with 32/64-bit types
3775   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3776     return false;
3777
3778   unsigned NumLanes = VT.getSizeInBits()/128;
3779   unsigned LaneSize = NumElts/NumLanes;
3780   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3781     for (unsigned i = 0; i != LaneSize; ++i) {
3782       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3783         return false;
3784       if (NumElts != 8 || l == 0)
3785         continue;
3786       // VPERMILPS handling
3787       if (Mask[i] < 0)
3788         continue;
3789       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3790         return false;
3791     }
3792   }
3793
3794   return true;
3795 }
3796
3797 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3798 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3799 /// element of vector 2 and the other elements to come from vector 1 in order.
3800 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3801                                bool V2IsSplat = false, bool V2IsUndef = false) {
3802   if (!VT.is128BitVector())
3803     return false;
3804
3805   unsigned NumOps = VT.getVectorNumElements();
3806   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3807     return false;
3808
3809   if (!isUndefOrEqual(Mask[0], 0))
3810     return false;
3811
3812   for (unsigned i = 1; i != NumOps; ++i)
3813     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3814           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3815           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3816       return false;
3817
3818   return true;
3819 }
3820
3821 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3822 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3823 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3824 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3825                            const X86Subtarget *Subtarget) {
3826   if (!Subtarget->hasSSE3())
3827     return false;
3828
3829   unsigned NumElems = VT.getVectorNumElements();
3830
3831   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3832       (VT.getSizeInBits() == 256 && NumElems != 8))
3833     return false;
3834
3835   // "i+1" is the value the indexed mask element must have
3836   for (unsigned i = 0; i != NumElems; i += 2)
3837     if (!isUndefOrEqual(Mask[i], i+1) ||
3838         !isUndefOrEqual(Mask[i+1], i+1))
3839       return false;
3840
3841   return true;
3842 }
3843
3844 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3845 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3846 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3847 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3848                            const X86Subtarget *Subtarget) {
3849   if (!Subtarget->hasSSE3())
3850     return false;
3851
3852   unsigned NumElems = VT.getVectorNumElements();
3853
3854   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3855       (VT.getSizeInBits() == 256 && NumElems != 8))
3856     return false;
3857
3858   // "i" is the value the indexed mask element must have
3859   for (unsigned i = 0; i != NumElems; i += 2)
3860     if (!isUndefOrEqual(Mask[i], i) ||
3861         !isUndefOrEqual(Mask[i+1], i))
3862       return false;
3863
3864   return true;
3865 }
3866
3867 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3868 /// specifies a shuffle of elements that is suitable for input to 256-bit
3869 /// version of MOVDDUP.
3870 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3871   if (!HasAVX || !VT.is256BitVector())
3872     return false;
3873
3874   unsigned NumElts = VT.getVectorNumElements();
3875   if (NumElts != 4)
3876     return false;
3877
3878   for (unsigned i = 0; i != NumElts/2; ++i)
3879     if (!isUndefOrEqual(Mask[i], 0))
3880       return false;
3881   for (unsigned i = NumElts/2; i != NumElts; ++i)
3882     if (!isUndefOrEqual(Mask[i], NumElts/2))
3883       return false;
3884   return true;
3885 }
3886
3887 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3888 /// specifies a shuffle of elements that is suitable for input to 128-bit
3889 /// version of MOVDDUP.
3890 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3891   if (!VT.is128BitVector())
3892     return false;
3893
3894   unsigned e = VT.getVectorNumElements() / 2;
3895   for (unsigned i = 0; i != e; ++i)
3896     if (!isUndefOrEqual(Mask[i], i))
3897       return false;
3898   for (unsigned i = 0; i != e; ++i)
3899     if (!isUndefOrEqual(Mask[e+i], i))
3900       return false;
3901   return true;
3902 }
3903
3904 /// isVEXTRACTF128Index - Return true if the specified
3905 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3906 /// suitable for input to VEXTRACTF128.
3907 bool X86::isVEXTRACTF128Index(SDNode *N) {
3908   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3909     return false;
3910
3911   // The index should be aligned on a 128-bit boundary.
3912   uint64_t Index =
3913     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3914
3915   unsigned VL = N->getValueType(0).getVectorNumElements();
3916   unsigned VBits = N->getValueType(0).getSizeInBits();
3917   unsigned ElSize = VBits / VL;
3918   bool Result = (Index * ElSize) % 128 == 0;
3919
3920   return Result;
3921 }
3922
3923 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3924 /// operand specifies a subvector insert that is suitable for input to
3925 /// VINSERTF128.
3926 bool X86::isVINSERTF128Index(SDNode *N) {
3927   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3928     return false;
3929
3930   // The index should be aligned on a 128-bit boundary.
3931   uint64_t Index =
3932     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3933
3934   unsigned VL = N->getValueType(0).getVectorNumElements();
3935   unsigned VBits = N->getValueType(0).getSizeInBits();
3936   unsigned ElSize = VBits / VL;
3937   bool Result = (Index * ElSize) % 128 == 0;
3938
3939   return Result;
3940 }
3941
3942 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3943 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3944 /// Handles 128-bit and 256-bit.
3945 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3946   EVT VT = N->getValueType(0);
3947
3948   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3949          "Unsupported vector type for PSHUF/SHUFP");
3950
3951   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3952   // independently on 128-bit lanes.
3953   unsigned NumElts = VT.getVectorNumElements();
3954   unsigned NumLanes = VT.getSizeInBits()/128;
3955   unsigned NumLaneElts = NumElts/NumLanes;
3956
3957   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3958          "Only supports 2 or 4 elements per lane");
3959
3960   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3961   unsigned Mask = 0;
3962   for (unsigned i = 0; i != NumElts; ++i) {
3963     int Elt = N->getMaskElt(i);
3964     if (Elt < 0) continue;
3965     Elt &= NumLaneElts - 1;
3966     unsigned ShAmt = (i << Shift) % 8;
3967     Mask |= Elt << ShAmt;
3968   }
3969
3970   return Mask;
3971 }
3972
3973 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3974 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3975 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3976   EVT VT = N->getValueType(0);
3977
3978   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3979          "Unsupported vector type for PSHUFHW");
3980
3981   unsigned NumElts = VT.getVectorNumElements();
3982
3983   unsigned Mask = 0;
3984   for (unsigned l = 0; l != NumElts; l += 8) {
3985     // 8 nodes per lane, but we only care about the last 4.
3986     for (unsigned i = 0; i < 4; ++i) {
3987       int Elt = N->getMaskElt(l+i+4);
3988       if (Elt < 0) continue;
3989       Elt &= 0x3; // only 2-bits.
3990       Mask |= Elt << (i * 2);
3991     }
3992   }
3993
3994   return Mask;
3995 }
3996
3997 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3998 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3999 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4000   EVT VT = N->getValueType(0);
4001
4002   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4003          "Unsupported vector type for PSHUFHW");
4004
4005   unsigned NumElts = VT.getVectorNumElements();
4006
4007   unsigned Mask = 0;
4008   for (unsigned l = 0; l != NumElts; l += 8) {
4009     // 8 nodes per lane, but we only care about the first 4.
4010     for (unsigned i = 0; i < 4; ++i) {
4011       int Elt = N->getMaskElt(l+i);
4012       if (Elt < 0) continue;
4013       Elt &= 0x3; // only 2-bits
4014       Mask |= Elt << (i * 2);
4015     }
4016   }
4017
4018   return Mask;
4019 }
4020
4021 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4022 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4023 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4024   EVT VT = SVOp->getValueType(0);
4025   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4026
4027   unsigned NumElts = VT.getVectorNumElements();
4028   unsigned NumLanes = VT.getSizeInBits()/128;
4029   unsigned NumLaneElts = NumElts/NumLanes;
4030
4031   int Val = 0;
4032   unsigned i;
4033   for (i = 0; i != NumElts; ++i) {
4034     Val = SVOp->getMaskElt(i);
4035     if (Val >= 0)
4036       break;
4037   }
4038   if (Val >= (int)NumElts)
4039     Val -= NumElts - NumLaneElts;
4040
4041   assert(Val - i > 0 && "PALIGNR imm should be positive");
4042   return (Val - i) * EltSize;
4043 }
4044
4045 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4046 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4047 /// instructions.
4048 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4049   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4050     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4051
4052   uint64_t Index =
4053     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4054
4055   EVT VecVT = N->getOperand(0).getValueType();
4056   EVT ElVT = VecVT.getVectorElementType();
4057
4058   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4059   return Index / NumElemsPerChunk;
4060 }
4061
4062 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4063 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4064 /// instructions.
4065 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4066   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4067     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4068
4069   uint64_t Index =
4070     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4071
4072   EVT VecVT = N->getValueType(0);
4073   EVT ElVT = VecVT.getVectorElementType();
4074
4075   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4076   return Index / NumElemsPerChunk;
4077 }
4078
4079 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4080 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4081 /// Handles 256-bit.
4082 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4083   EVT VT = N->getValueType(0);
4084
4085   unsigned NumElts = VT.getVectorNumElements();
4086
4087   assert((VT.is256BitVector() && NumElts == 4) &&
4088          "Unsupported vector type for VPERMQ/VPERMPD");
4089
4090   unsigned Mask = 0;
4091   for (unsigned i = 0; i != NumElts; ++i) {
4092     int Elt = N->getMaskElt(i);
4093     if (Elt < 0)
4094       continue;
4095     Mask |= Elt << (i*2);
4096   }
4097
4098   return Mask;
4099 }
4100 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4101 /// constant +0.0.
4102 bool X86::isZeroNode(SDValue Elt) {
4103   return ((isa<ConstantSDNode>(Elt) &&
4104            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4105           (isa<ConstantFPSDNode>(Elt) &&
4106            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4107 }
4108
4109 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4110 /// their permute mask.
4111 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4112                                     SelectionDAG &DAG) {
4113   EVT VT = SVOp->getValueType(0);
4114   unsigned NumElems = VT.getVectorNumElements();
4115   SmallVector<int, 8> MaskVec;
4116
4117   for (unsigned i = 0; i != NumElems; ++i) {
4118     int Idx = SVOp->getMaskElt(i);
4119     if (Idx >= 0) {
4120       if (Idx < (int)NumElems)
4121         Idx += NumElems;
4122       else
4123         Idx -= NumElems;
4124     }
4125     MaskVec.push_back(Idx);
4126   }
4127   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4128                               SVOp->getOperand(0), &MaskVec[0]);
4129 }
4130
4131 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4132 /// match movhlps. The lower half elements should come from upper half of
4133 /// V1 (and in order), and the upper half elements should come from the upper
4134 /// half of V2 (and in order).
4135 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4136   if (!VT.is128BitVector())
4137     return false;
4138   if (VT.getVectorNumElements() != 4)
4139     return false;
4140   for (unsigned i = 0, e = 2; i != e; ++i)
4141     if (!isUndefOrEqual(Mask[i], i+2))
4142       return false;
4143   for (unsigned i = 2; i != 4; ++i)
4144     if (!isUndefOrEqual(Mask[i], i+4))
4145       return false;
4146   return true;
4147 }
4148
4149 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4150 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4151 /// required.
4152 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4153   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4154     return false;
4155   N = N->getOperand(0).getNode();
4156   if (!ISD::isNON_EXTLoad(N))
4157     return false;
4158   if (LD)
4159     *LD = cast<LoadSDNode>(N);
4160   return true;
4161 }
4162
4163 // Test whether the given value is a vector value which will be legalized
4164 // into a load.
4165 static bool WillBeConstantPoolLoad(SDNode *N) {
4166   if (N->getOpcode() != ISD::BUILD_VECTOR)
4167     return false;
4168
4169   // Check for any non-constant elements.
4170   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4171     switch (N->getOperand(i).getNode()->getOpcode()) {
4172     case ISD::UNDEF:
4173     case ISD::ConstantFP:
4174     case ISD::Constant:
4175       break;
4176     default:
4177       return false;
4178     }
4179
4180   // Vectors of all-zeros and all-ones are materialized with special
4181   // instructions rather than being loaded.
4182   return !ISD::isBuildVectorAllZeros(N) &&
4183          !ISD::isBuildVectorAllOnes(N);
4184 }
4185
4186 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4187 /// match movlp{s|d}. The lower half elements should come from lower half of
4188 /// V1 (and in order), and the upper half elements should come from the upper
4189 /// half of V2 (and in order). And since V1 will become the source of the
4190 /// MOVLP, it must be either a vector load or a scalar load to vector.
4191 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4192                                ArrayRef<int> Mask, EVT VT) {
4193   if (!VT.is128BitVector())
4194     return false;
4195
4196   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4197     return false;
4198   // Is V2 is a vector load, don't do this transformation. We will try to use
4199   // load folding shufps op.
4200   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4201     return false;
4202
4203   unsigned NumElems = VT.getVectorNumElements();
4204
4205   if (NumElems != 2 && NumElems != 4)
4206     return false;
4207   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4208     if (!isUndefOrEqual(Mask[i], i))
4209       return false;
4210   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4211     if (!isUndefOrEqual(Mask[i], i+NumElems))
4212       return false;
4213   return true;
4214 }
4215
4216 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4217 /// all the same.
4218 static bool isSplatVector(SDNode *N) {
4219   if (N->getOpcode() != ISD::BUILD_VECTOR)
4220     return false;
4221
4222   SDValue SplatValue = N->getOperand(0);
4223   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4224     if (N->getOperand(i) != SplatValue)
4225       return false;
4226   return true;
4227 }
4228
4229 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4230 /// to an zero vector.
4231 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4232 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4233   SDValue V1 = N->getOperand(0);
4234   SDValue V2 = N->getOperand(1);
4235   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4236   for (unsigned i = 0; i != NumElems; ++i) {
4237     int Idx = N->getMaskElt(i);
4238     if (Idx >= (int)NumElems) {
4239       unsigned Opc = V2.getOpcode();
4240       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4241         continue;
4242       if (Opc != ISD::BUILD_VECTOR ||
4243           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4244         return false;
4245     } else if (Idx >= 0) {
4246       unsigned Opc = V1.getOpcode();
4247       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4248         continue;
4249       if (Opc != ISD::BUILD_VECTOR ||
4250           !X86::isZeroNode(V1.getOperand(Idx)))
4251         return false;
4252     }
4253   }
4254   return true;
4255 }
4256
4257 /// getZeroVector - Returns a vector of specified type with all zero elements.
4258 ///
4259 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4260                              SelectionDAG &DAG, DebugLoc dl) {
4261   assert(VT.isVector() && "Expected a vector type");
4262   unsigned Size = VT.getSizeInBits();
4263
4264   // Always build SSE zero vectors as <4 x i32> bitcasted
4265   // to their dest type. This ensures they get CSE'd.
4266   SDValue Vec;
4267   if (Size == 128) {  // SSE
4268     if (Subtarget->hasSSE2()) {  // SSE2
4269       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4270       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4271     } else { // SSE1
4272       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4273       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4274     }
4275   } else if (Size == 256) { // AVX
4276     if (Subtarget->hasAVX2()) { // AVX2
4277       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4278       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4279       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4280     } else {
4281       // 256-bit logic and arithmetic instructions in AVX are all
4282       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4283       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4284       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4285       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4286     }
4287   } else
4288     llvm_unreachable("Unexpected vector type");
4289
4290   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4291 }
4292
4293 /// getOnesVector - Returns a vector of specified type with all bits set.
4294 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4295 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4296 /// Then bitcast to their original type, ensuring they get CSE'd.
4297 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4298                              DebugLoc dl) {
4299   assert(VT.isVector() && "Expected a vector type");
4300   unsigned Size = VT.getSizeInBits();
4301
4302   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4303   SDValue Vec;
4304   if (Size == 256) {
4305     if (HasAVX2) { // AVX2
4306       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4307       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4308     } else { // AVX
4309       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4310       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4311     }
4312   } else if (Size == 128) {
4313     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4314   } else
4315     llvm_unreachable("Unexpected vector type");
4316
4317   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4318 }
4319
4320 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4321 /// that point to V2 points to its first element.
4322 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4323   for (unsigned i = 0; i != NumElems; ++i) {
4324     if (Mask[i] > (int)NumElems) {
4325       Mask[i] = NumElems;
4326     }
4327   }
4328 }
4329
4330 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4331 /// operation of specified width.
4332 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4333                        SDValue V2) {
4334   unsigned NumElems = VT.getVectorNumElements();
4335   SmallVector<int, 8> Mask;
4336   Mask.push_back(NumElems);
4337   for (unsigned i = 1; i != NumElems; ++i)
4338     Mask.push_back(i);
4339   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4340 }
4341
4342 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4343 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4344                           SDValue V2) {
4345   unsigned NumElems = VT.getVectorNumElements();
4346   SmallVector<int, 8> Mask;
4347   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4348     Mask.push_back(i);
4349     Mask.push_back(i + NumElems);
4350   }
4351   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4352 }
4353
4354 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4355 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4356                           SDValue V2) {
4357   unsigned NumElems = VT.getVectorNumElements();
4358   SmallVector<int, 8> Mask;
4359   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4360     Mask.push_back(i + Half);
4361     Mask.push_back(i + NumElems + Half);
4362   }
4363   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4364 }
4365
4366 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4367 // a generic shuffle instruction because the target has no such instructions.
4368 // Generate shuffles which repeat i16 and i8 several times until they can be
4369 // represented by v4f32 and then be manipulated by target suported shuffles.
4370 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4371   EVT VT = V.getValueType();
4372   int NumElems = VT.getVectorNumElements();
4373   DebugLoc dl = V.getDebugLoc();
4374
4375   while (NumElems > 4) {
4376     if (EltNo < NumElems/2) {
4377       V = getUnpackl(DAG, dl, VT, V, V);
4378     } else {
4379       V = getUnpackh(DAG, dl, VT, V, V);
4380       EltNo -= NumElems/2;
4381     }
4382     NumElems >>= 1;
4383   }
4384   return V;
4385 }
4386
4387 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4388 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4389   EVT VT = V.getValueType();
4390   DebugLoc dl = V.getDebugLoc();
4391   unsigned Size = VT.getSizeInBits();
4392
4393   if (Size == 128) {
4394     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4395     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4396     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4397                              &SplatMask[0]);
4398   } else if (Size == 256) {
4399     // To use VPERMILPS to splat scalars, the second half of indicies must
4400     // refer to the higher part, which is a duplication of the lower one,
4401     // because VPERMILPS can only handle in-lane permutations.
4402     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4403                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4404
4405     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4406     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4407                              &SplatMask[0]);
4408   } else
4409     llvm_unreachable("Vector size not supported");
4410
4411   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4412 }
4413
4414 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4415 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4416   EVT SrcVT = SV->getValueType(0);
4417   SDValue V1 = SV->getOperand(0);
4418   DebugLoc dl = SV->getDebugLoc();
4419
4420   int EltNo = SV->getSplatIndex();
4421   int NumElems = SrcVT.getVectorNumElements();
4422   unsigned Size = SrcVT.getSizeInBits();
4423
4424   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4425           "Unknown how to promote splat for type");
4426
4427   // Extract the 128-bit part containing the splat element and update
4428   // the splat element index when it refers to the higher register.
4429   if (Size == 256) {
4430     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4431     if (EltNo >= NumElems/2)
4432       EltNo -= NumElems/2;
4433   }
4434
4435   // All i16 and i8 vector types can't be used directly by a generic shuffle
4436   // instruction because the target has no such instruction. Generate shuffles
4437   // which repeat i16 and i8 several times until they fit in i32, and then can
4438   // be manipulated by target suported shuffles.
4439   EVT EltVT = SrcVT.getVectorElementType();
4440   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4441     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4442
4443   // Recreate the 256-bit vector and place the same 128-bit vector
4444   // into the low and high part. This is necessary because we want
4445   // to use VPERM* to shuffle the vectors
4446   if (Size == 256) {
4447     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4448   }
4449
4450   return getLegalSplat(DAG, V1, EltNo);
4451 }
4452
4453 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4454 /// vector of zero or undef vector.  This produces a shuffle where the low
4455 /// element of V2 is swizzled into the zero/undef vector, landing at element
4456 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4457 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4458                                            bool IsZero,
4459                                            const X86Subtarget *Subtarget,
4460                                            SelectionDAG &DAG) {
4461   EVT VT = V2.getValueType();
4462   SDValue V1 = IsZero
4463     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4464   unsigned NumElems = VT.getVectorNumElements();
4465   SmallVector<int, 16> MaskVec;
4466   for (unsigned i = 0; i != NumElems; ++i)
4467     // If this is the insertion idx, put the low elt of V2 here.
4468     MaskVec.push_back(i == Idx ? NumElems : i);
4469   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4470 }
4471
4472 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4473 /// target specific opcode. Returns true if the Mask could be calculated.
4474 /// Sets IsUnary to true if only uses one source.
4475 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4476                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4477   unsigned NumElems = VT.getVectorNumElements();
4478   SDValue ImmN;
4479
4480   IsUnary = false;
4481   switch(N->getOpcode()) {
4482   case X86ISD::SHUFP:
4483     ImmN = N->getOperand(N->getNumOperands()-1);
4484     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4485     break;
4486   case X86ISD::UNPCKH:
4487     DecodeUNPCKHMask(VT, Mask);
4488     break;
4489   case X86ISD::UNPCKL:
4490     DecodeUNPCKLMask(VT, Mask);
4491     break;
4492   case X86ISD::MOVHLPS:
4493     DecodeMOVHLPSMask(NumElems, Mask);
4494     break;
4495   case X86ISD::MOVLHPS:
4496     DecodeMOVLHPSMask(NumElems, Mask);
4497     break;
4498   case X86ISD::PSHUFD:
4499   case X86ISD::VPERMILP:
4500     ImmN = N->getOperand(N->getNumOperands()-1);
4501     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4502     IsUnary = true;
4503     break;
4504   case X86ISD::PSHUFHW:
4505     ImmN = N->getOperand(N->getNumOperands()-1);
4506     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4507     IsUnary = true;
4508     break;
4509   case X86ISD::PSHUFLW:
4510     ImmN = N->getOperand(N->getNumOperands()-1);
4511     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4512     IsUnary = true;
4513     break;
4514   case X86ISD::VPERMI:
4515     ImmN = N->getOperand(N->getNumOperands()-1);
4516     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4517     IsUnary = true;
4518     break;
4519   case X86ISD::MOVSS:
4520   case X86ISD::MOVSD: {
4521     // The index 0 always comes from the first element of the second source,
4522     // this is why MOVSS and MOVSD are used in the first place. The other
4523     // elements come from the other positions of the first source vector
4524     Mask.push_back(NumElems);
4525     for (unsigned i = 1; i != NumElems; ++i) {
4526       Mask.push_back(i);
4527     }
4528     break;
4529   }
4530   case X86ISD::VPERM2X128:
4531     ImmN = N->getOperand(N->getNumOperands()-1);
4532     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4533     if (Mask.empty()) return false;
4534     break;
4535   case X86ISD::MOVDDUP:
4536   case X86ISD::MOVLHPD:
4537   case X86ISD::MOVLPD:
4538   case X86ISD::MOVLPS:
4539   case X86ISD::MOVSHDUP:
4540   case X86ISD::MOVSLDUP:
4541   case X86ISD::PALIGN:
4542     // Not yet implemented
4543     return false;
4544   default: llvm_unreachable("unknown target shuffle node");
4545   }
4546
4547   return true;
4548 }
4549
4550 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4551 /// element of the result of the vector shuffle.
4552 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4553                                    unsigned Depth) {
4554   if (Depth == 6)
4555     return SDValue();  // Limit search depth.
4556
4557   SDValue V = SDValue(N, 0);
4558   EVT VT = V.getValueType();
4559   unsigned Opcode = V.getOpcode();
4560
4561   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4562   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4563     int Elt = SV->getMaskElt(Index);
4564
4565     if (Elt < 0)
4566       return DAG.getUNDEF(VT.getVectorElementType());
4567
4568     unsigned NumElems = VT.getVectorNumElements();
4569     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4570                                          : SV->getOperand(1);
4571     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4572   }
4573
4574   // Recurse into target specific vector shuffles to find scalars.
4575   if (isTargetShuffle(Opcode)) {
4576     MVT ShufVT = V.getValueType().getSimpleVT();
4577     unsigned NumElems = ShufVT.getVectorNumElements();
4578     SmallVector<int, 16> ShuffleMask;
4579     SDValue ImmN;
4580     bool IsUnary;
4581
4582     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4583       return SDValue();
4584
4585     int Elt = ShuffleMask[Index];
4586     if (Elt < 0)
4587       return DAG.getUNDEF(ShufVT.getVectorElementType());
4588
4589     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4590                                          : N->getOperand(1);
4591     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4592                                Depth+1);
4593   }
4594
4595   // Actual nodes that may contain scalar elements
4596   if (Opcode == ISD::BITCAST) {
4597     V = V.getOperand(0);
4598     EVT SrcVT = V.getValueType();
4599     unsigned NumElems = VT.getVectorNumElements();
4600
4601     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4602       return SDValue();
4603   }
4604
4605   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4606     return (Index == 0) ? V.getOperand(0)
4607                         : DAG.getUNDEF(VT.getVectorElementType());
4608
4609   if (V.getOpcode() == ISD::BUILD_VECTOR)
4610     return V.getOperand(Index);
4611
4612   return SDValue();
4613 }
4614
4615 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4616 /// shuffle operation which come from a consecutively from a zero. The
4617 /// search can start in two different directions, from left or right.
4618 static
4619 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4620                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4621   unsigned i;
4622   for (i = 0; i != NumElems; ++i) {
4623     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4624     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4625     if (!(Elt.getNode() &&
4626          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4627       break;
4628   }
4629
4630   return i;
4631 }
4632
4633 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4634 /// correspond consecutively to elements from one of the vector operands,
4635 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4636 static
4637 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4638                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4639                               unsigned NumElems, unsigned &OpNum) {
4640   bool SeenV1 = false;
4641   bool SeenV2 = false;
4642
4643   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4644     int Idx = SVOp->getMaskElt(i);
4645     // Ignore undef indicies
4646     if (Idx < 0)
4647       continue;
4648
4649     if (Idx < (int)NumElems)
4650       SeenV1 = true;
4651     else
4652       SeenV2 = true;
4653
4654     // Only accept consecutive elements from the same vector
4655     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4656       return false;
4657   }
4658
4659   OpNum = SeenV1 ? 0 : 1;
4660   return true;
4661 }
4662
4663 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4664 /// logical left shift of a vector.
4665 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4666                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4667   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4668   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4669               false /* check zeros from right */, DAG);
4670   unsigned OpSrc;
4671
4672   if (!NumZeros)
4673     return false;
4674
4675   // Considering the elements in the mask that are not consecutive zeros,
4676   // check if they consecutively come from only one of the source vectors.
4677   //
4678   //               V1 = {X, A, B, C}     0
4679   //                         \  \  \    /
4680   //   vector_shuffle V1, V2 <1, 2, 3, X>
4681   //
4682   if (!isShuffleMaskConsecutive(SVOp,
4683             0,                   // Mask Start Index
4684             NumElems-NumZeros,   // Mask End Index(exclusive)
4685             NumZeros,            // Where to start looking in the src vector
4686             NumElems,            // Number of elements in vector
4687             OpSrc))              // Which source operand ?
4688     return false;
4689
4690   isLeft = false;
4691   ShAmt = NumZeros;
4692   ShVal = SVOp->getOperand(OpSrc);
4693   return true;
4694 }
4695
4696 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4697 /// logical left shift of a vector.
4698 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4699                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4700   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4701   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4702               true /* check zeros from left */, DAG);
4703   unsigned OpSrc;
4704
4705   if (!NumZeros)
4706     return false;
4707
4708   // Considering the elements in the mask that are not consecutive zeros,
4709   // check if they consecutively come from only one of the source vectors.
4710   //
4711   //                           0    { A, B, X, X } = V2
4712   //                          / \    /  /
4713   //   vector_shuffle V1, V2 <X, X, 4, 5>
4714   //
4715   if (!isShuffleMaskConsecutive(SVOp,
4716             NumZeros,     // Mask Start Index
4717             NumElems,     // Mask End Index(exclusive)
4718             0,            // Where to start looking in the src vector
4719             NumElems,     // Number of elements in vector
4720             OpSrc))       // Which source operand ?
4721     return false;
4722
4723   isLeft = true;
4724   ShAmt = NumZeros;
4725   ShVal = SVOp->getOperand(OpSrc);
4726   return true;
4727 }
4728
4729 /// isVectorShift - Returns true if the shuffle can be implemented as a
4730 /// logical left or right shift of a vector.
4731 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4732                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4733   // Although the logic below support any bitwidth size, there are no
4734   // shift instructions which handle more than 128-bit vectors.
4735   if (!SVOp->getValueType(0).is128BitVector())
4736     return false;
4737
4738   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4739       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4740     return true;
4741
4742   return false;
4743 }
4744
4745 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4746 ///
4747 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4748                                        unsigned NumNonZero, unsigned NumZero,
4749                                        SelectionDAG &DAG,
4750                                        const X86Subtarget* Subtarget,
4751                                        const TargetLowering &TLI) {
4752   if (NumNonZero > 8)
4753     return SDValue();
4754
4755   DebugLoc dl = Op.getDebugLoc();
4756   SDValue V(0, 0);
4757   bool First = true;
4758   for (unsigned i = 0; i < 16; ++i) {
4759     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4760     if (ThisIsNonZero && First) {
4761       if (NumZero)
4762         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4763       else
4764         V = DAG.getUNDEF(MVT::v8i16);
4765       First = false;
4766     }
4767
4768     if ((i & 1) != 0) {
4769       SDValue ThisElt(0, 0), LastElt(0, 0);
4770       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4771       if (LastIsNonZero) {
4772         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4773                               MVT::i16, Op.getOperand(i-1));
4774       }
4775       if (ThisIsNonZero) {
4776         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4777         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4778                               ThisElt, DAG.getConstant(8, MVT::i8));
4779         if (LastIsNonZero)
4780           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4781       } else
4782         ThisElt = LastElt;
4783
4784       if (ThisElt.getNode())
4785         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4786                         DAG.getIntPtrConstant(i/2));
4787     }
4788   }
4789
4790   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4791 }
4792
4793 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4794 ///
4795 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4796                                      unsigned NumNonZero, unsigned NumZero,
4797                                      SelectionDAG &DAG,
4798                                      const X86Subtarget* Subtarget,
4799                                      const TargetLowering &TLI) {
4800   if (NumNonZero > 4)
4801     return SDValue();
4802
4803   DebugLoc dl = Op.getDebugLoc();
4804   SDValue V(0, 0);
4805   bool First = true;
4806   for (unsigned i = 0; i < 8; ++i) {
4807     bool isNonZero = (NonZeros & (1 << i)) != 0;
4808     if (isNonZero) {
4809       if (First) {
4810         if (NumZero)
4811           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4812         else
4813           V = DAG.getUNDEF(MVT::v8i16);
4814         First = false;
4815       }
4816       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4817                       MVT::v8i16, V, Op.getOperand(i),
4818                       DAG.getIntPtrConstant(i));
4819     }
4820   }
4821
4822   return V;
4823 }
4824
4825 /// getVShift - Return a vector logical shift node.
4826 ///
4827 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4828                          unsigned NumBits, SelectionDAG &DAG,
4829                          const TargetLowering &TLI, DebugLoc dl) {
4830   assert(VT.is128BitVector() && "Unknown type for VShift");
4831   EVT ShVT = MVT::v2i64;
4832   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4833   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4834   return DAG.getNode(ISD::BITCAST, dl, VT,
4835                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4836                              DAG.getConstant(NumBits,
4837                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4838 }
4839
4840 SDValue
4841 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4842                                           SelectionDAG &DAG) const {
4843
4844   // Check if the scalar load can be widened into a vector load. And if
4845   // the address is "base + cst" see if the cst can be "absorbed" into
4846   // the shuffle mask.
4847   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4848     SDValue Ptr = LD->getBasePtr();
4849     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4850       return SDValue();
4851     EVT PVT = LD->getValueType(0);
4852     if (PVT != MVT::i32 && PVT != MVT::f32)
4853       return SDValue();
4854
4855     int FI = -1;
4856     int64_t Offset = 0;
4857     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4858       FI = FINode->getIndex();
4859       Offset = 0;
4860     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4861                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4862       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4863       Offset = Ptr.getConstantOperandVal(1);
4864       Ptr = Ptr.getOperand(0);
4865     } else {
4866       return SDValue();
4867     }
4868
4869     // FIXME: 256-bit vector instructions don't require a strict alignment,
4870     // improve this code to support it better.
4871     unsigned RequiredAlign = VT.getSizeInBits()/8;
4872     SDValue Chain = LD->getChain();
4873     // Make sure the stack object alignment is at least 16 or 32.
4874     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4875     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4876       if (MFI->isFixedObjectIndex(FI)) {
4877         // Can't change the alignment. FIXME: It's possible to compute
4878         // the exact stack offset and reference FI + adjust offset instead.
4879         // If someone *really* cares about this. That's the way to implement it.
4880         return SDValue();
4881       } else {
4882         MFI->setObjectAlignment(FI, RequiredAlign);
4883       }
4884     }
4885
4886     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4887     // Ptr + (Offset & ~15).
4888     if (Offset < 0)
4889       return SDValue();
4890     if ((Offset % RequiredAlign) & 3)
4891       return SDValue();
4892     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4893     if (StartOffset)
4894       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4895                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4896
4897     int EltNo = (Offset - StartOffset) >> 2;
4898     unsigned NumElems = VT.getVectorNumElements();
4899
4900     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4901     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4902                              LD->getPointerInfo().getWithOffset(StartOffset),
4903                              false, false, false, 0);
4904
4905     SmallVector<int, 8> Mask;
4906     for (unsigned i = 0; i != NumElems; ++i)
4907       Mask.push_back(EltNo);
4908
4909     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4910   }
4911
4912   return SDValue();
4913 }
4914
4915 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4916 /// vector of type 'VT', see if the elements can be replaced by a single large
4917 /// load which has the same value as a build_vector whose operands are 'elts'.
4918 ///
4919 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4920 ///
4921 /// FIXME: we'd also like to handle the case where the last elements are zero
4922 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4923 /// There's even a handy isZeroNode for that purpose.
4924 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4925                                         DebugLoc &DL, SelectionDAG &DAG) {
4926   EVT EltVT = VT.getVectorElementType();
4927   unsigned NumElems = Elts.size();
4928
4929   LoadSDNode *LDBase = NULL;
4930   unsigned LastLoadedElt = -1U;
4931
4932   // For each element in the initializer, see if we've found a load or an undef.
4933   // If we don't find an initial load element, or later load elements are
4934   // non-consecutive, bail out.
4935   for (unsigned i = 0; i < NumElems; ++i) {
4936     SDValue Elt = Elts[i];
4937
4938     if (!Elt.getNode() ||
4939         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4940       return SDValue();
4941     if (!LDBase) {
4942       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4943         return SDValue();
4944       LDBase = cast<LoadSDNode>(Elt.getNode());
4945       LastLoadedElt = i;
4946       continue;
4947     }
4948     if (Elt.getOpcode() == ISD::UNDEF)
4949       continue;
4950
4951     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4952     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4953       return SDValue();
4954     LastLoadedElt = i;
4955   }
4956
4957   // If we have found an entire vector of loads and undefs, then return a large
4958   // load of the entire vector width starting at the base pointer.  If we found
4959   // consecutive loads for the low half, generate a vzext_load node.
4960   if (LastLoadedElt == NumElems - 1) {
4961     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4962       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4963                          LDBase->getPointerInfo(),
4964                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4965                          LDBase->isInvariant(), 0);
4966     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4967                        LDBase->getPointerInfo(),
4968                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4969                        LDBase->isInvariant(), LDBase->getAlignment());
4970   }
4971   if (NumElems == 4 && LastLoadedElt == 1 &&
4972       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4973     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4974     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4975     SDValue ResNode =
4976         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4977                                 LDBase->getPointerInfo(),
4978                                 LDBase->getAlignment(),
4979                                 false/*isVolatile*/, true/*ReadMem*/,
4980                                 false/*WriteMem*/);
4981
4982     // Make sure the newly-created LOAD is in the same position as LDBase in
4983     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4984     // update uses of LDBase's output chain to use the TokenFactor.
4985     if (LDBase->hasAnyUseOfValue(1)) {
4986       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4987                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4988       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4989       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4990                              SDValue(ResNode.getNode(), 1));
4991     }
4992
4993     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4994   }
4995   return SDValue();
4996 }
4997
4998 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4999 /// to generate a splat value for the following cases:
5000 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5001 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5002 /// a scalar load, or a constant.
5003 /// The VBROADCAST node is returned when a pattern is found,
5004 /// or SDValue() otherwise.
5005 SDValue
5006 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
5007   if (!Subtarget->hasAVX())
5008     return SDValue();
5009
5010   EVT VT = Op.getValueType();
5011   DebugLoc dl = Op.getDebugLoc();
5012
5013   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5014          "Unsupported vector type for broadcast.");
5015
5016   SDValue Ld;
5017   bool ConstSplatVal;
5018
5019   switch (Op.getOpcode()) {
5020     default:
5021       // Unknown pattern found.
5022       return SDValue();
5023
5024     case ISD::BUILD_VECTOR: {
5025       // The BUILD_VECTOR node must be a splat.
5026       if (!isSplatVector(Op.getNode()))
5027         return SDValue();
5028
5029       Ld = Op.getOperand(0);
5030       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5031                      Ld.getOpcode() == ISD::ConstantFP);
5032
5033       // The suspected load node has several users. Make sure that all
5034       // of its users are from the BUILD_VECTOR node.
5035       // Constants may have multiple users.
5036       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5037         return SDValue();
5038       break;
5039     }
5040
5041     case ISD::VECTOR_SHUFFLE: {
5042       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5043
5044       // Shuffles must have a splat mask where the first element is
5045       // broadcasted.
5046       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5047         return SDValue();
5048
5049       SDValue Sc = Op.getOperand(0);
5050       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5051           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5052
5053         if (!Subtarget->hasAVX2())
5054           return SDValue();
5055
5056         // Use the register form of the broadcast instruction available on AVX2.
5057         if (VT.is256BitVector())
5058           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5059         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5060       }
5061
5062       Ld = Sc.getOperand(0);
5063       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5064                        Ld.getOpcode() == ISD::ConstantFP);
5065
5066       // The scalar_to_vector node and the suspected
5067       // load node must have exactly one user.
5068       // Constants may have multiple users.
5069       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5070         return SDValue();
5071       break;
5072     }
5073   }
5074
5075   bool Is256 = VT.is256BitVector();
5076
5077   // Handle the broadcasting a single constant scalar from the constant pool
5078   // into a vector. On Sandybridge it is still better to load a constant vector
5079   // from the constant pool and not to broadcast it from a scalar.
5080   if (ConstSplatVal && Subtarget->hasAVX2()) {
5081     EVT CVT = Ld.getValueType();
5082     assert(!CVT.isVector() && "Must not broadcast a vector type");
5083     unsigned ScalarSize = CVT.getSizeInBits();
5084
5085     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5086       const Constant *C = 0;
5087       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5088         C = CI->getConstantIntValue();
5089       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5090         C = CF->getConstantFPValue();
5091
5092       assert(C && "Invalid constant type");
5093
5094       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5095       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5096       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5097                        MachinePointerInfo::getConstantPool(),
5098                        false, false, false, Alignment);
5099
5100       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5101     }
5102   }
5103
5104   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5105   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5106
5107   // Handle AVX2 in-register broadcasts.
5108   if (!IsLoad && Subtarget->hasAVX2() &&
5109       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5110     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5111
5112   // The scalar source must be a normal load.
5113   if (!IsLoad)
5114     return SDValue();
5115
5116   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5117     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5118
5119   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5120   // double since there is no vbroadcastsd xmm
5121   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5122     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5123       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5124   }
5125
5126   // Unsupported broadcast.
5127   return SDValue();
5128 }
5129
5130 // LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5131 // and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5132 // constraint of matching input/output vector elements.
5133 SDValue
5134 X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5135   DebugLoc DL = Op.getDebugLoc();
5136   SDNode *N = Op.getNode();
5137   EVT VT = Op.getValueType();
5138   unsigned NumElts = Op.getNumOperands();
5139
5140   // Check supported types and sub-targets.
5141   //
5142   // Only v2f32 -> v2f64 needs special handling.
5143   if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5144     return SDValue();
5145
5146   SDValue VecIn;
5147   EVT VecInVT;
5148   SmallVector<int, 8> Mask;
5149   EVT SrcVT = MVT::Other;
5150
5151   // Check the patterns could be translated into X86vfpext.
5152   for (unsigned i = 0; i < NumElts; ++i) {
5153     SDValue In = N->getOperand(i);
5154     unsigned Opcode = In.getOpcode();
5155
5156     // Skip if the element is undefined.
5157     if (Opcode == ISD::UNDEF) {
5158       Mask.push_back(-1);
5159       continue;
5160     }
5161
5162     // Quit if one of the elements is not defined from 'fpext'.
5163     if (Opcode != ISD::FP_EXTEND)
5164       return SDValue();
5165
5166     // Check how the source of 'fpext' is defined.
5167     SDValue L2In = In.getOperand(0);
5168     EVT L2InVT = L2In.getValueType();
5169
5170     // Check the original type
5171     if (SrcVT == MVT::Other)
5172       SrcVT = L2InVT;
5173     else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5174       return SDValue();
5175
5176     // Check whether the value being 'fpext'ed is extracted from the same
5177     // source.
5178     Opcode = L2In.getOpcode();
5179
5180     // Quit if it's not extracted with a constant index.
5181     if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5182         !isa<ConstantSDNode>(L2In.getOperand(1)))
5183       return SDValue();
5184
5185     SDValue ExtractedFromVec = L2In.getOperand(0);
5186
5187     if (VecIn.getNode() == 0) {
5188       VecIn = ExtractedFromVec;
5189       VecInVT = ExtractedFromVec.getValueType();
5190     } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5191       return SDValue();
5192
5193     Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5194   }
5195
5196   // Quit if all operands of BUILD_VECTOR are undefined.
5197   if (!VecIn.getNode())
5198     return SDValue();
5199
5200   // Fill the remaining mask as undef.
5201   for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5202     Mask.push_back(-1);
5203
5204   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5205                      DAG.getVectorShuffle(VecInVT, DL,
5206                                           VecIn, DAG.getUNDEF(VecInVT),
5207                                           &Mask[0]));
5208 }
5209
5210 SDValue
5211 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5212   DebugLoc dl = Op.getDebugLoc();
5213
5214   EVT VT = Op.getValueType();
5215   EVT ExtVT = VT.getVectorElementType();
5216   unsigned NumElems = Op.getNumOperands();
5217
5218   // Vectors containing all zeros can be matched by pxor and xorps later
5219   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5220     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5221     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5222     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5223       return Op;
5224
5225     return getZeroVector(VT, Subtarget, DAG, dl);
5226   }
5227
5228   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5229   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5230   // vpcmpeqd on 256-bit vectors.
5231   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5232     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5233       return Op;
5234
5235     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5236   }
5237
5238   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5239   if (Broadcast.getNode())
5240     return Broadcast;
5241
5242   SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5243   if (FpExt.getNode())
5244     return FpExt;
5245
5246   unsigned EVTBits = ExtVT.getSizeInBits();
5247
5248   unsigned NumZero  = 0;
5249   unsigned NumNonZero = 0;
5250   unsigned NonZeros = 0;
5251   bool IsAllConstants = true;
5252   SmallSet<SDValue, 8> Values;
5253   for (unsigned i = 0; i < NumElems; ++i) {
5254     SDValue Elt = Op.getOperand(i);
5255     if (Elt.getOpcode() == ISD::UNDEF)
5256       continue;
5257     Values.insert(Elt);
5258     if (Elt.getOpcode() != ISD::Constant &&
5259         Elt.getOpcode() != ISD::ConstantFP)
5260       IsAllConstants = false;
5261     if (X86::isZeroNode(Elt))
5262       NumZero++;
5263     else {
5264       NonZeros |= (1 << i);
5265       NumNonZero++;
5266     }
5267   }
5268
5269   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5270   if (NumNonZero == 0)
5271     return DAG.getUNDEF(VT);
5272
5273   // Special case for single non-zero, non-undef, element.
5274   if (NumNonZero == 1) {
5275     unsigned Idx = CountTrailingZeros_32(NonZeros);
5276     SDValue Item = Op.getOperand(Idx);
5277
5278     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5279     // the value are obviously zero, truncate the value to i32 and do the
5280     // insertion that way.  Only do this if the value is non-constant or if the
5281     // value is a constant being inserted into element 0.  It is cheaper to do
5282     // a constant pool load than it is to do a movd + shuffle.
5283     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5284         (!IsAllConstants || Idx == 0)) {
5285       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5286         // Handle SSE only.
5287         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5288         EVT VecVT = MVT::v4i32;
5289         unsigned VecElts = 4;
5290
5291         // Truncate the value (which may itself be a constant) to i32, and
5292         // convert it to a vector with movd (S2V+shuffle to zero extend).
5293         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5294         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5295         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5296
5297         // Now we have our 32-bit value zero extended in the low element of
5298         // a vector.  If Idx != 0, swizzle it into place.
5299         if (Idx != 0) {
5300           SmallVector<int, 4> Mask;
5301           Mask.push_back(Idx);
5302           for (unsigned i = 1; i != VecElts; ++i)
5303             Mask.push_back(i);
5304           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5305                                       &Mask[0]);
5306         }
5307         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5308       }
5309     }
5310
5311     // If we have a constant or non-constant insertion into the low element of
5312     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5313     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5314     // depending on what the source datatype is.
5315     if (Idx == 0) {
5316       if (NumZero == 0)
5317         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5318
5319       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5320           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5321         if (VT.is256BitVector()) {
5322           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5323           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5324                              Item, DAG.getIntPtrConstant(0));
5325         }
5326         assert(VT.is128BitVector() && "Expected an SSE value type!");
5327         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5328         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5329         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5330       }
5331
5332       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5333         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5334         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5335         if (VT.is256BitVector()) {
5336           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5337           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5338         } else {
5339           assert(VT.is128BitVector() && "Expected an SSE value type!");
5340           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5341         }
5342         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5343       }
5344     }
5345
5346     // Is it a vector logical left shift?
5347     if (NumElems == 2 && Idx == 1 &&
5348         X86::isZeroNode(Op.getOperand(0)) &&
5349         !X86::isZeroNode(Op.getOperand(1))) {
5350       unsigned NumBits = VT.getSizeInBits();
5351       return getVShift(true, VT,
5352                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5353                                    VT, Op.getOperand(1)),
5354                        NumBits/2, DAG, *this, dl);
5355     }
5356
5357     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5358       return SDValue();
5359
5360     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5361     // is a non-constant being inserted into an element other than the low one,
5362     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5363     // movd/movss) to move this into the low element, then shuffle it into
5364     // place.
5365     if (EVTBits == 32) {
5366       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5367
5368       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5369       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5370       SmallVector<int, 8> MaskVec;
5371       for (unsigned i = 0; i != NumElems; ++i)
5372         MaskVec.push_back(i == Idx ? 0 : 1);
5373       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5374     }
5375   }
5376
5377   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5378   if (Values.size() == 1) {
5379     if (EVTBits == 32) {
5380       // Instead of a shuffle like this:
5381       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5382       // Check if it's possible to issue this instead.
5383       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5384       unsigned Idx = CountTrailingZeros_32(NonZeros);
5385       SDValue Item = Op.getOperand(Idx);
5386       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5387         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5388     }
5389     return SDValue();
5390   }
5391
5392   // A vector full of immediates; various special cases are already
5393   // handled, so this is best done with a single constant-pool load.
5394   if (IsAllConstants)
5395     return SDValue();
5396
5397   // For AVX-length vectors, build the individual 128-bit pieces and use
5398   // shuffles to put them in place.
5399   if (VT.is256BitVector()) {
5400     SmallVector<SDValue, 32> V;
5401     for (unsigned i = 0; i != NumElems; ++i)
5402       V.push_back(Op.getOperand(i));
5403
5404     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5405
5406     // Build both the lower and upper subvector.
5407     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5408     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5409                                 NumElems/2);
5410
5411     // Recreate the wider vector with the lower and upper part.
5412     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5413   }
5414
5415   // Let legalizer expand 2-wide build_vectors.
5416   if (EVTBits == 64) {
5417     if (NumNonZero == 1) {
5418       // One half is zero or undef.
5419       unsigned Idx = CountTrailingZeros_32(NonZeros);
5420       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5421                                  Op.getOperand(Idx));
5422       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5423     }
5424     return SDValue();
5425   }
5426
5427   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5428   if (EVTBits == 8 && NumElems == 16) {
5429     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5430                                         Subtarget, *this);
5431     if (V.getNode()) return V;
5432   }
5433
5434   if (EVTBits == 16 && NumElems == 8) {
5435     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5436                                       Subtarget, *this);
5437     if (V.getNode()) return V;
5438   }
5439
5440   // If element VT is == 32 bits, turn it into a number of shuffles.
5441   SmallVector<SDValue, 8> V(NumElems);
5442   if (NumElems == 4 && NumZero > 0) {
5443     for (unsigned i = 0; i < 4; ++i) {
5444       bool isZero = !(NonZeros & (1 << i));
5445       if (isZero)
5446         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5447       else
5448         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5449     }
5450
5451     for (unsigned i = 0; i < 2; ++i) {
5452       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5453         default: break;
5454         case 0:
5455           V[i] = V[i*2];  // Must be a zero vector.
5456           break;
5457         case 1:
5458           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5459           break;
5460         case 2:
5461           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5462           break;
5463         case 3:
5464           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5465           break;
5466       }
5467     }
5468
5469     bool Reverse1 = (NonZeros & 0x3) == 2;
5470     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5471     int MaskVec[] = {
5472       Reverse1 ? 1 : 0,
5473       Reverse1 ? 0 : 1,
5474       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5475       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5476     };
5477     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5478   }
5479
5480   if (Values.size() > 1 && VT.is128BitVector()) {
5481     // Check for a build vector of consecutive loads.
5482     for (unsigned i = 0; i < NumElems; ++i)
5483       V[i] = Op.getOperand(i);
5484
5485     // Check for elements which are consecutive loads.
5486     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5487     if (LD.getNode())
5488       return LD;
5489
5490     // For SSE 4.1, use insertps to put the high elements into the low element.
5491     if (getSubtarget()->hasSSE41()) {
5492       SDValue Result;
5493       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5494         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5495       else
5496         Result = DAG.getUNDEF(VT);
5497
5498       for (unsigned i = 1; i < NumElems; ++i) {
5499         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5500         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5501                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5502       }
5503       return Result;
5504     }
5505
5506     // Otherwise, expand into a number of unpckl*, start by extending each of
5507     // our (non-undef) elements to the full vector width with the element in the
5508     // bottom slot of the vector (which generates no code for SSE).
5509     for (unsigned i = 0; i < NumElems; ++i) {
5510       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5511         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5512       else
5513         V[i] = DAG.getUNDEF(VT);
5514     }
5515
5516     // Next, we iteratively mix elements, e.g. for v4f32:
5517     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5518     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5519     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5520     unsigned EltStride = NumElems >> 1;
5521     while (EltStride != 0) {
5522       for (unsigned i = 0; i < EltStride; ++i) {
5523         // If V[i+EltStride] is undef and this is the first round of mixing,
5524         // then it is safe to just drop this shuffle: V[i] is already in the
5525         // right place, the one element (since it's the first round) being
5526         // inserted as undef can be dropped.  This isn't safe for successive
5527         // rounds because they will permute elements within both vectors.
5528         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5529             EltStride == NumElems/2)
5530           continue;
5531
5532         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5533       }
5534       EltStride >>= 1;
5535     }
5536     return V[0];
5537   }
5538   return SDValue();
5539 }
5540
5541 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5542 // to create 256-bit vectors from two other 128-bit ones.
5543 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5544   DebugLoc dl = Op.getDebugLoc();
5545   EVT ResVT = Op.getValueType();
5546
5547   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5548
5549   SDValue V1 = Op.getOperand(0);
5550   SDValue V2 = Op.getOperand(1);
5551   unsigned NumElems = ResVT.getVectorNumElements();
5552
5553   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5554 }
5555
5556 SDValue
5557 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5558   assert(Op.getNumOperands() == 2);
5559
5560   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5561   // from two other 128-bit ones.
5562   return LowerAVXCONCAT_VECTORS(Op, DAG);
5563 }
5564
5565 // Try to lower a shuffle node into a simple blend instruction.
5566 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5567                                           const X86Subtarget *Subtarget,
5568                                           SelectionDAG &DAG) {
5569   SDValue V1 = SVOp->getOperand(0);
5570   SDValue V2 = SVOp->getOperand(1);
5571   DebugLoc dl = SVOp->getDebugLoc();
5572   MVT VT = SVOp->getValueType(0).getSimpleVT();
5573   unsigned NumElems = VT.getVectorNumElements();
5574
5575   if (!Subtarget->hasSSE41())
5576     return SDValue();
5577
5578   unsigned ISDNo = 0;
5579   MVT OpTy;
5580
5581   switch (VT.SimpleTy) {
5582   default: return SDValue();
5583   case MVT::v8i16:
5584     ISDNo = X86ISD::BLENDPW;
5585     OpTy = MVT::v8i16;
5586     break;
5587   case MVT::v4i32:
5588   case MVT::v4f32:
5589     ISDNo = X86ISD::BLENDPS;
5590     OpTy = MVT::v4f32;
5591     break;
5592   case MVT::v2i64:
5593   case MVT::v2f64:
5594     ISDNo = X86ISD::BLENDPD;
5595     OpTy = MVT::v2f64;
5596     break;
5597   case MVT::v8i32:
5598   case MVT::v8f32:
5599     if (!Subtarget->hasAVX())
5600       return SDValue();
5601     ISDNo = X86ISD::BLENDPS;
5602     OpTy = MVT::v8f32;
5603     break;
5604   case MVT::v4i64:
5605   case MVT::v4f64:
5606     if (!Subtarget->hasAVX())
5607       return SDValue();
5608     ISDNo = X86ISD::BLENDPD;
5609     OpTy = MVT::v4f64;
5610     break;
5611   }
5612   assert(ISDNo && "Invalid Op Number");
5613
5614   unsigned MaskVals = 0;
5615
5616   for (unsigned i = 0; i != NumElems; ++i) {
5617     int EltIdx = SVOp->getMaskElt(i);
5618     if (EltIdx == (int)i || EltIdx < 0)
5619       MaskVals |= (1<<i);
5620     else if (EltIdx == (int)(i + NumElems))
5621       continue; // Bit is set to zero;
5622     else
5623       return SDValue();
5624   }
5625
5626   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5627   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5628   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5629                              DAG.getConstant(MaskVals, MVT::i32));
5630   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5631 }
5632
5633 // v8i16 shuffles - Prefer shuffles in the following order:
5634 // 1. [all]   pshuflw, pshufhw, optional move
5635 // 2. [ssse3] 1 x pshufb
5636 // 3. [ssse3] 2 x pshufb + 1 x por
5637 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5638 SDValue
5639 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5640                                             SelectionDAG &DAG) const {
5641   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5642   SDValue V1 = SVOp->getOperand(0);
5643   SDValue V2 = SVOp->getOperand(1);
5644   DebugLoc dl = SVOp->getDebugLoc();
5645   SmallVector<int, 8> MaskVals;
5646
5647   // Determine if more than 1 of the words in each of the low and high quadwords
5648   // of the result come from the same quadword of one of the two inputs.  Undef
5649   // mask values count as coming from any quadword, for better codegen.
5650   unsigned LoQuad[] = { 0, 0, 0, 0 };
5651   unsigned HiQuad[] = { 0, 0, 0, 0 };
5652   std::bitset<4> InputQuads;
5653   for (unsigned i = 0; i < 8; ++i) {
5654     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5655     int EltIdx = SVOp->getMaskElt(i);
5656     MaskVals.push_back(EltIdx);
5657     if (EltIdx < 0) {
5658       ++Quad[0];
5659       ++Quad[1];
5660       ++Quad[2];
5661       ++Quad[3];
5662       continue;
5663     }
5664     ++Quad[EltIdx / 4];
5665     InputQuads.set(EltIdx / 4);
5666   }
5667
5668   int BestLoQuad = -1;
5669   unsigned MaxQuad = 1;
5670   for (unsigned i = 0; i < 4; ++i) {
5671     if (LoQuad[i] > MaxQuad) {
5672       BestLoQuad = i;
5673       MaxQuad = LoQuad[i];
5674     }
5675   }
5676
5677   int BestHiQuad = -1;
5678   MaxQuad = 1;
5679   for (unsigned i = 0; i < 4; ++i) {
5680     if (HiQuad[i] > MaxQuad) {
5681       BestHiQuad = i;
5682       MaxQuad = HiQuad[i];
5683     }
5684   }
5685
5686   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5687   // of the two input vectors, shuffle them into one input vector so only a
5688   // single pshufb instruction is necessary. If There are more than 2 input
5689   // quads, disable the next transformation since it does not help SSSE3.
5690   bool V1Used = InputQuads[0] || InputQuads[1];
5691   bool V2Used = InputQuads[2] || InputQuads[3];
5692   if (Subtarget->hasSSSE3()) {
5693     if (InputQuads.count() == 2 && V1Used && V2Used) {
5694       BestLoQuad = InputQuads[0] ? 0 : 1;
5695       BestHiQuad = InputQuads[2] ? 2 : 3;
5696     }
5697     if (InputQuads.count() > 2) {
5698       BestLoQuad = -1;
5699       BestHiQuad = -1;
5700     }
5701   }
5702
5703   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5704   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5705   // words from all 4 input quadwords.
5706   SDValue NewV;
5707   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5708     int MaskV[] = {
5709       BestLoQuad < 0 ? 0 : BestLoQuad,
5710       BestHiQuad < 0 ? 1 : BestHiQuad
5711     };
5712     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5713                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5714                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5715     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5716
5717     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5718     // source words for the shuffle, to aid later transformations.
5719     bool AllWordsInNewV = true;
5720     bool InOrder[2] = { true, true };
5721     for (unsigned i = 0; i != 8; ++i) {
5722       int idx = MaskVals[i];
5723       if (idx != (int)i)
5724         InOrder[i/4] = false;
5725       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5726         continue;
5727       AllWordsInNewV = false;
5728       break;
5729     }
5730
5731     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5732     if (AllWordsInNewV) {
5733       for (int i = 0; i != 8; ++i) {
5734         int idx = MaskVals[i];
5735         if (idx < 0)
5736           continue;
5737         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5738         if ((idx != i) && idx < 4)
5739           pshufhw = false;
5740         if ((idx != i) && idx > 3)
5741           pshuflw = false;
5742       }
5743       V1 = NewV;
5744       V2Used = false;
5745       BestLoQuad = 0;
5746       BestHiQuad = 1;
5747     }
5748
5749     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5750     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5751     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5752       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5753       unsigned TargetMask = 0;
5754       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5755                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5756       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5757       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5758                              getShufflePSHUFLWImmediate(SVOp);
5759       V1 = NewV.getOperand(0);
5760       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5761     }
5762   }
5763
5764   // If we have SSSE3, and all words of the result are from 1 input vector,
5765   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5766   // is present, fall back to case 4.
5767   if (Subtarget->hasSSSE3()) {
5768     SmallVector<SDValue,16> pshufbMask;
5769
5770     // If we have elements from both input vectors, set the high bit of the
5771     // shuffle mask element to zero out elements that come from V2 in the V1
5772     // mask, and elements that come from V1 in the V2 mask, so that the two
5773     // results can be OR'd together.
5774     bool TwoInputs = V1Used && V2Used;
5775     for (unsigned i = 0; i != 8; ++i) {
5776       int EltIdx = MaskVals[i] * 2;
5777       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5778       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5779       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5780       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5781     }
5782     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5783     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5784                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5785                                  MVT::v16i8, &pshufbMask[0], 16));
5786     if (!TwoInputs)
5787       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5788
5789     // Calculate the shuffle mask for the second input, shuffle it, and
5790     // OR it with the first shuffled input.
5791     pshufbMask.clear();
5792     for (unsigned i = 0; i != 8; ++i) {
5793       int EltIdx = MaskVals[i] * 2;
5794       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5795       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5796       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5797       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5798     }
5799     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5800     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5801                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5802                                  MVT::v16i8, &pshufbMask[0], 16));
5803     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5804     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5805   }
5806
5807   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5808   // and update MaskVals with new element order.
5809   std::bitset<8> InOrder;
5810   if (BestLoQuad >= 0) {
5811     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5812     for (int i = 0; i != 4; ++i) {
5813       int idx = MaskVals[i];
5814       if (idx < 0) {
5815         InOrder.set(i);
5816       } else if ((idx / 4) == BestLoQuad) {
5817         MaskV[i] = idx & 3;
5818         InOrder.set(i);
5819       }
5820     }
5821     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5822                                 &MaskV[0]);
5823
5824     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5825       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5826       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5827                                   NewV.getOperand(0),
5828                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5829     }
5830   }
5831
5832   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5833   // and update MaskVals with the new element order.
5834   if (BestHiQuad >= 0) {
5835     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5836     for (unsigned i = 4; i != 8; ++i) {
5837       int idx = MaskVals[i];
5838       if (idx < 0) {
5839         InOrder.set(i);
5840       } else if ((idx / 4) == BestHiQuad) {
5841         MaskV[i] = (idx & 3) + 4;
5842         InOrder.set(i);
5843       }
5844     }
5845     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5846                                 &MaskV[0]);
5847
5848     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5849       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5850       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5851                                   NewV.getOperand(0),
5852                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5853     }
5854   }
5855
5856   // In case BestHi & BestLo were both -1, which means each quadword has a word
5857   // from each of the four input quadwords, calculate the InOrder bitvector now
5858   // before falling through to the insert/extract cleanup.
5859   if (BestLoQuad == -1 && BestHiQuad == -1) {
5860     NewV = V1;
5861     for (int i = 0; i != 8; ++i)
5862       if (MaskVals[i] < 0 || MaskVals[i] == i)
5863         InOrder.set(i);
5864   }
5865
5866   // The other elements are put in the right place using pextrw and pinsrw.
5867   for (unsigned i = 0; i != 8; ++i) {
5868     if (InOrder[i])
5869       continue;
5870     int EltIdx = MaskVals[i];
5871     if (EltIdx < 0)
5872       continue;
5873     SDValue ExtOp = (EltIdx < 8) ?
5874       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5875                   DAG.getIntPtrConstant(EltIdx)) :
5876       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5877                   DAG.getIntPtrConstant(EltIdx - 8));
5878     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5879                        DAG.getIntPtrConstant(i));
5880   }
5881   return NewV;
5882 }
5883
5884 // v16i8 shuffles - Prefer shuffles in the following order:
5885 // 1. [ssse3] 1 x pshufb
5886 // 2. [ssse3] 2 x pshufb + 1 x por
5887 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5888 static
5889 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5890                                  SelectionDAG &DAG,
5891                                  const X86TargetLowering &TLI) {
5892   SDValue V1 = SVOp->getOperand(0);
5893   SDValue V2 = SVOp->getOperand(1);
5894   DebugLoc dl = SVOp->getDebugLoc();
5895   ArrayRef<int> MaskVals = SVOp->getMask();
5896
5897   // If we have SSSE3, case 1 is generated when all result bytes come from
5898   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5899   // present, fall back to case 3.
5900
5901   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5902   if (TLI.getSubtarget()->hasSSSE3()) {
5903     SmallVector<SDValue,16> pshufbMask;
5904
5905     // If all result elements are from one input vector, then only translate
5906     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5907     //
5908     // Otherwise, we have elements from both input vectors, and must zero out
5909     // elements that come from V2 in the first mask, and V1 in the second mask
5910     // so that we can OR them together.
5911     for (unsigned i = 0; i != 16; ++i) {
5912       int EltIdx = MaskVals[i];
5913       if (EltIdx < 0 || EltIdx >= 16)
5914         EltIdx = 0x80;
5915       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5916     }
5917     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5918                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5919                                  MVT::v16i8, &pshufbMask[0], 16));
5920
5921     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5922     // the 2nd operand if it's undefined or zero.
5923     if (V2.getOpcode() == ISD::UNDEF ||
5924         ISD::isBuildVectorAllZeros(V2.getNode()))
5925       return V1;
5926
5927     // Calculate the shuffle mask for the second input, shuffle it, and
5928     // OR it with the first shuffled input.
5929     pshufbMask.clear();
5930     for (unsigned i = 0; i != 16; ++i) {
5931       int EltIdx = MaskVals[i];
5932       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5933       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5934     }
5935     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5936                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5937                                  MVT::v16i8, &pshufbMask[0], 16));
5938     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5939   }
5940
5941   // No SSSE3 - Calculate in place words and then fix all out of place words
5942   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5943   // the 16 different words that comprise the two doublequadword input vectors.
5944   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5945   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5946   SDValue NewV = V1;
5947   for (int i = 0; i != 8; ++i) {
5948     int Elt0 = MaskVals[i*2];
5949     int Elt1 = MaskVals[i*2+1];
5950
5951     // This word of the result is all undef, skip it.
5952     if (Elt0 < 0 && Elt1 < 0)
5953       continue;
5954
5955     // This word of the result is already in the correct place, skip it.
5956     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5957       continue;
5958
5959     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5960     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5961     SDValue InsElt;
5962
5963     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5964     // using a single extract together, load it and store it.
5965     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5966       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5967                            DAG.getIntPtrConstant(Elt1 / 2));
5968       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5969                         DAG.getIntPtrConstant(i));
5970       continue;
5971     }
5972
5973     // If Elt1 is defined, extract it from the appropriate source.  If the
5974     // source byte is not also odd, shift the extracted word left 8 bits
5975     // otherwise clear the bottom 8 bits if we need to do an or.
5976     if (Elt1 >= 0) {
5977       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5978                            DAG.getIntPtrConstant(Elt1 / 2));
5979       if ((Elt1 & 1) == 0)
5980         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5981                              DAG.getConstant(8,
5982                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5983       else if (Elt0 >= 0)
5984         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5985                              DAG.getConstant(0xFF00, MVT::i16));
5986     }
5987     // If Elt0 is defined, extract it from the appropriate source.  If the
5988     // source byte is not also even, shift the extracted word right 8 bits. If
5989     // Elt1 was also defined, OR the extracted values together before
5990     // inserting them in the result.
5991     if (Elt0 >= 0) {
5992       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5993                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5994       if ((Elt0 & 1) != 0)
5995         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5996                               DAG.getConstant(8,
5997                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5998       else if (Elt1 >= 0)
5999         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6000                              DAG.getConstant(0x00FF, MVT::i16));
6001       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6002                          : InsElt0;
6003     }
6004     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6005                        DAG.getIntPtrConstant(i));
6006   }
6007   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6008 }
6009
6010 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6011 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6012 /// done when every pair / quad of shuffle mask elements point to elements in
6013 /// the right sequence. e.g.
6014 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6015 static
6016 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6017                                  SelectionDAG &DAG, DebugLoc dl) {
6018   MVT VT = SVOp->getValueType(0).getSimpleVT();
6019   unsigned NumElems = VT.getVectorNumElements();
6020   MVT NewVT;
6021   unsigned Scale;
6022   switch (VT.SimpleTy) {
6023   default: llvm_unreachable("Unexpected!");
6024   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6025   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6026   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6027   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6028   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6029   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6030   }
6031
6032   SmallVector<int, 8> MaskVec;
6033   for (unsigned i = 0; i != NumElems; i += Scale) {
6034     int StartIdx = -1;
6035     for (unsigned j = 0; j != Scale; ++j) {
6036       int EltIdx = SVOp->getMaskElt(i+j);
6037       if (EltIdx < 0)
6038         continue;
6039       if (StartIdx < 0)
6040         StartIdx = (EltIdx / Scale);
6041       if (EltIdx != (int)(StartIdx*Scale + j))
6042         return SDValue();
6043     }
6044     MaskVec.push_back(StartIdx);
6045   }
6046
6047   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6048   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6049   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6050 }
6051
6052 /// getVZextMovL - Return a zero-extending vector move low node.
6053 ///
6054 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6055                             SDValue SrcOp, SelectionDAG &DAG,
6056                             const X86Subtarget *Subtarget, DebugLoc dl) {
6057   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6058     LoadSDNode *LD = NULL;
6059     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6060       LD = dyn_cast<LoadSDNode>(SrcOp);
6061     if (!LD) {
6062       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6063       // instead.
6064       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6065       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6066           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6067           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6068           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6069         // PR2108
6070         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6071         return DAG.getNode(ISD::BITCAST, dl, VT,
6072                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6073                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6074                                                    OpVT,
6075                                                    SrcOp.getOperand(0)
6076                                                           .getOperand(0))));
6077       }
6078     }
6079   }
6080
6081   return DAG.getNode(ISD::BITCAST, dl, VT,
6082                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6083                                  DAG.getNode(ISD::BITCAST, dl,
6084                                              OpVT, SrcOp)));
6085 }
6086
6087 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6088 /// which could not be matched by any known target speficic shuffle
6089 static SDValue
6090 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6091
6092   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6093   if (NewOp.getNode())
6094     return NewOp;
6095
6096   EVT VT = SVOp->getValueType(0);
6097
6098   unsigned NumElems = VT.getVectorNumElements();
6099   unsigned NumLaneElems = NumElems / 2;
6100
6101   DebugLoc dl = SVOp->getDebugLoc();
6102   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6103   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6104   SDValue Output[2];
6105
6106   SmallVector<int, 16> Mask;
6107   for (unsigned l = 0; l < 2; ++l) {
6108     // Build a shuffle mask for the output, discovering on the fly which
6109     // input vectors to use as shuffle operands (recorded in InputUsed).
6110     // If building a suitable shuffle vector proves too hard, then bail
6111     // out with UseBuildVector set.
6112     bool UseBuildVector = false;
6113     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6114     unsigned LaneStart = l * NumLaneElems;
6115     for (unsigned i = 0; i != NumLaneElems; ++i) {
6116       // The mask element.  This indexes into the input.
6117       int Idx = SVOp->getMaskElt(i+LaneStart);
6118       if (Idx < 0) {
6119         // the mask element does not index into any input vector.
6120         Mask.push_back(-1);
6121         continue;
6122       }
6123
6124       // The input vector this mask element indexes into.
6125       int Input = Idx / NumLaneElems;
6126
6127       // Turn the index into an offset from the start of the input vector.
6128       Idx -= Input * NumLaneElems;
6129
6130       // Find or create a shuffle vector operand to hold this input.
6131       unsigned OpNo;
6132       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6133         if (InputUsed[OpNo] == Input)
6134           // This input vector is already an operand.
6135           break;
6136         if (InputUsed[OpNo] < 0) {
6137           // Create a new operand for this input vector.
6138           InputUsed[OpNo] = Input;
6139           break;
6140         }
6141       }
6142
6143       if (OpNo >= array_lengthof(InputUsed)) {
6144         // More than two input vectors used!  Give up on trying to create a
6145         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6146         UseBuildVector = true;
6147         break;
6148       }
6149
6150       // Add the mask index for the new shuffle vector.
6151       Mask.push_back(Idx + OpNo * NumLaneElems);
6152     }
6153
6154     if (UseBuildVector) {
6155       SmallVector<SDValue, 16> SVOps;
6156       for (unsigned i = 0; i != NumLaneElems; ++i) {
6157         // The mask element.  This indexes into the input.
6158         int Idx = SVOp->getMaskElt(i+LaneStart);
6159         if (Idx < 0) {
6160           SVOps.push_back(DAG.getUNDEF(EltVT));
6161           continue;
6162         }
6163
6164         // The input vector this mask element indexes into.
6165         int Input = Idx / NumElems;
6166
6167         // Turn the index into an offset from the start of the input vector.
6168         Idx -= Input * NumElems;
6169
6170         // Extract the vector element by hand.
6171         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6172                                     SVOp->getOperand(Input),
6173                                     DAG.getIntPtrConstant(Idx)));
6174       }
6175
6176       // Construct the output using a BUILD_VECTOR.
6177       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6178                               SVOps.size());
6179     } else if (InputUsed[0] < 0) {
6180       // No input vectors were used! The result is undefined.
6181       Output[l] = DAG.getUNDEF(NVT);
6182     } else {
6183       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6184                                         (InputUsed[0] % 2) * NumLaneElems,
6185                                         DAG, dl);
6186       // If only one input was used, use an undefined vector for the other.
6187       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6188         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6189                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6190       // At least one input vector was used. Create a new shuffle vector.
6191       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6192     }
6193
6194     Mask.clear();
6195   }
6196
6197   // Concatenate the result back
6198   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6199 }
6200
6201 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6202 /// 4 elements, and match them with several different shuffle types.
6203 static SDValue
6204 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6205   SDValue V1 = SVOp->getOperand(0);
6206   SDValue V2 = SVOp->getOperand(1);
6207   DebugLoc dl = SVOp->getDebugLoc();
6208   EVT VT = SVOp->getValueType(0);
6209
6210   assert(VT.is128BitVector() && "Unsupported vector size");
6211
6212   std::pair<int, int> Locs[4];
6213   int Mask1[] = { -1, -1, -1, -1 };
6214   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6215
6216   unsigned NumHi = 0;
6217   unsigned NumLo = 0;
6218   for (unsigned i = 0; i != 4; ++i) {
6219     int Idx = PermMask[i];
6220     if (Idx < 0) {
6221       Locs[i] = std::make_pair(-1, -1);
6222     } else {
6223       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6224       if (Idx < 4) {
6225         Locs[i] = std::make_pair(0, NumLo);
6226         Mask1[NumLo] = Idx;
6227         NumLo++;
6228       } else {
6229         Locs[i] = std::make_pair(1, NumHi);
6230         if (2+NumHi < 4)
6231           Mask1[2+NumHi] = Idx;
6232         NumHi++;
6233       }
6234     }
6235   }
6236
6237   if (NumLo <= 2 && NumHi <= 2) {
6238     // If no more than two elements come from either vector. This can be
6239     // implemented with two shuffles. First shuffle gather the elements.
6240     // The second shuffle, which takes the first shuffle as both of its
6241     // vector operands, put the elements into the right order.
6242     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6243
6244     int Mask2[] = { -1, -1, -1, -1 };
6245
6246     for (unsigned i = 0; i != 4; ++i)
6247       if (Locs[i].first != -1) {
6248         unsigned Idx = (i < 2) ? 0 : 4;
6249         Idx += Locs[i].first * 2 + Locs[i].second;
6250         Mask2[i] = Idx;
6251       }
6252
6253     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6254   }
6255
6256   if (NumLo == 3 || NumHi == 3) {
6257     // Otherwise, we must have three elements from one vector, call it X, and
6258     // one element from the other, call it Y.  First, use a shufps to build an
6259     // intermediate vector with the one element from Y and the element from X
6260     // that will be in the same half in the final destination (the indexes don't
6261     // matter). Then, use a shufps to build the final vector, taking the half
6262     // containing the element from Y from the intermediate, and the other half
6263     // from X.
6264     if (NumHi == 3) {
6265       // Normalize it so the 3 elements come from V1.
6266       CommuteVectorShuffleMask(PermMask, 4);
6267       std::swap(V1, V2);
6268     }
6269
6270     // Find the element from V2.
6271     unsigned HiIndex;
6272     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6273       int Val = PermMask[HiIndex];
6274       if (Val < 0)
6275         continue;
6276       if (Val >= 4)
6277         break;
6278     }
6279
6280     Mask1[0] = PermMask[HiIndex];
6281     Mask1[1] = -1;
6282     Mask1[2] = PermMask[HiIndex^1];
6283     Mask1[3] = -1;
6284     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6285
6286     if (HiIndex >= 2) {
6287       Mask1[0] = PermMask[0];
6288       Mask1[1] = PermMask[1];
6289       Mask1[2] = HiIndex & 1 ? 6 : 4;
6290       Mask1[3] = HiIndex & 1 ? 4 : 6;
6291       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6292     }
6293
6294     Mask1[0] = HiIndex & 1 ? 2 : 0;
6295     Mask1[1] = HiIndex & 1 ? 0 : 2;
6296     Mask1[2] = PermMask[2];
6297     Mask1[3] = PermMask[3];
6298     if (Mask1[2] >= 0)
6299       Mask1[2] += 4;
6300     if (Mask1[3] >= 0)
6301       Mask1[3] += 4;
6302     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6303   }
6304
6305   // Break it into (shuffle shuffle_hi, shuffle_lo).
6306   int LoMask[] = { -1, -1, -1, -1 };
6307   int HiMask[] = { -1, -1, -1, -1 };
6308
6309   int *MaskPtr = LoMask;
6310   unsigned MaskIdx = 0;
6311   unsigned LoIdx = 0;
6312   unsigned HiIdx = 2;
6313   for (unsigned i = 0; i != 4; ++i) {
6314     if (i == 2) {
6315       MaskPtr = HiMask;
6316       MaskIdx = 1;
6317       LoIdx = 0;
6318       HiIdx = 2;
6319     }
6320     int Idx = PermMask[i];
6321     if (Idx < 0) {
6322       Locs[i] = std::make_pair(-1, -1);
6323     } else if (Idx < 4) {
6324       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6325       MaskPtr[LoIdx] = Idx;
6326       LoIdx++;
6327     } else {
6328       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6329       MaskPtr[HiIdx] = Idx;
6330       HiIdx++;
6331     }
6332   }
6333
6334   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6335   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6336   int MaskOps[] = { -1, -1, -1, -1 };
6337   for (unsigned i = 0; i != 4; ++i)
6338     if (Locs[i].first != -1)
6339       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6340   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6341 }
6342
6343 static bool MayFoldVectorLoad(SDValue V) {
6344   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6345     V = V.getOperand(0);
6346   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6347     V = V.getOperand(0);
6348   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6349       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6350     // BUILD_VECTOR (load), undef
6351     V = V.getOperand(0);
6352   if (MayFoldLoad(V))
6353     return true;
6354   return false;
6355 }
6356
6357 // FIXME: the version above should always be used. Since there's
6358 // a bug where several vector shuffles can't be folded because the
6359 // DAG is not updated during lowering and a node claims to have two
6360 // uses while it only has one, use this version, and let isel match
6361 // another instruction if the load really happens to have more than
6362 // one use. Remove this version after this bug get fixed.
6363 // rdar://8434668, PR8156
6364 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6365   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6366     V = V.getOperand(0);
6367   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6368     V = V.getOperand(0);
6369   if (ISD::isNormalLoad(V.getNode()))
6370     return true;
6371   return false;
6372 }
6373
6374 static
6375 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6376   EVT VT = Op.getValueType();
6377
6378   // Canonizalize to v2f64.
6379   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6380   return DAG.getNode(ISD::BITCAST, dl, VT,
6381                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6382                                           V1, DAG));
6383 }
6384
6385 static
6386 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6387                         bool HasSSE2) {
6388   SDValue V1 = Op.getOperand(0);
6389   SDValue V2 = Op.getOperand(1);
6390   EVT VT = Op.getValueType();
6391
6392   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6393
6394   if (HasSSE2 && VT == MVT::v2f64)
6395     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6396
6397   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6398   return DAG.getNode(ISD::BITCAST, dl, VT,
6399                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6400                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6401                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6402 }
6403
6404 static
6405 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6406   SDValue V1 = Op.getOperand(0);
6407   SDValue V2 = Op.getOperand(1);
6408   EVT VT = Op.getValueType();
6409
6410   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6411          "unsupported shuffle type");
6412
6413   if (V2.getOpcode() == ISD::UNDEF)
6414     V2 = V1;
6415
6416   // v4i32 or v4f32
6417   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6418 }
6419
6420 static
6421 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6422   SDValue V1 = Op.getOperand(0);
6423   SDValue V2 = Op.getOperand(1);
6424   EVT VT = Op.getValueType();
6425   unsigned NumElems = VT.getVectorNumElements();
6426
6427   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6428   // operand of these instructions is only memory, so check if there's a
6429   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6430   // same masks.
6431   bool CanFoldLoad = false;
6432
6433   // Trivial case, when V2 comes from a load.
6434   if (MayFoldVectorLoad(V2))
6435     CanFoldLoad = true;
6436
6437   // When V1 is a load, it can be folded later into a store in isel, example:
6438   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6439   //    turns into:
6440   //  (MOVLPSmr addr:$src1, VR128:$src2)
6441   // So, recognize this potential and also use MOVLPS or MOVLPD
6442   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6443     CanFoldLoad = true;
6444
6445   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6446   if (CanFoldLoad) {
6447     if (HasSSE2 && NumElems == 2)
6448       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6449
6450     if (NumElems == 4)
6451       // If we don't care about the second element, proceed to use movss.
6452       if (SVOp->getMaskElt(1) != -1)
6453         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6454   }
6455
6456   // movl and movlp will both match v2i64, but v2i64 is never matched by
6457   // movl earlier because we make it strict to avoid messing with the movlp load
6458   // folding logic (see the code above getMOVLP call). Match it here then,
6459   // this is horrible, but will stay like this until we move all shuffle
6460   // matching to x86 specific nodes. Note that for the 1st condition all
6461   // types are matched with movsd.
6462   if (HasSSE2) {
6463     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6464     // as to remove this logic from here, as much as possible
6465     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6466       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6467     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6468   }
6469
6470   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6471
6472   // Invert the operand order and use SHUFPS to match it.
6473   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6474                               getShuffleSHUFImmediate(SVOp), DAG);
6475 }
6476
6477 SDValue
6478 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6479   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6480   EVT VT = Op.getValueType();
6481   DebugLoc dl = Op.getDebugLoc();
6482   SDValue V1 = Op.getOperand(0);
6483   SDValue V2 = Op.getOperand(1);
6484
6485   if (isZeroShuffle(SVOp))
6486     return getZeroVector(VT, Subtarget, DAG, dl);
6487
6488   // Handle splat operations
6489   if (SVOp->isSplat()) {
6490     unsigned NumElem = VT.getVectorNumElements();
6491     int Size = VT.getSizeInBits();
6492
6493     // Use vbroadcast whenever the splat comes from a foldable load
6494     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6495     if (Broadcast.getNode())
6496       return Broadcast;
6497
6498     // Handle splats by matching through known shuffle masks
6499     if ((Size == 128 && NumElem <= 4) ||
6500         (Size == 256 && NumElem < 8))
6501       return SDValue();
6502
6503     // All remaning splats are promoted to target supported vector shuffles.
6504     return PromoteSplat(SVOp, DAG);
6505   }
6506
6507   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6508   // do it!
6509   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6510       VT == MVT::v16i16 || VT == MVT::v32i8) {
6511     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6512     if (NewOp.getNode())
6513       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6514   } else if ((VT == MVT::v4i32 ||
6515              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6516     // FIXME: Figure out a cleaner way to do this.
6517     // Try to make use of movq to zero out the top part.
6518     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6519       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6520       if (NewOp.getNode()) {
6521         EVT NewVT = NewOp.getValueType();
6522         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6523                                NewVT, true, false))
6524           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6525                               DAG, Subtarget, dl);
6526       }
6527     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6528       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6529       if (NewOp.getNode()) {
6530         EVT NewVT = NewOp.getValueType();
6531         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6532           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6533                               DAG, Subtarget, dl);
6534       }
6535     }
6536   }
6537   return SDValue();
6538 }
6539
6540 SDValue
6541 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6542   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6543   SDValue V1 = Op.getOperand(0);
6544   SDValue V2 = Op.getOperand(1);
6545   EVT VT = Op.getValueType();
6546   DebugLoc dl = Op.getDebugLoc();
6547   unsigned NumElems = VT.getVectorNumElements();
6548   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6549   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6550   bool V1IsSplat = false;
6551   bool V2IsSplat = false;
6552   bool HasSSE2 = Subtarget->hasSSE2();
6553   bool HasAVX    = Subtarget->hasAVX();
6554   bool HasAVX2   = Subtarget->hasAVX2();
6555   MachineFunction &MF = DAG.getMachineFunction();
6556   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6557
6558   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6559
6560   if (V1IsUndef && V2IsUndef)
6561     return DAG.getUNDEF(VT);
6562
6563   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6564
6565   // Vector shuffle lowering takes 3 steps:
6566   //
6567   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6568   //    narrowing and commutation of operands should be handled.
6569   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6570   //    shuffle nodes.
6571   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6572   //    so the shuffle can be broken into other shuffles and the legalizer can
6573   //    try the lowering again.
6574   //
6575   // The general idea is that no vector_shuffle operation should be left to
6576   // be matched during isel, all of them must be converted to a target specific
6577   // node here.
6578
6579   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6580   // narrowing and commutation of operands should be handled. The actual code
6581   // doesn't include all of those, work in progress...
6582   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6583   if (NewOp.getNode())
6584     return NewOp;
6585
6586   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6587
6588   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6589   // unpckh_undef). Only use pshufd if speed is more important than size.
6590   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6591     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6592   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6593     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6594
6595   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6596       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6597     return getMOVDDup(Op, dl, V1, DAG);
6598
6599   if (isMOVHLPS_v_undef_Mask(M, VT))
6600     return getMOVHighToLow(Op, dl, DAG);
6601
6602   // Use to match splats
6603   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6604       (VT == MVT::v2f64 || VT == MVT::v2i64))
6605     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6606
6607   if (isPSHUFDMask(M, VT)) {
6608     // The actual implementation will match the mask in the if above and then
6609     // during isel it can match several different instructions, not only pshufd
6610     // as its name says, sad but true, emulate the behavior for now...
6611     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6612       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6613
6614     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6615
6616     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6617       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6618
6619     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6620       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6621
6622     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6623                                 TargetMask, DAG);
6624   }
6625
6626   // Check if this can be converted into a logical shift.
6627   bool isLeft = false;
6628   unsigned ShAmt = 0;
6629   SDValue ShVal;
6630   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6631   if (isShift && ShVal.hasOneUse()) {
6632     // If the shifted value has multiple uses, it may be cheaper to use
6633     // v_set0 + movlhps or movhlps, etc.
6634     EVT EltVT = VT.getVectorElementType();
6635     ShAmt *= EltVT.getSizeInBits();
6636     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6637   }
6638
6639   if (isMOVLMask(M, VT)) {
6640     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6641       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6642     if (!isMOVLPMask(M, VT)) {
6643       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6644         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6645
6646       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6647         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6648     }
6649   }
6650
6651   // FIXME: fold these into legal mask.
6652   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6653     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6654
6655   if (isMOVHLPSMask(M, VT))
6656     return getMOVHighToLow(Op, dl, DAG);
6657
6658   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6659     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6660
6661   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6662     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6663
6664   if (isMOVLPMask(M, VT))
6665     return getMOVLP(Op, dl, DAG, HasSSE2);
6666
6667   if (ShouldXformToMOVHLPS(M, VT) ||
6668       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6669     return CommuteVectorShuffle(SVOp, DAG);
6670
6671   if (isShift) {
6672     // No better options. Use a vshldq / vsrldq.
6673     EVT EltVT = VT.getVectorElementType();
6674     ShAmt *= EltVT.getSizeInBits();
6675     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6676   }
6677
6678   bool Commuted = false;
6679   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6680   // 1,1,1,1 -> v8i16 though.
6681   V1IsSplat = isSplatVector(V1.getNode());
6682   V2IsSplat = isSplatVector(V2.getNode());
6683
6684   // Canonicalize the splat or undef, if present, to be on the RHS.
6685   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6686     CommuteVectorShuffleMask(M, NumElems);
6687     std::swap(V1, V2);
6688     std::swap(V1IsSplat, V2IsSplat);
6689     Commuted = true;
6690   }
6691
6692   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6693     // Shuffling low element of v1 into undef, just return v1.
6694     if (V2IsUndef)
6695       return V1;
6696     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6697     // the instruction selector will not match, so get a canonical MOVL with
6698     // swapped operands to undo the commute.
6699     return getMOVL(DAG, dl, VT, V2, V1);
6700   }
6701
6702   if (isUNPCKLMask(M, VT, HasAVX2))
6703     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6704
6705   if (isUNPCKHMask(M, VT, HasAVX2))
6706     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6707
6708   if (V2IsSplat) {
6709     // Normalize mask so all entries that point to V2 points to its first
6710     // element then try to match unpck{h|l} again. If match, return a
6711     // new vector_shuffle with the corrected mask.p
6712     SmallVector<int, 8> NewMask(M.begin(), M.end());
6713     NormalizeMask(NewMask, NumElems);
6714     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6715       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6716     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6717       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6718   }
6719
6720   if (Commuted) {
6721     // Commute is back and try unpck* again.
6722     // FIXME: this seems wrong.
6723     CommuteVectorShuffleMask(M, NumElems);
6724     std::swap(V1, V2);
6725     std::swap(V1IsSplat, V2IsSplat);
6726     Commuted = false;
6727
6728     if (isUNPCKLMask(M, VT, HasAVX2))
6729       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6730
6731     if (isUNPCKHMask(M, VT, HasAVX2))
6732       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6733   }
6734
6735   // Normalize the node to match x86 shuffle ops if needed
6736   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6737     return CommuteVectorShuffle(SVOp, DAG);
6738
6739   // The checks below are all present in isShuffleMaskLegal, but they are
6740   // inlined here right now to enable us to directly emit target specific
6741   // nodes, and remove one by one until they don't return Op anymore.
6742
6743   if (isPALIGNRMask(M, VT, Subtarget))
6744     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6745                                 getShufflePALIGNRImmediate(SVOp),
6746                                 DAG);
6747
6748   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6749       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6750     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6751       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6752   }
6753
6754   if (isPSHUFHWMask(M, VT, HasAVX2))
6755     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6756                                 getShufflePSHUFHWImmediate(SVOp),
6757                                 DAG);
6758
6759   if (isPSHUFLWMask(M, VT, HasAVX2))
6760     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6761                                 getShufflePSHUFLWImmediate(SVOp),
6762                                 DAG);
6763
6764   if (isSHUFPMask(M, VT, HasAVX))
6765     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6766                                 getShuffleSHUFImmediate(SVOp), DAG);
6767
6768   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6769     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6770   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6771     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6772
6773   //===--------------------------------------------------------------------===//
6774   // Generate target specific nodes for 128 or 256-bit shuffles only
6775   // supported in the AVX instruction set.
6776   //
6777
6778   // Handle VMOVDDUPY permutations
6779   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6780     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6781
6782   // Handle VPERMILPS/D* permutations
6783   if (isVPERMILPMask(M, VT, HasAVX)) {
6784     if (HasAVX2 && VT == MVT::v8i32)
6785       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6786                                   getShuffleSHUFImmediate(SVOp), DAG);
6787     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6788                                 getShuffleSHUFImmediate(SVOp), DAG);
6789   }
6790
6791   // Handle VPERM2F128/VPERM2I128 permutations
6792   if (isVPERM2X128Mask(M, VT, HasAVX))
6793     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6794                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6795
6796   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6797   if (BlendOp.getNode())
6798     return BlendOp;
6799
6800   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6801     SmallVector<SDValue, 8> permclMask;
6802     for (unsigned i = 0; i != 8; ++i) {
6803       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6804     }
6805     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6806                                &permclMask[0], 8);
6807     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6808     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6809                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6810   }
6811
6812   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6813     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6814                                 getShuffleCLImmediate(SVOp), DAG);
6815
6816
6817   //===--------------------------------------------------------------------===//
6818   // Since no target specific shuffle was selected for this generic one,
6819   // lower it into other known shuffles. FIXME: this isn't true yet, but
6820   // this is the plan.
6821   //
6822
6823   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6824   if (VT == MVT::v8i16) {
6825     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6826     if (NewOp.getNode())
6827       return NewOp;
6828   }
6829
6830   if (VT == MVT::v16i8) {
6831     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6832     if (NewOp.getNode())
6833       return NewOp;
6834   }
6835
6836   // Handle all 128-bit wide vectors with 4 elements, and match them with
6837   // several different shuffle types.
6838   if (NumElems == 4 && VT.is128BitVector())
6839     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6840
6841   // Handle general 256-bit shuffles
6842   if (VT.is256BitVector())
6843     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6844
6845   return SDValue();
6846 }
6847
6848 SDValue
6849 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6850                                                 SelectionDAG &DAG) const {
6851   EVT VT = Op.getValueType();
6852   DebugLoc dl = Op.getDebugLoc();
6853
6854   if (!Op.getOperand(0).getValueType().is128BitVector())
6855     return SDValue();
6856
6857   if (VT.getSizeInBits() == 8) {
6858     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6859                                     Op.getOperand(0), Op.getOperand(1));
6860     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6861                                     DAG.getValueType(VT));
6862     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6863   }
6864
6865   if (VT.getSizeInBits() == 16) {
6866     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6867     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6868     if (Idx == 0)
6869       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6870                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6871                                      DAG.getNode(ISD::BITCAST, dl,
6872                                                  MVT::v4i32,
6873                                                  Op.getOperand(0)),
6874                                      Op.getOperand(1)));
6875     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6876                                     Op.getOperand(0), Op.getOperand(1));
6877     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6878                                     DAG.getValueType(VT));
6879     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6880   }
6881
6882   if (VT == MVT::f32) {
6883     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6884     // the result back to FR32 register. It's only worth matching if the
6885     // result has a single use which is a store or a bitcast to i32.  And in
6886     // the case of a store, it's not worth it if the index is a constant 0,
6887     // because a MOVSSmr can be used instead, which is smaller and faster.
6888     if (!Op.hasOneUse())
6889       return SDValue();
6890     SDNode *User = *Op.getNode()->use_begin();
6891     if ((User->getOpcode() != ISD::STORE ||
6892          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6893           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6894         (User->getOpcode() != ISD::BITCAST ||
6895          User->getValueType(0) != MVT::i32))
6896       return SDValue();
6897     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6898                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6899                                               Op.getOperand(0)),
6900                                               Op.getOperand(1));
6901     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6902   }
6903
6904   if (VT == MVT::i32 || VT == MVT::i64) {
6905     // ExtractPS/pextrq works with constant index.
6906     if (isa<ConstantSDNode>(Op.getOperand(1)))
6907       return Op;
6908   }
6909   return SDValue();
6910 }
6911
6912
6913 SDValue
6914 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6915                                            SelectionDAG &DAG) const {
6916   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6917     return SDValue();
6918
6919   SDValue Vec = Op.getOperand(0);
6920   EVT VecVT = Vec.getValueType();
6921
6922   // If this is a 256-bit vector result, first extract the 128-bit vector and
6923   // then extract the element from the 128-bit vector.
6924   if (VecVT.is256BitVector()) {
6925     DebugLoc dl = Op.getNode()->getDebugLoc();
6926     unsigned NumElems = VecVT.getVectorNumElements();
6927     SDValue Idx = Op.getOperand(1);
6928     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6929
6930     // Get the 128-bit vector.
6931     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6932
6933     if (IdxVal >= NumElems/2)
6934       IdxVal -= NumElems/2;
6935     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6936                        DAG.getConstant(IdxVal, MVT::i32));
6937   }
6938
6939   assert(VecVT.is128BitVector() && "Unexpected vector length");
6940
6941   if (Subtarget->hasSSE41()) {
6942     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6943     if (Res.getNode())
6944       return Res;
6945   }
6946
6947   EVT VT = Op.getValueType();
6948   DebugLoc dl = Op.getDebugLoc();
6949   // TODO: handle v16i8.
6950   if (VT.getSizeInBits() == 16) {
6951     SDValue Vec = Op.getOperand(0);
6952     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6953     if (Idx == 0)
6954       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6955                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6956                                      DAG.getNode(ISD::BITCAST, dl,
6957                                                  MVT::v4i32, Vec),
6958                                      Op.getOperand(1)));
6959     // Transform it so it match pextrw which produces a 32-bit result.
6960     EVT EltVT = MVT::i32;
6961     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6962                                     Op.getOperand(0), Op.getOperand(1));
6963     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6964                                     DAG.getValueType(VT));
6965     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6966   }
6967
6968   if (VT.getSizeInBits() == 32) {
6969     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6970     if (Idx == 0)
6971       return Op;
6972
6973     // SHUFPS the element to the lowest double word, then movss.
6974     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6975     EVT VVT = Op.getOperand(0).getValueType();
6976     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6977                                        DAG.getUNDEF(VVT), Mask);
6978     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6979                        DAG.getIntPtrConstant(0));
6980   }
6981
6982   if (VT.getSizeInBits() == 64) {
6983     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6984     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6985     //        to match extract_elt for f64.
6986     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6987     if (Idx == 0)
6988       return Op;
6989
6990     // UNPCKHPD the element to the lowest double word, then movsd.
6991     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6992     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6993     int Mask[2] = { 1, -1 };
6994     EVT VVT = Op.getOperand(0).getValueType();
6995     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6996                                        DAG.getUNDEF(VVT), Mask);
6997     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6998                        DAG.getIntPtrConstant(0));
6999   }
7000
7001   return SDValue();
7002 }
7003
7004 SDValue
7005 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7006                                                SelectionDAG &DAG) const {
7007   EVT VT = Op.getValueType();
7008   EVT EltVT = VT.getVectorElementType();
7009   DebugLoc dl = Op.getDebugLoc();
7010
7011   SDValue N0 = Op.getOperand(0);
7012   SDValue N1 = Op.getOperand(1);
7013   SDValue N2 = Op.getOperand(2);
7014
7015   if (!VT.is128BitVector())
7016     return SDValue();
7017
7018   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7019       isa<ConstantSDNode>(N2)) {
7020     unsigned Opc;
7021     if (VT == MVT::v8i16)
7022       Opc = X86ISD::PINSRW;
7023     else if (VT == MVT::v16i8)
7024       Opc = X86ISD::PINSRB;
7025     else
7026       Opc = X86ISD::PINSRB;
7027
7028     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7029     // argument.
7030     if (N1.getValueType() != MVT::i32)
7031       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7032     if (N2.getValueType() != MVT::i32)
7033       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7034     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7035   }
7036
7037   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7038     // Bits [7:6] of the constant are the source select.  This will always be
7039     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7040     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7041     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7042     // Bits [5:4] of the constant are the destination select.  This is the
7043     //  value of the incoming immediate.
7044     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7045     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7046     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7047     // Create this as a scalar to vector..
7048     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7049     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7050   }
7051
7052   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7053     // PINSR* works with constant index.
7054     return Op;
7055   }
7056   return SDValue();
7057 }
7058
7059 SDValue
7060 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7061   EVT VT = Op.getValueType();
7062   EVT EltVT = VT.getVectorElementType();
7063
7064   DebugLoc dl = Op.getDebugLoc();
7065   SDValue N0 = Op.getOperand(0);
7066   SDValue N1 = Op.getOperand(1);
7067   SDValue N2 = Op.getOperand(2);
7068
7069   // If this is a 256-bit vector result, first extract the 128-bit vector,
7070   // insert the element into the extracted half and then place it back.
7071   if (VT.is256BitVector()) {
7072     if (!isa<ConstantSDNode>(N2))
7073       return SDValue();
7074
7075     // Get the desired 128-bit vector half.
7076     unsigned NumElems = VT.getVectorNumElements();
7077     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7078     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7079
7080     // Insert the element into the desired half.
7081     bool Upper = IdxVal >= NumElems/2;
7082     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7083                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7084
7085     // Insert the changed part back to the 256-bit vector
7086     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7087   }
7088
7089   if (Subtarget->hasSSE41())
7090     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7091
7092   if (EltVT == MVT::i8)
7093     return SDValue();
7094
7095   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7096     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7097     // as its second argument.
7098     if (N1.getValueType() != MVT::i32)
7099       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7100     if (N2.getValueType() != MVT::i32)
7101       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7102     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7103   }
7104   return SDValue();
7105 }
7106
7107 SDValue
7108 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7109   LLVMContext *Context = DAG.getContext();
7110   DebugLoc dl = Op.getDebugLoc();
7111   EVT OpVT = Op.getValueType();
7112
7113   // If this is a 256-bit vector result, first insert into a 128-bit
7114   // vector and then insert into the 256-bit vector.
7115   if (!OpVT.is128BitVector()) {
7116     // Insert into a 128-bit vector.
7117     EVT VT128 = EVT::getVectorVT(*Context,
7118                                  OpVT.getVectorElementType(),
7119                                  OpVT.getVectorNumElements() / 2);
7120
7121     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7122
7123     // Insert the 128-bit vector.
7124     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7125   }
7126
7127   if (OpVT == MVT::v1i64 &&
7128       Op.getOperand(0).getValueType() == MVT::i64)
7129     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7130
7131   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7132   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7133   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7134                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7135 }
7136
7137 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7138 // a simple subregister reference or explicit instructions to grab
7139 // upper bits of a vector.
7140 SDValue
7141 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7142   if (Subtarget->hasAVX()) {
7143     DebugLoc dl = Op.getNode()->getDebugLoc();
7144     SDValue Vec = Op.getNode()->getOperand(0);
7145     SDValue Idx = Op.getNode()->getOperand(1);
7146
7147     if (Op.getNode()->getValueType(0).is128BitVector() &&
7148         Vec.getNode()->getValueType(0).is256BitVector() &&
7149         isa<ConstantSDNode>(Idx)) {
7150       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7151       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7152     }
7153   }
7154   return SDValue();
7155 }
7156
7157 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7158 // simple superregister reference or explicit instructions to insert
7159 // the upper bits of a vector.
7160 SDValue
7161 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7162   if (Subtarget->hasAVX()) {
7163     DebugLoc dl = Op.getNode()->getDebugLoc();
7164     SDValue Vec = Op.getNode()->getOperand(0);
7165     SDValue SubVec = Op.getNode()->getOperand(1);
7166     SDValue Idx = Op.getNode()->getOperand(2);
7167
7168     if (Op.getNode()->getValueType(0).is256BitVector() &&
7169         SubVec.getNode()->getValueType(0).is128BitVector() &&
7170         isa<ConstantSDNode>(Idx)) {
7171       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7172       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7173     }
7174   }
7175   return SDValue();
7176 }
7177
7178 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7179 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7180 // one of the above mentioned nodes. It has to be wrapped because otherwise
7181 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7182 // be used to form addressing mode. These wrapped nodes will be selected
7183 // into MOV32ri.
7184 SDValue
7185 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7186   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7187
7188   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7189   // global base reg.
7190   unsigned char OpFlag = 0;
7191   unsigned WrapperKind = X86ISD::Wrapper;
7192   CodeModel::Model M = getTargetMachine().getCodeModel();
7193
7194   if (Subtarget->isPICStyleRIPRel() &&
7195       (M == CodeModel::Small || M == CodeModel::Kernel))
7196     WrapperKind = X86ISD::WrapperRIP;
7197   else if (Subtarget->isPICStyleGOT())
7198     OpFlag = X86II::MO_GOTOFF;
7199   else if (Subtarget->isPICStyleStubPIC())
7200     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7201
7202   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7203                                              CP->getAlignment(),
7204                                              CP->getOffset(), OpFlag);
7205   DebugLoc DL = CP->getDebugLoc();
7206   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7207   // With PIC, the address is actually $g + Offset.
7208   if (OpFlag) {
7209     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7210                          DAG.getNode(X86ISD::GlobalBaseReg,
7211                                      DebugLoc(), getPointerTy()),
7212                          Result);
7213   }
7214
7215   return Result;
7216 }
7217
7218 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7219   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7220
7221   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7222   // global base reg.
7223   unsigned char OpFlag = 0;
7224   unsigned WrapperKind = X86ISD::Wrapper;
7225   CodeModel::Model M = getTargetMachine().getCodeModel();
7226
7227   if (Subtarget->isPICStyleRIPRel() &&
7228       (M == CodeModel::Small || M == CodeModel::Kernel))
7229     WrapperKind = X86ISD::WrapperRIP;
7230   else if (Subtarget->isPICStyleGOT())
7231     OpFlag = X86II::MO_GOTOFF;
7232   else if (Subtarget->isPICStyleStubPIC())
7233     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7234
7235   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7236                                           OpFlag);
7237   DebugLoc DL = JT->getDebugLoc();
7238   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7239
7240   // With PIC, the address is actually $g + Offset.
7241   if (OpFlag)
7242     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7243                          DAG.getNode(X86ISD::GlobalBaseReg,
7244                                      DebugLoc(), getPointerTy()),
7245                          Result);
7246
7247   return Result;
7248 }
7249
7250 SDValue
7251 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7252   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7253
7254   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7255   // global base reg.
7256   unsigned char OpFlag = 0;
7257   unsigned WrapperKind = X86ISD::Wrapper;
7258   CodeModel::Model M = getTargetMachine().getCodeModel();
7259
7260   if (Subtarget->isPICStyleRIPRel() &&
7261       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7262     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7263       OpFlag = X86II::MO_GOTPCREL;
7264     WrapperKind = X86ISD::WrapperRIP;
7265   } else if (Subtarget->isPICStyleGOT()) {
7266     OpFlag = X86II::MO_GOT;
7267   } else if (Subtarget->isPICStyleStubPIC()) {
7268     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7269   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7270     OpFlag = X86II::MO_DARWIN_NONLAZY;
7271   }
7272
7273   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7274
7275   DebugLoc DL = Op.getDebugLoc();
7276   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7277
7278
7279   // With PIC, the address is actually $g + Offset.
7280   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7281       !Subtarget->is64Bit()) {
7282     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7283                          DAG.getNode(X86ISD::GlobalBaseReg,
7284                                      DebugLoc(), getPointerTy()),
7285                          Result);
7286   }
7287
7288   // For symbols that require a load from a stub to get the address, emit the
7289   // load.
7290   if (isGlobalStubReference(OpFlag))
7291     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7292                          MachinePointerInfo::getGOT(), false, false, false, 0);
7293
7294   return Result;
7295 }
7296
7297 SDValue
7298 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7299   // Create the TargetBlockAddressAddress node.
7300   unsigned char OpFlags =
7301     Subtarget->ClassifyBlockAddressReference();
7302   CodeModel::Model M = getTargetMachine().getCodeModel();
7303   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7304   DebugLoc dl = Op.getDebugLoc();
7305   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7306                                        /*isTarget=*/true, OpFlags);
7307
7308   if (Subtarget->isPICStyleRIPRel() &&
7309       (M == CodeModel::Small || M == CodeModel::Kernel))
7310     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7311   else
7312     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7313
7314   // With PIC, the address is actually $g + Offset.
7315   if (isGlobalRelativeToPICBase(OpFlags)) {
7316     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7317                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7318                          Result);
7319   }
7320
7321   return Result;
7322 }
7323
7324 SDValue
7325 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7326                                       int64_t Offset,
7327                                       SelectionDAG &DAG) const {
7328   // Create the TargetGlobalAddress node, folding in the constant
7329   // offset if it is legal.
7330   unsigned char OpFlags =
7331     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7332   CodeModel::Model M = getTargetMachine().getCodeModel();
7333   SDValue Result;
7334   if (OpFlags == X86II::MO_NO_FLAG &&
7335       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7336     // A direct static reference to a global.
7337     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7338     Offset = 0;
7339   } else {
7340     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7341   }
7342
7343   if (Subtarget->isPICStyleRIPRel() &&
7344       (M == CodeModel::Small || M == CodeModel::Kernel))
7345     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7346   else
7347     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7348
7349   // With PIC, the address is actually $g + Offset.
7350   if (isGlobalRelativeToPICBase(OpFlags)) {
7351     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7352                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7353                          Result);
7354   }
7355
7356   // For globals that require a load from a stub to get the address, emit the
7357   // load.
7358   if (isGlobalStubReference(OpFlags))
7359     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7360                          MachinePointerInfo::getGOT(), false, false, false, 0);
7361
7362   // If there was a non-zero offset that we didn't fold, create an explicit
7363   // addition for it.
7364   if (Offset != 0)
7365     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7366                          DAG.getConstant(Offset, getPointerTy()));
7367
7368   return Result;
7369 }
7370
7371 SDValue
7372 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7373   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7374   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7375   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7376 }
7377
7378 static SDValue
7379 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7380            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7381            unsigned char OperandFlags, bool LocalDynamic = false) {
7382   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7383   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7384   DebugLoc dl = GA->getDebugLoc();
7385   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7386                                            GA->getValueType(0),
7387                                            GA->getOffset(),
7388                                            OperandFlags);
7389
7390   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7391                                            : X86ISD::TLSADDR;
7392
7393   if (InFlag) {
7394     SDValue Ops[] = { Chain,  TGA, *InFlag };
7395     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7396   } else {
7397     SDValue Ops[]  = { Chain, TGA };
7398     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7399   }
7400
7401   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7402   MFI->setAdjustsStack(true);
7403
7404   SDValue Flag = Chain.getValue(1);
7405   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7406 }
7407
7408 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7409 static SDValue
7410 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7411                                 const EVT PtrVT) {
7412   SDValue InFlag;
7413   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7414   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7415                                      DAG.getNode(X86ISD::GlobalBaseReg,
7416                                                  DebugLoc(), PtrVT), InFlag);
7417   InFlag = Chain.getValue(1);
7418
7419   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7420 }
7421
7422 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7423 static SDValue
7424 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7425                                 const EVT PtrVT) {
7426   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7427                     X86::RAX, X86II::MO_TLSGD);
7428 }
7429
7430 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7431                                            SelectionDAG &DAG,
7432                                            const EVT PtrVT,
7433                                            bool is64Bit) {
7434   DebugLoc dl = GA->getDebugLoc();
7435
7436   // Get the start address of the TLS block for this module.
7437   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7438       .getInfo<X86MachineFunctionInfo>();
7439   MFI->incNumLocalDynamicTLSAccesses();
7440
7441   SDValue Base;
7442   if (is64Bit) {
7443     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7444                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7445   } else {
7446     SDValue InFlag;
7447     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7448         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7449     InFlag = Chain.getValue(1);
7450     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7451                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7452   }
7453
7454   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7455   // of Base.
7456
7457   // Build x@dtpoff.
7458   unsigned char OperandFlags = X86II::MO_DTPOFF;
7459   unsigned WrapperKind = X86ISD::Wrapper;
7460   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7461                                            GA->getValueType(0),
7462                                            GA->getOffset(), OperandFlags);
7463   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7464
7465   // Add x@dtpoff with the base.
7466   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7467 }
7468
7469 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7470 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7471                                    const EVT PtrVT, TLSModel::Model model,
7472                                    bool is64Bit, bool isPIC) {
7473   DebugLoc dl = GA->getDebugLoc();
7474
7475   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7476   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7477                                                          is64Bit ? 257 : 256));
7478
7479   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7480                                       DAG.getIntPtrConstant(0),
7481                                       MachinePointerInfo(Ptr),
7482                                       false, false, false, 0);
7483
7484   unsigned char OperandFlags = 0;
7485   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7486   // initialexec.
7487   unsigned WrapperKind = X86ISD::Wrapper;
7488   if (model == TLSModel::LocalExec) {
7489     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7490   } else if (model == TLSModel::InitialExec) {
7491     if (is64Bit) {
7492       OperandFlags = X86II::MO_GOTTPOFF;
7493       WrapperKind = X86ISD::WrapperRIP;
7494     } else {
7495       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7496     }
7497   } else {
7498     llvm_unreachable("Unexpected model");
7499   }
7500
7501   // emit "addl x@ntpoff,%eax" (local exec)
7502   // or "addl x@indntpoff,%eax" (initial exec)
7503   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7504   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7505                                            GA->getValueType(0),
7506                                            GA->getOffset(), OperandFlags);
7507   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7508
7509   if (model == TLSModel::InitialExec) {
7510     if (isPIC && !is64Bit) {
7511       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7512                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7513                            Offset);
7514     }
7515
7516     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7517                          MachinePointerInfo::getGOT(), false, false, false,
7518                          0);
7519   }
7520
7521   // The address of the thread local variable is the add of the thread
7522   // pointer with the offset of the variable.
7523   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7524 }
7525
7526 SDValue
7527 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7528
7529   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7530   const GlobalValue *GV = GA->getGlobal();
7531
7532   if (Subtarget->isTargetELF()) {
7533     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7534
7535     switch (model) {
7536       case TLSModel::GeneralDynamic:
7537         if (Subtarget->is64Bit())
7538           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7539         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7540       case TLSModel::LocalDynamic:
7541         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7542                                            Subtarget->is64Bit());
7543       case TLSModel::InitialExec:
7544       case TLSModel::LocalExec:
7545         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7546                                    Subtarget->is64Bit(),
7547                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7548     }
7549     llvm_unreachable("Unknown TLS model.");
7550   }
7551
7552   if (Subtarget->isTargetDarwin()) {
7553     // Darwin only has one model of TLS.  Lower to that.
7554     unsigned char OpFlag = 0;
7555     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7556                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7557
7558     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7559     // global base reg.
7560     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7561                   !Subtarget->is64Bit();
7562     if (PIC32)
7563       OpFlag = X86II::MO_TLVP_PIC_BASE;
7564     else
7565       OpFlag = X86II::MO_TLVP;
7566     DebugLoc DL = Op.getDebugLoc();
7567     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7568                                                 GA->getValueType(0),
7569                                                 GA->getOffset(), OpFlag);
7570     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7571
7572     // With PIC32, the address is actually $g + Offset.
7573     if (PIC32)
7574       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7575                            DAG.getNode(X86ISD::GlobalBaseReg,
7576                                        DebugLoc(), getPointerTy()),
7577                            Offset);
7578
7579     // Lowering the machine isd will make sure everything is in the right
7580     // location.
7581     SDValue Chain = DAG.getEntryNode();
7582     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7583     SDValue Args[] = { Chain, Offset };
7584     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7585
7586     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7587     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7588     MFI->setAdjustsStack(true);
7589
7590     // And our return value (tls address) is in the standard call return value
7591     // location.
7592     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7593     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7594                               Chain.getValue(1));
7595   }
7596
7597   if (Subtarget->isTargetWindows()) {
7598     // Just use the implicit TLS architecture
7599     // Need to generate someting similar to:
7600     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7601     //                                  ; from TEB
7602     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7603     //   mov     rcx, qword [rdx+rcx*8]
7604     //   mov     eax, .tls$:tlsvar
7605     //   [rax+rcx] contains the address
7606     // Windows 64bit: gs:0x58
7607     // Windows 32bit: fs:__tls_array
7608
7609     // If GV is an alias then use the aliasee for determining
7610     // thread-localness.
7611     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7612       GV = GA->resolveAliasedGlobal(false);
7613     DebugLoc dl = GA->getDebugLoc();
7614     SDValue Chain = DAG.getEntryNode();
7615
7616     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7617     // %gs:0x58 (64-bit).
7618     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7619                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7620                                                              256)
7621                                         : Type::getInt32PtrTy(*DAG.getContext(),
7622                                                               257));
7623
7624     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7625                                         Subtarget->is64Bit()
7626                                         ? DAG.getIntPtrConstant(0x58)
7627                                         : DAG.getExternalSymbol("_tls_array",
7628                                                                 getPointerTy()),
7629                                         MachinePointerInfo(Ptr),
7630                                         false, false, false, 0);
7631
7632     // Load the _tls_index variable
7633     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7634     if (Subtarget->is64Bit())
7635       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7636                            IDX, MachinePointerInfo(), MVT::i32,
7637                            false, false, 0);
7638     else
7639       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7640                         false, false, false, 0);
7641
7642     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7643                                     getPointerTy());
7644     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7645
7646     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7647     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7648                       false, false, false, 0);
7649
7650     // Get the offset of start of .tls section
7651     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7652                                              GA->getValueType(0),
7653                                              GA->getOffset(), X86II::MO_SECREL);
7654     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7655
7656     // The address of the thread local variable is the add of the thread
7657     // pointer with the offset of the variable.
7658     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7659   }
7660
7661   llvm_unreachable("TLS not implemented for this target.");
7662 }
7663
7664
7665 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7666 /// and take a 2 x i32 value to shift plus a shift amount.
7667 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7668   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7669   EVT VT = Op.getValueType();
7670   unsigned VTBits = VT.getSizeInBits();
7671   DebugLoc dl = Op.getDebugLoc();
7672   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7673   SDValue ShOpLo = Op.getOperand(0);
7674   SDValue ShOpHi = Op.getOperand(1);
7675   SDValue ShAmt  = Op.getOperand(2);
7676   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7677                                      DAG.getConstant(VTBits - 1, MVT::i8))
7678                        : DAG.getConstant(0, VT);
7679
7680   SDValue Tmp2, Tmp3;
7681   if (Op.getOpcode() == ISD::SHL_PARTS) {
7682     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7683     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7684   } else {
7685     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7686     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7687   }
7688
7689   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7690                                 DAG.getConstant(VTBits, MVT::i8));
7691   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7692                              AndNode, DAG.getConstant(0, MVT::i8));
7693
7694   SDValue Hi, Lo;
7695   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7696   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7697   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7698
7699   if (Op.getOpcode() == ISD::SHL_PARTS) {
7700     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7701     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7702   } else {
7703     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7704     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7705   }
7706
7707   SDValue Ops[2] = { Lo, Hi };
7708   return DAG.getMergeValues(Ops, 2, dl);
7709 }
7710
7711 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7712                                            SelectionDAG &DAG) const {
7713   EVT SrcVT = Op.getOperand(0).getValueType();
7714
7715   if (SrcVT.isVector())
7716     return SDValue();
7717
7718   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7719          "Unknown SINT_TO_FP to lower!");
7720
7721   // These are really Legal; return the operand so the caller accepts it as
7722   // Legal.
7723   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7724     return Op;
7725   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7726       Subtarget->is64Bit()) {
7727     return Op;
7728   }
7729
7730   DebugLoc dl = Op.getDebugLoc();
7731   unsigned Size = SrcVT.getSizeInBits()/8;
7732   MachineFunction &MF = DAG.getMachineFunction();
7733   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7734   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7735   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7736                                StackSlot,
7737                                MachinePointerInfo::getFixedStack(SSFI),
7738                                false, false, 0);
7739   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7740 }
7741
7742 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7743                                      SDValue StackSlot,
7744                                      SelectionDAG &DAG) const {
7745   // Build the FILD
7746   DebugLoc DL = Op.getDebugLoc();
7747   SDVTList Tys;
7748   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7749   if (useSSE)
7750     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7751   else
7752     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7753
7754   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7755
7756   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7757   MachineMemOperand *MMO;
7758   if (FI) {
7759     int SSFI = FI->getIndex();
7760     MMO =
7761       DAG.getMachineFunction()
7762       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7763                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7764   } else {
7765     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7766     StackSlot = StackSlot.getOperand(1);
7767   }
7768   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7769   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7770                                            X86ISD::FILD, DL,
7771                                            Tys, Ops, array_lengthof(Ops),
7772                                            SrcVT, MMO);
7773
7774   if (useSSE) {
7775     Chain = Result.getValue(1);
7776     SDValue InFlag = Result.getValue(2);
7777
7778     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7779     // shouldn't be necessary except that RFP cannot be live across
7780     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7781     MachineFunction &MF = DAG.getMachineFunction();
7782     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7783     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7784     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7785     Tys = DAG.getVTList(MVT::Other);
7786     SDValue Ops[] = {
7787       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7788     };
7789     MachineMemOperand *MMO =
7790       DAG.getMachineFunction()
7791       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7792                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7793
7794     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7795                                     Ops, array_lengthof(Ops),
7796                                     Op.getValueType(), MMO);
7797     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7798                          MachinePointerInfo::getFixedStack(SSFI),
7799                          false, false, false, 0);
7800   }
7801
7802   return Result;
7803 }
7804
7805 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7806 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7807                                                SelectionDAG &DAG) const {
7808   // This algorithm is not obvious. Here it is what we're trying to output:
7809   /*
7810      movq       %rax,  %xmm0
7811      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7812      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7813      #ifdef __SSE3__
7814        haddpd   %xmm0, %xmm0
7815      #else
7816        pshufd   $0x4e, %xmm0, %xmm1
7817        addpd    %xmm1, %xmm0
7818      #endif
7819   */
7820
7821   DebugLoc dl = Op.getDebugLoc();
7822   LLVMContext *Context = DAG.getContext();
7823
7824   // Build some magic constants.
7825   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7826   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7827   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7828
7829   SmallVector<Constant*,2> CV1;
7830   CV1.push_back(
7831         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7832   CV1.push_back(
7833         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7834   Constant *C1 = ConstantVector::get(CV1);
7835   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7836
7837   // Load the 64-bit value into an XMM register.
7838   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7839                             Op.getOperand(0));
7840   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7841                               MachinePointerInfo::getConstantPool(),
7842                               false, false, false, 16);
7843   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7844                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7845                               CLod0);
7846
7847   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7848                               MachinePointerInfo::getConstantPool(),
7849                               false, false, false, 16);
7850   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7851   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7852   SDValue Result;
7853
7854   if (Subtarget->hasSSE3()) {
7855     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7856     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7857   } else {
7858     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7859     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7860                                            S2F, 0x4E, DAG);
7861     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7862                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7863                          Sub);
7864   }
7865
7866   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7867                      DAG.getIntPtrConstant(0));
7868 }
7869
7870 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7871 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7872                                                SelectionDAG &DAG) const {
7873   DebugLoc dl = Op.getDebugLoc();
7874   // FP constant to bias correct the final result.
7875   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7876                                    MVT::f64);
7877
7878   // Load the 32-bit value into an XMM register.
7879   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7880                              Op.getOperand(0));
7881
7882   // Zero out the upper parts of the register.
7883   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7884
7885   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7886                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7887                      DAG.getIntPtrConstant(0));
7888
7889   // Or the load with the bias.
7890   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7891                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7892                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7893                                                    MVT::v2f64, Load)),
7894                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7895                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7896                                                    MVT::v2f64, Bias)));
7897   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7898                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7899                    DAG.getIntPtrConstant(0));
7900
7901   // Subtract the bias.
7902   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7903
7904   // Handle final rounding.
7905   EVT DestVT = Op.getValueType();
7906
7907   if (DestVT.bitsLT(MVT::f64))
7908     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7909                        DAG.getIntPtrConstant(0));
7910   if (DestVT.bitsGT(MVT::f64))
7911     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7912
7913   // Handle final rounding.
7914   return Sub;
7915 }
7916
7917 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7918                                            SelectionDAG &DAG) const {
7919   SDValue N0 = Op.getOperand(0);
7920   DebugLoc dl = Op.getDebugLoc();
7921
7922   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7923   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7924   // the optimization here.
7925   if (DAG.SignBitIsZero(N0))
7926     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7927
7928   EVT SrcVT = N0.getValueType();
7929   EVT DstVT = Op.getValueType();
7930   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7931     return LowerUINT_TO_FP_i64(Op, DAG);
7932   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7933     return LowerUINT_TO_FP_i32(Op, DAG);
7934   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7935     return SDValue();
7936
7937   // Make a 64-bit buffer, and use it to build an FILD.
7938   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7939   if (SrcVT == MVT::i32) {
7940     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7941     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7942                                      getPointerTy(), StackSlot, WordOff);
7943     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7944                                   StackSlot, MachinePointerInfo(),
7945                                   false, false, 0);
7946     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7947                                   OffsetSlot, MachinePointerInfo(),
7948                                   false, false, 0);
7949     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7950     return Fild;
7951   }
7952
7953   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7954   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7955                                StackSlot, MachinePointerInfo(),
7956                                false, false, 0);
7957   // For i64 source, we need to add the appropriate power of 2 if the input
7958   // was negative.  This is the same as the optimization in
7959   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7960   // we must be careful to do the computation in x87 extended precision, not
7961   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7962   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7963   MachineMemOperand *MMO =
7964     DAG.getMachineFunction()
7965     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7966                           MachineMemOperand::MOLoad, 8, 8);
7967
7968   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7969   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7970   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7971                                          MVT::i64, MMO);
7972
7973   APInt FF(32, 0x5F800000ULL);
7974
7975   // Check whether the sign bit is set.
7976   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7977                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7978                                  ISD::SETLT);
7979
7980   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7981   SDValue FudgePtr = DAG.getConstantPool(
7982                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7983                                          getPointerTy());
7984
7985   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7986   SDValue Zero = DAG.getIntPtrConstant(0);
7987   SDValue Four = DAG.getIntPtrConstant(4);
7988   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7989                                Zero, Four);
7990   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7991
7992   // Load the value out, extending it from f32 to f80.
7993   // FIXME: Avoid the extend by constructing the right constant pool?
7994   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7995                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7996                                  MVT::f32, false, false, 4);
7997   // Extend everything to 80 bits to force it to be done on x87.
7998   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7999   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8000 }
8001
8002 std::pair<SDValue,SDValue> X86TargetLowering::
8003 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8004   DebugLoc DL = Op.getDebugLoc();
8005
8006   EVT DstTy = Op.getValueType();
8007
8008   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8009     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8010     DstTy = MVT::i64;
8011   }
8012
8013   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8014          DstTy.getSimpleVT() >= MVT::i16 &&
8015          "Unknown FP_TO_INT to lower!");
8016
8017   // These are really Legal.
8018   if (DstTy == MVT::i32 &&
8019       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8020     return std::make_pair(SDValue(), SDValue());
8021   if (Subtarget->is64Bit() &&
8022       DstTy == MVT::i64 &&
8023       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8024     return std::make_pair(SDValue(), SDValue());
8025
8026   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8027   // stack slot, or into the FTOL runtime function.
8028   MachineFunction &MF = DAG.getMachineFunction();
8029   unsigned MemSize = DstTy.getSizeInBits()/8;
8030   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8031   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8032
8033   unsigned Opc;
8034   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8035     Opc = X86ISD::WIN_FTOL;
8036   else
8037     switch (DstTy.getSimpleVT().SimpleTy) {
8038     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8039     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8040     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8041     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8042     }
8043
8044   SDValue Chain = DAG.getEntryNode();
8045   SDValue Value = Op.getOperand(0);
8046   EVT TheVT = Op.getOperand(0).getValueType();
8047   // FIXME This causes a redundant load/store if the SSE-class value is already
8048   // in memory, such as if it is on the callstack.
8049   if (isScalarFPTypeInSSEReg(TheVT)) {
8050     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8051     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8052                          MachinePointerInfo::getFixedStack(SSFI),
8053                          false, false, 0);
8054     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8055     SDValue Ops[] = {
8056       Chain, StackSlot, DAG.getValueType(TheVT)
8057     };
8058
8059     MachineMemOperand *MMO =
8060       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8061                               MachineMemOperand::MOLoad, MemSize, MemSize);
8062     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8063                                     DstTy, MMO);
8064     Chain = Value.getValue(1);
8065     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8066     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8067   }
8068
8069   MachineMemOperand *MMO =
8070     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8071                             MachineMemOperand::MOStore, MemSize, MemSize);
8072
8073   if (Opc != X86ISD::WIN_FTOL) {
8074     // Build the FP_TO_INT*_IN_MEM
8075     SDValue Ops[] = { Chain, Value, StackSlot };
8076     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8077                                            Ops, 3, DstTy, MMO);
8078     return std::make_pair(FIST, StackSlot);
8079   } else {
8080     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8081       DAG.getVTList(MVT::Other, MVT::Glue),
8082       Chain, Value);
8083     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8084       MVT::i32, ftol.getValue(1));
8085     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8086       MVT::i32, eax.getValue(2));
8087     SDValue Ops[] = { eax, edx };
8088     SDValue pair = IsReplace
8089       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8090       : DAG.getMergeValues(Ops, 2, DL);
8091     return std::make_pair(pair, SDValue());
8092   }
8093 }
8094
8095 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8096                                            SelectionDAG &DAG) const {
8097   if (Op.getValueType().isVector())
8098     return SDValue();
8099
8100   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8101     /*IsSigned=*/ true, /*IsReplace=*/ false);
8102   SDValue FIST = Vals.first, StackSlot = Vals.second;
8103   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8104   if (FIST.getNode() == 0) return Op;
8105
8106   if (StackSlot.getNode())
8107     // Load the result.
8108     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8109                        FIST, StackSlot, MachinePointerInfo(),
8110                        false, false, false, 0);
8111
8112   // The node is the result.
8113   return FIST;
8114 }
8115
8116 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8117                                            SelectionDAG &DAG) const {
8118   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8119     /*IsSigned=*/ false, /*IsReplace=*/ false);
8120   SDValue FIST = Vals.first, StackSlot = Vals.second;
8121   assert(FIST.getNode() && "Unexpected failure");
8122
8123   if (StackSlot.getNode())
8124     // Load the result.
8125     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8126                        FIST, StackSlot, MachinePointerInfo(),
8127                        false, false, false, 0);
8128
8129   // The node is the result.
8130   return FIST;
8131 }
8132
8133 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8134                                      SelectionDAG &DAG) const {
8135   LLVMContext *Context = DAG.getContext();
8136   DebugLoc dl = Op.getDebugLoc();
8137   EVT VT = Op.getValueType();
8138   EVT EltVT = VT;
8139   if (VT.isVector())
8140     EltVT = VT.getVectorElementType();
8141   Constant *C;
8142   if (EltVT == MVT::f64) {
8143     C = ConstantVector::getSplat(2,
8144                 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8145   } else {
8146     C = ConstantVector::getSplat(4,
8147                ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8148   }
8149   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8150   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8151                              MachinePointerInfo::getConstantPool(),
8152                              false, false, false, 16);
8153   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8154 }
8155
8156 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8157   LLVMContext *Context = DAG.getContext();
8158   DebugLoc dl = Op.getDebugLoc();
8159   EVT VT = Op.getValueType();
8160   EVT EltVT = VT;
8161   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8162   if (VT.isVector()) {
8163     EltVT = VT.getVectorElementType();
8164     NumElts = VT.getVectorNumElements();
8165   }
8166   Constant *C;
8167   if (EltVT == MVT::f64)
8168     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8169   else
8170     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8171   C = ConstantVector::getSplat(NumElts, C);
8172   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8173   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8174                              MachinePointerInfo::getConstantPool(),
8175                              false, false, false, 16);
8176   if (VT.isVector()) {
8177     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8178     return DAG.getNode(ISD::BITCAST, dl, VT,
8179                        DAG.getNode(ISD::XOR, dl, XORVT,
8180                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8181                                                Op.getOperand(0)),
8182                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8183   }
8184
8185   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8186 }
8187
8188 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8189   LLVMContext *Context = DAG.getContext();
8190   SDValue Op0 = Op.getOperand(0);
8191   SDValue Op1 = Op.getOperand(1);
8192   DebugLoc dl = Op.getDebugLoc();
8193   EVT VT = Op.getValueType();
8194   EVT SrcVT = Op1.getValueType();
8195
8196   // If second operand is smaller, extend it first.
8197   if (SrcVT.bitsLT(VT)) {
8198     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8199     SrcVT = VT;
8200   }
8201   // And if it is bigger, shrink it first.
8202   if (SrcVT.bitsGT(VT)) {
8203     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8204     SrcVT = VT;
8205   }
8206
8207   // At this point the operands and the result should have the same
8208   // type, and that won't be f80 since that is not custom lowered.
8209
8210   // First get the sign bit of second operand.
8211   SmallVector<Constant*,4> CV;
8212   if (SrcVT == MVT::f64) {
8213     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8214     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8215   } else {
8216     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8217     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8218     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8219     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8220   }
8221   Constant *C = ConstantVector::get(CV);
8222   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8223   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8224                               MachinePointerInfo::getConstantPool(),
8225                               false, false, false, 16);
8226   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8227
8228   // Shift sign bit right or left if the two operands have different types.
8229   if (SrcVT.bitsGT(VT)) {
8230     // Op0 is MVT::f32, Op1 is MVT::f64.
8231     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8232     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8233                           DAG.getConstant(32, MVT::i32));
8234     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8235     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8236                           DAG.getIntPtrConstant(0));
8237   }
8238
8239   // Clear first operand sign bit.
8240   CV.clear();
8241   if (VT == MVT::f64) {
8242     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8243     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8244   } else {
8245     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8246     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8247     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8248     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8249   }
8250   C = ConstantVector::get(CV);
8251   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8252   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8253                               MachinePointerInfo::getConstantPool(),
8254                               false, false, false, 16);
8255   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8256
8257   // Or the value with the sign bit.
8258   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8259 }
8260
8261 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8262   SDValue N0 = Op.getOperand(0);
8263   DebugLoc dl = Op.getDebugLoc();
8264   EVT VT = Op.getValueType();
8265
8266   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8267   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8268                                   DAG.getConstant(1, VT));
8269   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8270 }
8271
8272 /// Emit nodes that will be selected as "test Op0,Op0", or something
8273 /// equivalent.
8274 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8275                                     SelectionDAG &DAG) const {
8276   DebugLoc dl = Op.getDebugLoc();
8277
8278   // CF and OF aren't always set the way we want. Determine which
8279   // of these we need.
8280   bool NeedCF = false;
8281   bool NeedOF = false;
8282   switch (X86CC) {
8283   default: break;
8284   case X86::COND_A: case X86::COND_AE:
8285   case X86::COND_B: case X86::COND_BE:
8286     NeedCF = true;
8287     break;
8288   case X86::COND_G: case X86::COND_GE:
8289   case X86::COND_L: case X86::COND_LE:
8290   case X86::COND_O: case X86::COND_NO:
8291     NeedOF = true;
8292     break;
8293   }
8294
8295   // See if we can use the EFLAGS value from the operand instead of
8296   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8297   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8298   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8299     // Emit a CMP with 0, which is the TEST pattern.
8300     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8301                        DAG.getConstant(0, Op.getValueType()));
8302
8303   unsigned Opcode = 0;
8304   unsigned NumOperands = 0;
8305
8306   // Truncate operations may prevent the merge of the SETCC instruction
8307   // and the arithmetic intruction before it. Attempt to truncate the operands
8308   // of the arithmetic instruction and use a reduced bit-width instruction.
8309   bool NeedTruncation = false;
8310   SDValue ArithOp = Op;
8311   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8312     SDValue Arith = Op->getOperand(0);
8313     // Both the trunc and the arithmetic op need to have one user each.
8314     if (Arith->hasOneUse())
8315       switch (Arith.getOpcode()) {
8316         default: break;
8317         case ISD::ADD:
8318         case ISD::SUB:
8319         case ISD::AND:
8320         case ISD::OR:
8321         case ISD::XOR: {
8322           NeedTruncation = true;
8323           ArithOp = Arith;
8324         }
8325       }
8326   }
8327
8328   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8329   // which may be the result of a CAST.  We use the variable 'Op', which is the
8330   // non-casted variable when we check for possible users.
8331   switch (ArithOp.getOpcode()) {
8332   case ISD::ADD:
8333     // Due to an isel shortcoming, be conservative if this add is likely to be
8334     // selected as part of a load-modify-store instruction. When the root node
8335     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8336     // uses of other nodes in the match, such as the ADD in this case. This
8337     // leads to the ADD being left around and reselected, with the result being
8338     // two adds in the output.  Alas, even if none our users are stores, that
8339     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8340     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8341     // climbing the DAG back to the root, and it doesn't seem to be worth the
8342     // effort.
8343     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8344          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8345       if (UI->getOpcode() != ISD::CopyToReg &&
8346           UI->getOpcode() != ISD::SETCC &&
8347           UI->getOpcode() != ISD::STORE)
8348         goto default_case;
8349
8350     if (ConstantSDNode *C =
8351         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8352       // An add of one will be selected as an INC.
8353       if (C->getAPIntValue() == 1) {
8354         Opcode = X86ISD::INC;
8355         NumOperands = 1;
8356         break;
8357       }
8358
8359       // An add of negative one (subtract of one) will be selected as a DEC.
8360       if (C->getAPIntValue().isAllOnesValue()) {
8361         Opcode = X86ISD::DEC;
8362         NumOperands = 1;
8363         break;
8364       }
8365     }
8366
8367     // Otherwise use a regular EFLAGS-setting add.
8368     Opcode = X86ISD::ADD;
8369     NumOperands = 2;
8370     break;
8371   case ISD::AND: {
8372     // If the primary and result isn't used, don't bother using X86ISD::AND,
8373     // because a TEST instruction will be better.
8374     bool NonFlagUse = false;
8375     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8376            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8377       SDNode *User = *UI;
8378       unsigned UOpNo = UI.getOperandNo();
8379       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8380         // Look pass truncate.
8381         UOpNo = User->use_begin().getOperandNo();
8382         User = *User->use_begin();
8383       }
8384
8385       if (User->getOpcode() != ISD::BRCOND &&
8386           User->getOpcode() != ISD::SETCC &&
8387           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8388         NonFlagUse = true;
8389         break;
8390       }
8391     }
8392
8393     if (!NonFlagUse)
8394       break;
8395   }
8396     // FALL THROUGH
8397   case ISD::SUB:
8398   case ISD::OR:
8399   case ISD::XOR:
8400     // Due to the ISEL shortcoming noted above, be conservative if this op is
8401     // likely to be selected as part of a load-modify-store instruction.
8402     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8403            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8404       if (UI->getOpcode() == ISD::STORE)
8405         goto default_case;
8406
8407     // Otherwise use a regular EFLAGS-setting instruction.
8408     switch (ArithOp.getOpcode()) {
8409     default: llvm_unreachable("unexpected operator!");
8410     case ISD::SUB: Opcode = X86ISD::SUB; break;
8411     case ISD::OR:  Opcode = X86ISD::OR;  break;
8412     case ISD::XOR: Opcode = X86ISD::XOR; break;
8413     case ISD::AND: Opcode = X86ISD::AND; break;
8414     }
8415
8416     NumOperands = 2;
8417     break;
8418   case X86ISD::ADD:
8419   case X86ISD::SUB:
8420   case X86ISD::INC:
8421   case X86ISD::DEC:
8422   case X86ISD::OR:
8423   case X86ISD::XOR:
8424   case X86ISD::AND:
8425     return SDValue(Op.getNode(), 1);
8426   default:
8427   default_case:
8428     break;
8429   }
8430
8431   // If we found that truncation is beneficial, perform the truncation and
8432   // update 'Op'.
8433   if (NeedTruncation) {
8434     EVT VT = Op.getValueType();
8435     SDValue WideVal = Op->getOperand(0);
8436     EVT WideVT = WideVal.getValueType();
8437     unsigned ConvertedOp = 0;
8438     // Use a target machine opcode to prevent further DAGCombine
8439     // optimizations that may separate the arithmetic operations
8440     // from the setcc node.
8441     switch (WideVal.getOpcode()) {
8442       default: break;
8443       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8444       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8445       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8446       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8447       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8448     }
8449
8450     if (ConvertedOp) {
8451       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8452       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8453         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8454         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8455         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8456       }
8457     }
8458   }
8459
8460   if (Opcode == 0)
8461     // Emit a CMP with 0, which is the TEST pattern.
8462     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8463                        DAG.getConstant(0, Op.getValueType()));
8464
8465   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8466   SmallVector<SDValue, 4> Ops;
8467   for (unsigned i = 0; i != NumOperands; ++i)
8468     Ops.push_back(Op.getOperand(i));
8469
8470   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8471   DAG.ReplaceAllUsesWith(Op, New);
8472   return SDValue(New.getNode(), 1);
8473 }
8474
8475 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8476 /// equivalent.
8477 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8478                                    SelectionDAG &DAG) const {
8479   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8480     if (C->getAPIntValue() == 0)
8481       return EmitTest(Op0, X86CC, DAG);
8482
8483   DebugLoc dl = Op0.getDebugLoc();
8484   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8485        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8486     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8487     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8488     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8489                               Op0, Op1);
8490     return SDValue(Sub.getNode(), 1);
8491   }
8492   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8493 }
8494
8495 /// Convert a comparison if required by the subtarget.
8496 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8497                                                  SelectionDAG &DAG) const {
8498   // If the subtarget does not support the FUCOMI instruction, floating-point
8499   // comparisons have to be converted.
8500   if (Subtarget->hasCMov() ||
8501       Cmp.getOpcode() != X86ISD::CMP ||
8502       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8503       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8504     return Cmp;
8505
8506   // The instruction selector will select an FUCOM instruction instead of
8507   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8508   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8509   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8510   DebugLoc dl = Cmp.getDebugLoc();
8511   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8512   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8513   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8514                             DAG.getConstant(8, MVT::i8));
8515   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8516   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8517 }
8518
8519 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8520 /// if it's possible.
8521 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8522                                      DebugLoc dl, SelectionDAG &DAG) const {
8523   SDValue Op0 = And.getOperand(0);
8524   SDValue Op1 = And.getOperand(1);
8525   if (Op0.getOpcode() == ISD::TRUNCATE)
8526     Op0 = Op0.getOperand(0);
8527   if (Op1.getOpcode() == ISD::TRUNCATE)
8528     Op1 = Op1.getOperand(0);
8529
8530   SDValue LHS, RHS;
8531   if (Op1.getOpcode() == ISD::SHL)
8532     std::swap(Op0, Op1);
8533   if (Op0.getOpcode() == ISD::SHL) {
8534     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8535       if (And00C->getZExtValue() == 1) {
8536         // If we looked past a truncate, check that it's only truncating away
8537         // known zeros.
8538         unsigned BitWidth = Op0.getValueSizeInBits();
8539         unsigned AndBitWidth = And.getValueSizeInBits();
8540         if (BitWidth > AndBitWidth) {
8541           APInt Zeros, Ones;
8542           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8543           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8544             return SDValue();
8545         }
8546         LHS = Op1;
8547         RHS = Op0.getOperand(1);
8548       }
8549   } else if (Op1.getOpcode() == ISD::Constant) {
8550     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8551     uint64_t AndRHSVal = AndRHS->getZExtValue();
8552     SDValue AndLHS = Op0;
8553
8554     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8555       LHS = AndLHS.getOperand(0);
8556       RHS = AndLHS.getOperand(1);
8557     }
8558
8559     // Use BT if the immediate can't be encoded in a TEST instruction.
8560     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8561       LHS = AndLHS;
8562       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8563     }
8564   }
8565
8566   if (LHS.getNode()) {
8567     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8568     // instruction.  Since the shift amount is in-range-or-undefined, we know
8569     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8570     // the encoding for the i16 version is larger than the i32 version.
8571     // Also promote i16 to i32 for performance / code size reason.
8572     if (LHS.getValueType() == MVT::i8 ||
8573         LHS.getValueType() == MVT::i16)
8574       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8575
8576     // If the operand types disagree, extend the shift amount to match.  Since
8577     // BT ignores high bits (like shifts) we can use anyextend.
8578     if (LHS.getValueType() != RHS.getValueType())
8579       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8580
8581     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8582     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8583     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8584                        DAG.getConstant(Cond, MVT::i8), BT);
8585   }
8586
8587   return SDValue();
8588 }
8589
8590 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8591
8592   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8593
8594   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8595   SDValue Op0 = Op.getOperand(0);
8596   SDValue Op1 = Op.getOperand(1);
8597   DebugLoc dl = Op.getDebugLoc();
8598   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8599
8600   // Optimize to BT if possible.
8601   // Lower (X & (1 << N)) == 0 to BT(X, N).
8602   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8603   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8604   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8605       Op1.getOpcode() == ISD::Constant &&
8606       cast<ConstantSDNode>(Op1)->isNullValue() &&
8607       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8608     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8609     if (NewSetCC.getNode())
8610       return NewSetCC;
8611   }
8612
8613   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8614   // these.
8615   if (Op1.getOpcode() == ISD::Constant &&
8616       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8617        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8618       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8619
8620     // If the input is a setcc, then reuse the input setcc or use a new one with
8621     // the inverted condition.
8622     if (Op0.getOpcode() == X86ISD::SETCC) {
8623       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8624       bool Invert = (CC == ISD::SETNE) ^
8625         cast<ConstantSDNode>(Op1)->isNullValue();
8626       if (!Invert) return Op0;
8627
8628       CCode = X86::GetOppositeBranchCondition(CCode);
8629       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8630                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8631     }
8632   }
8633
8634   bool isFP = Op1.getValueType().isFloatingPoint();
8635   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8636   if (X86CC == X86::COND_INVALID)
8637     return SDValue();
8638
8639   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8640   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8641   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8642                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8643 }
8644
8645 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8646 // ones, and then concatenate the result back.
8647 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8648   EVT VT = Op.getValueType();
8649
8650   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8651          "Unsupported value type for operation");
8652
8653   unsigned NumElems = VT.getVectorNumElements();
8654   DebugLoc dl = Op.getDebugLoc();
8655   SDValue CC = Op.getOperand(2);
8656
8657   // Extract the LHS vectors
8658   SDValue LHS = Op.getOperand(0);
8659   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8660   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8661
8662   // Extract the RHS vectors
8663   SDValue RHS = Op.getOperand(1);
8664   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8665   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8666
8667   // Issue the operation on the smaller types and concatenate the result back
8668   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8669   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8670   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8671                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8672                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8673 }
8674
8675
8676 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8677   SDValue Cond;
8678   SDValue Op0 = Op.getOperand(0);
8679   SDValue Op1 = Op.getOperand(1);
8680   SDValue CC = Op.getOperand(2);
8681   EVT VT = Op.getValueType();
8682   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8683   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8684   DebugLoc dl = Op.getDebugLoc();
8685
8686   if (isFP) {
8687 #ifndef NDEBUG
8688     EVT EltVT = Op0.getValueType().getVectorElementType();
8689     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8690 #endif
8691
8692     unsigned SSECC;
8693     bool Swap = false;
8694
8695     // SSE Condition code mapping:
8696     //  0 - EQ
8697     //  1 - LT
8698     //  2 - LE
8699     //  3 - UNORD
8700     //  4 - NEQ
8701     //  5 - NLT
8702     //  6 - NLE
8703     //  7 - ORD
8704     switch (SetCCOpcode) {
8705     default: llvm_unreachable("Unexpected SETCC condition");
8706     case ISD::SETOEQ:
8707     case ISD::SETEQ:  SSECC = 0; break;
8708     case ISD::SETOGT:
8709     case ISD::SETGT: Swap = true; // Fallthrough
8710     case ISD::SETLT:
8711     case ISD::SETOLT: SSECC = 1; break;
8712     case ISD::SETOGE:
8713     case ISD::SETGE: Swap = true; // Fallthrough
8714     case ISD::SETLE:
8715     case ISD::SETOLE: SSECC = 2; break;
8716     case ISD::SETUO:  SSECC = 3; break;
8717     case ISD::SETUNE:
8718     case ISD::SETNE:  SSECC = 4; break;
8719     case ISD::SETULE: Swap = true; // Fallthrough
8720     case ISD::SETUGE: SSECC = 5; break;
8721     case ISD::SETULT: Swap = true; // Fallthrough
8722     case ISD::SETUGT: SSECC = 6; break;
8723     case ISD::SETO:   SSECC = 7; break;
8724     case ISD::SETUEQ:
8725     case ISD::SETONE: SSECC = 8; break;
8726     }
8727     if (Swap)
8728       std::swap(Op0, Op1);
8729
8730     // In the two special cases we can't handle, emit two comparisons.
8731     if (SSECC == 8) {
8732       unsigned CC0, CC1;
8733       unsigned CombineOpc;
8734       if (SetCCOpcode == ISD::SETUEQ) {
8735         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8736       } else {
8737         assert(SetCCOpcode == ISD::SETONE);
8738         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8739       }
8740
8741       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8742                                  DAG.getConstant(CC0, MVT::i8));
8743       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8744                                  DAG.getConstant(CC1, MVT::i8));
8745       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8746     }
8747     // Handle all other FP comparisons here.
8748     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8749                        DAG.getConstant(SSECC, MVT::i8));
8750   }
8751
8752   // Break 256-bit integer vector compare into smaller ones.
8753   if (VT.is256BitVector() && !Subtarget->hasAVX2())
8754     return Lower256IntVSETCC(Op, DAG);
8755
8756   // We are handling one of the integer comparisons here.  Since SSE only has
8757   // GT and EQ comparisons for integer, swapping operands and multiple
8758   // operations may be required for some comparisons.
8759   unsigned Opc;
8760   bool Swap = false, Invert = false, FlipSigns = false;
8761
8762   switch (SetCCOpcode) {
8763   default: llvm_unreachable("Unexpected SETCC condition");
8764   case ISD::SETNE:  Invert = true;
8765   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8766   case ISD::SETLT:  Swap = true;
8767   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8768   case ISD::SETGE:  Swap = true;
8769   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8770   case ISD::SETULT: Swap = true;
8771   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8772   case ISD::SETUGE: Swap = true;
8773   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8774   }
8775   if (Swap)
8776     std::swap(Op0, Op1);
8777
8778   // Check that the operation in question is available (most are plain SSE2,
8779   // but PCMPGTQ and PCMPEQQ have different requirements).
8780   if (VT == MVT::v2i64) {
8781     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8782       return SDValue();
8783     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8784       return SDValue();
8785   }
8786
8787   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8788   // bits of the inputs before performing those operations.
8789   if (FlipSigns) {
8790     EVT EltVT = VT.getVectorElementType();
8791     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8792                                       EltVT);
8793     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8794     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8795                                     SignBits.size());
8796     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8797     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8798   }
8799
8800   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8801
8802   // If the logical-not of the result is required, perform that now.
8803   if (Invert)
8804     Result = DAG.getNOT(dl, Result, VT);
8805
8806   return Result;
8807 }
8808
8809 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8810 static bool isX86LogicalCmp(SDValue Op) {
8811   unsigned Opc = Op.getNode()->getOpcode();
8812   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8813       Opc == X86ISD::SAHF)
8814     return true;
8815   if (Op.getResNo() == 1 &&
8816       (Opc == X86ISD::ADD ||
8817        Opc == X86ISD::SUB ||
8818        Opc == X86ISD::ADC ||
8819        Opc == X86ISD::SBB ||
8820        Opc == X86ISD::SMUL ||
8821        Opc == X86ISD::UMUL ||
8822        Opc == X86ISD::INC ||
8823        Opc == X86ISD::DEC ||
8824        Opc == X86ISD::OR ||
8825        Opc == X86ISD::XOR ||
8826        Opc == X86ISD::AND))
8827     return true;
8828
8829   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8830     return true;
8831
8832   return false;
8833 }
8834
8835 static bool isZero(SDValue V) {
8836   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8837   return C && C->isNullValue();
8838 }
8839
8840 static bool isAllOnes(SDValue V) {
8841   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8842   return C && C->isAllOnesValue();
8843 }
8844
8845 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8846   if (V.getOpcode() != ISD::TRUNCATE)
8847     return false;
8848
8849   SDValue VOp0 = V.getOperand(0);
8850   unsigned InBits = VOp0.getValueSizeInBits();
8851   unsigned Bits = V.getValueSizeInBits();
8852   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8853 }
8854
8855 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8856   bool addTest = true;
8857   SDValue Cond  = Op.getOperand(0);
8858   SDValue Op1 = Op.getOperand(1);
8859   SDValue Op2 = Op.getOperand(2);
8860   DebugLoc DL = Op.getDebugLoc();
8861   SDValue CC;
8862
8863   if (Cond.getOpcode() == ISD::SETCC) {
8864     SDValue NewCond = LowerSETCC(Cond, DAG);
8865     if (NewCond.getNode())
8866       Cond = NewCond;
8867   }
8868
8869   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8870   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8871   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8872   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8873   if (Cond.getOpcode() == X86ISD::SETCC &&
8874       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8875       isZero(Cond.getOperand(1).getOperand(1))) {
8876     SDValue Cmp = Cond.getOperand(1);
8877
8878     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8879
8880     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8881         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8882       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8883
8884       SDValue CmpOp0 = Cmp.getOperand(0);
8885       // Apply further optimizations for special cases
8886       // (select (x != 0), -1, 0) -> neg & sbb
8887       // (select (x == 0), 0, -1) -> neg & sbb
8888       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8889         if (YC->isNullValue() &&
8890             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8891           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8892           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8893                                     DAG.getConstant(0, CmpOp0.getValueType()),
8894                                     CmpOp0);
8895           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8896                                     DAG.getConstant(X86::COND_B, MVT::i8),
8897                                     SDValue(Neg.getNode(), 1));
8898           return Res;
8899         }
8900
8901       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8902                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8903       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8904
8905       SDValue Res =   // Res = 0 or -1.
8906         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8907                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8908
8909       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8910         Res = DAG.getNOT(DL, Res, Res.getValueType());
8911
8912       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8913       if (N2C == 0 || !N2C->isNullValue())
8914         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8915       return Res;
8916     }
8917   }
8918
8919   // Look past (and (setcc_carry (cmp ...)), 1).
8920   if (Cond.getOpcode() == ISD::AND &&
8921       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8922     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8923     if (C && C->getAPIntValue() == 1)
8924       Cond = Cond.getOperand(0);
8925   }
8926
8927   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8928   // setting operand in place of the X86ISD::SETCC.
8929   unsigned CondOpcode = Cond.getOpcode();
8930   if (CondOpcode == X86ISD::SETCC ||
8931       CondOpcode == X86ISD::SETCC_CARRY) {
8932     CC = Cond.getOperand(0);
8933
8934     SDValue Cmp = Cond.getOperand(1);
8935     unsigned Opc = Cmp.getOpcode();
8936     EVT VT = Op.getValueType();
8937
8938     bool IllegalFPCMov = false;
8939     if (VT.isFloatingPoint() && !VT.isVector() &&
8940         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8941       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8942
8943     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8944         Opc == X86ISD::BT) { // FIXME
8945       Cond = Cmp;
8946       addTest = false;
8947     }
8948   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8949              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8950              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8951               Cond.getOperand(0).getValueType() != MVT::i8)) {
8952     SDValue LHS = Cond.getOperand(0);
8953     SDValue RHS = Cond.getOperand(1);
8954     unsigned X86Opcode;
8955     unsigned X86Cond;
8956     SDVTList VTs;
8957     switch (CondOpcode) {
8958     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8959     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8960     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8961     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8962     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8963     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8964     default: llvm_unreachable("unexpected overflowing operator");
8965     }
8966     if (CondOpcode == ISD::UMULO)
8967       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8968                           MVT::i32);
8969     else
8970       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8971
8972     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8973
8974     if (CondOpcode == ISD::UMULO)
8975       Cond = X86Op.getValue(2);
8976     else
8977       Cond = X86Op.getValue(1);
8978
8979     CC = DAG.getConstant(X86Cond, MVT::i8);
8980     addTest = false;
8981   }
8982
8983   if (addTest) {
8984     // Look pass the truncate if the high bits are known zero.
8985     if (isTruncWithZeroHighBitsInput(Cond, DAG))
8986         Cond = Cond.getOperand(0);
8987
8988     // We know the result of AND is compared against zero. Try to match
8989     // it to BT.
8990     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8991       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8992       if (NewSetCC.getNode()) {
8993         CC = NewSetCC.getOperand(0);
8994         Cond = NewSetCC.getOperand(1);
8995         addTest = false;
8996       }
8997     }
8998   }
8999
9000   if (addTest) {
9001     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9002     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9003   }
9004
9005   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9006   // a <  b ?  0 : -1 -> RES = setcc_carry
9007   // a >= b ? -1 :  0 -> RES = setcc_carry
9008   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9009   if (Cond.getOpcode() == X86ISD::SUB) {
9010     Cond = ConvertCmpIfNecessary(Cond, DAG);
9011     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9012
9013     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9014         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9015       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9016                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9017       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9018         return DAG.getNOT(DL, Res, Res.getValueType());
9019       return Res;
9020     }
9021   }
9022
9023   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9024   // condition is true.
9025   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9026   SDValue Ops[] = { Op2, Op1, CC, Cond };
9027   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9028 }
9029
9030 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9031 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9032 // from the AND / OR.
9033 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9034   Opc = Op.getOpcode();
9035   if (Opc != ISD::OR && Opc != ISD::AND)
9036     return false;
9037   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9038           Op.getOperand(0).hasOneUse() &&
9039           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9040           Op.getOperand(1).hasOneUse());
9041 }
9042
9043 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9044 // 1 and that the SETCC node has a single use.
9045 static bool isXor1OfSetCC(SDValue Op) {
9046   if (Op.getOpcode() != ISD::XOR)
9047     return false;
9048   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9049   if (N1C && N1C->getAPIntValue() == 1) {
9050     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9051       Op.getOperand(0).hasOneUse();
9052   }
9053   return false;
9054 }
9055
9056 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9057   bool addTest = true;
9058   SDValue Chain = Op.getOperand(0);
9059   SDValue Cond  = Op.getOperand(1);
9060   SDValue Dest  = Op.getOperand(2);
9061   DebugLoc dl = Op.getDebugLoc();
9062   SDValue CC;
9063   bool Inverted = false;
9064
9065   if (Cond.getOpcode() == ISD::SETCC) {
9066     // Check for setcc([su]{add,sub,mul}o == 0).
9067     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9068         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9069         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9070         Cond.getOperand(0).getResNo() == 1 &&
9071         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9072          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9073          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9074          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9075          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9076          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9077       Inverted = true;
9078       Cond = Cond.getOperand(0);
9079     } else {
9080       SDValue NewCond = LowerSETCC(Cond, DAG);
9081       if (NewCond.getNode())
9082         Cond = NewCond;
9083     }
9084   }
9085 #if 0
9086   // FIXME: LowerXALUO doesn't handle these!!
9087   else if (Cond.getOpcode() == X86ISD::ADD  ||
9088            Cond.getOpcode() == X86ISD::SUB  ||
9089            Cond.getOpcode() == X86ISD::SMUL ||
9090            Cond.getOpcode() == X86ISD::UMUL)
9091     Cond = LowerXALUO(Cond, DAG);
9092 #endif
9093
9094   // Look pass (and (setcc_carry (cmp ...)), 1).
9095   if (Cond.getOpcode() == ISD::AND &&
9096       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9097     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9098     if (C && C->getAPIntValue() == 1)
9099       Cond = Cond.getOperand(0);
9100   }
9101
9102   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9103   // setting operand in place of the X86ISD::SETCC.
9104   unsigned CondOpcode = Cond.getOpcode();
9105   if (CondOpcode == X86ISD::SETCC ||
9106       CondOpcode == X86ISD::SETCC_CARRY) {
9107     CC = Cond.getOperand(0);
9108
9109     SDValue Cmp = Cond.getOperand(1);
9110     unsigned Opc = Cmp.getOpcode();
9111     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9112     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9113       Cond = Cmp;
9114       addTest = false;
9115     } else {
9116       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9117       default: break;
9118       case X86::COND_O:
9119       case X86::COND_B:
9120         // These can only come from an arithmetic instruction with overflow,
9121         // e.g. SADDO, UADDO.
9122         Cond = Cond.getNode()->getOperand(1);
9123         addTest = false;
9124         break;
9125       }
9126     }
9127   }
9128   CondOpcode = Cond.getOpcode();
9129   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9130       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9131       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9132        Cond.getOperand(0).getValueType() != MVT::i8)) {
9133     SDValue LHS = Cond.getOperand(0);
9134     SDValue RHS = Cond.getOperand(1);
9135     unsigned X86Opcode;
9136     unsigned X86Cond;
9137     SDVTList VTs;
9138     switch (CondOpcode) {
9139     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9140     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9141     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9142     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9143     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9144     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9145     default: llvm_unreachable("unexpected overflowing operator");
9146     }
9147     if (Inverted)
9148       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9149     if (CondOpcode == ISD::UMULO)
9150       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9151                           MVT::i32);
9152     else
9153       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9154
9155     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9156
9157     if (CondOpcode == ISD::UMULO)
9158       Cond = X86Op.getValue(2);
9159     else
9160       Cond = X86Op.getValue(1);
9161
9162     CC = DAG.getConstant(X86Cond, MVT::i8);
9163     addTest = false;
9164   } else {
9165     unsigned CondOpc;
9166     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9167       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9168       if (CondOpc == ISD::OR) {
9169         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9170         // two branches instead of an explicit OR instruction with a
9171         // separate test.
9172         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9173             isX86LogicalCmp(Cmp)) {
9174           CC = Cond.getOperand(0).getOperand(0);
9175           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9176                               Chain, Dest, CC, Cmp);
9177           CC = Cond.getOperand(1).getOperand(0);
9178           Cond = Cmp;
9179           addTest = false;
9180         }
9181       } else { // ISD::AND
9182         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9183         // two branches instead of an explicit AND instruction with a
9184         // separate test. However, we only do this if this block doesn't
9185         // have a fall-through edge, because this requires an explicit
9186         // jmp when the condition is false.
9187         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9188             isX86LogicalCmp(Cmp) &&
9189             Op.getNode()->hasOneUse()) {
9190           X86::CondCode CCode =
9191             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9192           CCode = X86::GetOppositeBranchCondition(CCode);
9193           CC = DAG.getConstant(CCode, MVT::i8);
9194           SDNode *User = *Op.getNode()->use_begin();
9195           // Look for an unconditional branch following this conditional branch.
9196           // We need this because we need to reverse the successors in order
9197           // to implement FCMP_OEQ.
9198           if (User->getOpcode() == ISD::BR) {
9199             SDValue FalseBB = User->getOperand(1);
9200             SDNode *NewBR =
9201               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9202             assert(NewBR == User);
9203             (void)NewBR;
9204             Dest = FalseBB;
9205
9206             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9207                                 Chain, Dest, CC, Cmp);
9208             X86::CondCode CCode =
9209               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9210             CCode = X86::GetOppositeBranchCondition(CCode);
9211             CC = DAG.getConstant(CCode, MVT::i8);
9212             Cond = Cmp;
9213             addTest = false;
9214           }
9215         }
9216       }
9217     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9218       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9219       // It should be transformed during dag combiner except when the condition
9220       // is set by a arithmetics with overflow node.
9221       X86::CondCode CCode =
9222         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9223       CCode = X86::GetOppositeBranchCondition(CCode);
9224       CC = DAG.getConstant(CCode, MVT::i8);
9225       Cond = Cond.getOperand(0).getOperand(1);
9226       addTest = false;
9227     } else if (Cond.getOpcode() == ISD::SETCC &&
9228                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9229       // For FCMP_OEQ, we can emit
9230       // two branches instead of an explicit AND instruction with a
9231       // separate test. However, we only do this if this block doesn't
9232       // have a fall-through edge, because this requires an explicit
9233       // jmp when the condition is false.
9234       if (Op.getNode()->hasOneUse()) {
9235         SDNode *User = *Op.getNode()->use_begin();
9236         // Look for an unconditional branch following this conditional branch.
9237         // We need this because we need to reverse the successors in order
9238         // to implement FCMP_OEQ.
9239         if (User->getOpcode() == ISD::BR) {
9240           SDValue FalseBB = User->getOperand(1);
9241           SDNode *NewBR =
9242             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9243           assert(NewBR == User);
9244           (void)NewBR;
9245           Dest = FalseBB;
9246
9247           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9248                                     Cond.getOperand(0), Cond.getOperand(1));
9249           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9250           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9251           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9252                               Chain, Dest, CC, Cmp);
9253           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9254           Cond = Cmp;
9255           addTest = false;
9256         }
9257       }
9258     } else if (Cond.getOpcode() == ISD::SETCC &&
9259                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9260       // For FCMP_UNE, we can emit
9261       // two branches instead of an explicit AND instruction with a
9262       // separate test. However, we only do this if this block doesn't
9263       // have a fall-through edge, because this requires an explicit
9264       // jmp when the condition is false.
9265       if (Op.getNode()->hasOneUse()) {
9266         SDNode *User = *Op.getNode()->use_begin();
9267         // Look for an unconditional branch following this conditional branch.
9268         // We need this because we need to reverse the successors in order
9269         // to implement FCMP_UNE.
9270         if (User->getOpcode() == ISD::BR) {
9271           SDValue FalseBB = User->getOperand(1);
9272           SDNode *NewBR =
9273             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9274           assert(NewBR == User);
9275           (void)NewBR;
9276
9277           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9278                                     Cond.getOperand(0), Cond.getOperand(1));
9279           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9280           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9281           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9282                               Chain, Dest, CC, Cmp);
9283           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9284           Cond = Cmp;
9285           addTest = false;
9286           Dest = FalseBB;
9287         }
9288       }
9289     }
9290   }
9291
9292   if (addTest) {
9293     // Look pass the truncate if the high bits are known zero.
9294     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9295         Cond = Cond.getOperand(0);
9296
9297     // We know the result of AND is compared against zero. Try to match
9298     // it to BT.
9299     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9300       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9301       if (NewSetCC.getNode()) {
9302         CC = NewSetCC.getOperand(0);
9303         Cond = NewSetCC.getOperand(1);
9304         addTest = false;
9305       }
9306     }
9307   }
9308
9309   if (addTest) {
9310     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9311     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9312   }
9313   Cond = ConvertCmpIfNecessary(Cond, DAG);
9314   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9315                      Chain, Dest, CC, Cond);
9316 }
9317
9318
9319 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9320 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9321 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9322 // that the guard pages used by the OS virtual memory manager are allocated in
9323 // correct sequence.
9324 SDValue
9325 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9326                                            SelectionDAG &DAG) const {
9327   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9328           getTargetMachine().Options.EnableSegmentedStacks) &&
9329          "This should be used only on Windows targets or when segmented stacks "
9330          "are being used");
9331   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9332   DebugLoc dl = Op.getDebugLoc();
9333
9334   // Get the inputs.
9335   SDValue Chain = Op.getOperand(0);
9336   SDValue Size  = Op.getOperand(1);
9337   // FIXME: Ensure alignment here
9338
9339   bool Is64Bit = Subtarget->is64Bit();
9340   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9341
9342   if (getTargetMachine().Options.EnableSegmentedStacks) {
9343     MachineFunction &MF = DAG.getMachineFunction();
9344     MachineRegisterInfo &MRI = MF.getRegInfo();
9345
9346     if (Is64Bit) {
9347       // The 64 bit implementation of segmented stacks needs to clobber both r10
9348       // r11. This makes it impossible to use it along with nested parameters.
9349       const Function *F = MF.getFunction();
9350
9351       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9352            I != E; ++I)
9353         if (I->hasNestAttr())
9354           report_fatal_error("Cannot use segmented stacks with functions that "
9355                              "have nested arguments.");
9356     }
9357
9358     const TargetRegisterClass *AddrRegClass =
9359       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9360     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9361     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9362     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9363                                 DAG.getRegister(Vreg, SPTy));
9364     SDValue Ops1[2] = { Value, Chain };
9365     return DAG.getMergeValues(Ops1, 2, dl);
9366   } else {
9367     SDValue Flag;
9368     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9369
9370     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9371     Flag = Chain.getValue(1);
9372     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9373
9374     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9375     Flag = Chain.getValue(1);
9376
9377     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9378
9379     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9380     return DAG.getMergeValues(Ops1, 2, dl);
9381   }
9382 }
9383
9384 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9385   MachineFunction &MF = DAG.getMachineFunction();
9386   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9387
9388   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9389   DebugLoc DL = Op.getDebugLoc();
9390
9391   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9392     // vastart just stores the address of the VarArgsFrameIndex slot into the
9393     // memory location argument.
9394     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9395                                    getPointerTy());
9396     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9397                         MachinePointerInfo(SV), false, false, 0);
9398   }
9399
9400   // __va_list_tag:
9401   //   gp_offset         (0 - 6 * 8)
9402   //   fp_offset         (48 - 48 + 8 * 16)
9403   //   overflow_arg_area (point to parameters coming in memory).
9404   //   reg_save_area
9405   SmallVector<SDValue, 8> MemOps;
9406   SDValue FIN = Op.getOperand(1);
9407   // Store gp_offset
9408   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9409                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9410                                                MVT::i32),
9411                                FIN, MachinePointerInfo(SV), false, false, 0);
9412   MemOps.push_back(Store);
9413
9414   // Store fp_offset
9415   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9416                     FIN, DAG.getIntPtrConstant(4));
9417   Store = DAG.getStore(Op.getOperand(0), DL,
9418                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9419                                        MVT::i32),
9420                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9421   MemOps.push_back(Store);
9422
9423   // Store ptr to overflow_arg_area
9424   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9425                     FIN, DAG.getIntPtrConstant(4));
9426   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9427                                     getPointerTy());
9428   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9429                        MachinePointerInfo(SV, 8),
9430                        false, false, 0);
9431   MemOps.push_back(Store);
9432
9433   // Store ptr to reg_save_area.
9434   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9435                     FIN, DAG.getIntPtrConstant(8));
9436   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9437                                     getPointerTy());
9438   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9439                        MachinePointerInfo(SV, 16), false, false, 0);
9440   MemOps.push_back(Store);
9441   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9442                      &MemOps[0], MemOps.size());
9443 }
9444
9445 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9446   assert(Subtarget->is64Bit() &&
9447          "LowerVAARG only handles 64-bit va_arg!");
9448   assert((Subtarget->isTargetLinux() ||
9449           Subtarget->isTargetDarwin()) &&
9450           "Unhandled target in LowerVAARG");
9451   assert(Op.getNode()->getNumOperands() == 4);
9452   SDValue Chain = Op.getOperand(0);
9453   SDValue SrcPtr = Op.getOperand(1);
9454   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9455   unsigned Align = Op.getConstantOperandVal(3);
9456   DebugLoc dl = Op.getDebugLoc();
9457
9458   EVT ArgVT = Op.getNode()->getValueType(0);
9459   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9460   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9461   uint8_t ArgMode;
9462
9463   // Decide which area this value should be read from.
9464   // TODO: Implement the AMD64 ABI in its entirety. This simple
9465   // selection mechanism works only for the basic types.
9466   if (ArgVT == MVT::f80) {
9467     llvm_unreachable("va_arg for f80 not yet implemented");
9468   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9469     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9470   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9471     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9472   } else {
9473     llvm_unreachable("Unhandled argument type in LowerVAARG");
9474   }
9475
9476   if (ArgMode == 2) {
9477     // Sanity Check: Make sure using fp_offset makes sense.
9478     assert(!getTargetMachine().Options.UseSoftFloat &&
9479            !(DAG.getMachineFunction()
9480                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9481            Subtarget->hasSSE1());
9482   }
9483
9484   // Insert VAARG_64 node into the DAG
9485   // VAARG_64 returns two values: Variable Argument Address, Chain
9486   SmallVector<SDValue, 11> InstOps;
9487   InstOps.push_back(Chain);
9488   InstOps.push_back(SrcPtr);
9489   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9490   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9491   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9492   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9493   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9494                                           VTs, &InstOps[0], InstOps.size(),
9495                                           MVT::i64,
9496                                           MachinePointerInfo(SV),
9497                                           /*Align=*/0,
9498                                           /*Volatile=*/false,
9499                                           /*ReadMem=*/true,
9500                                           /*WriteMem=*/true);
9501   Chain = VAARG.getValue(1);
9502
9503   // Load the next argument and return it
9504   return DAG.getLoad(ArgVT, dl,
9505                      Chain,
9506                      VAARG,
9507                      MachinePointerInfo(),
9508                      false, false, false, 0);
9509 }
9510
9511 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9512   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9513   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9514   SDValue Chain = Op.getOperand(0);
9515   SDValue DstPtr = Op.getOperand(1);
9516   SDValue SrcPtr = Op.getOperand(2);
9517   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9518   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9519   DebugLoc DL = Op.getDebugLoc();
9520
9521   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9522                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9523                        false,
9524                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9525 }
9526
9527 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9528 // may or may not be a constant. Takes immediate version of shift as input.
9529 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9530                                    SDValue SrcOp, SDValue ShAmt,
9531                                    SelectionDAG &DAG) {
9532   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9533
9534   if (isa<ConstantSDNode>(ShAmt)) {
9535     // Constant may be a TargetConstant. Use a regular constant.
9536     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9537     switch (Opc) {
9538       default: llvm_unreachable("Unknown target vector shift node");
9539       case X86ISD::VSHLI:
9540       case X86ISD::VSRLI:
9541       case X86ISD::VSRAI:
9542         return DAG.getNode(Opc, dl, VT, SrcOp,
9543                            DAG.getConstant(ShiftAmt, MVT::i32));
9544     }
9545   }
9546
9547   // Change opcode to non-immediate version
9548   switch (Opc) {
9549     default: llvm_unreachable("Unknown target vector shift node");
9550     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9551     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9552     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9553   }
9554
9555   // Need to build a vector containing shift amount
9556   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9557   SDValue ShOps[4];
9558   ShOps[0] = ShAmt;
9559   ShOps[1] = DAG.getConstant(0, MVT::i32);
9560   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9561   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9562
9563   // The return type has to be a 128-bit type with the same element
9564   // type as the input type.
9565   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9566   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9567
9568   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9569   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9570 }
9571
9572 SDValue
9573 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9574   DebugLoc dl = Op.getDebugLoc();
9575   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9576   switch (IntNo) {
9577   default: return SDValue();    // Don't custom lower most intrinsics.
9578   // Comparison intrinsics.
9579   case Intrinsic::x86_sse_comieq_ss:
9580   case Intrinsic::x86_sse_comilt_ss:
9581   case Intrinsic::x86_sse_comile_ss:
9582   case Intrinsic::x86_sse_comigt_ss:
9583   case Intrinsic::x86_sse_comige_ss:
9584   case Intrinsic::x86_sse_comineq_ss:
9585   case Intrinsic::x86_sse_ucomieq_ss:
9586   case Intrinsic::x86_sse_ucomilt_ss:
9587   case Intrinsic::x86_sse_ucomile_ss:
9588   case Intrinsic::x86_sse_ucomigt_ss:
9589   case Intrinsic::x86_sse_ucomige_ss:
9590   case Intrinsic::x86_sse_ucomineq_ss:
9591   case Intrinsic::x86_sse2_comieq_sd:
9592   case Intrinsic::x86_sse2_comilt_sd:
9593   case Intrinsic::x86_sse2_comile_sd:
9594   case Intrinsic::x86_sse2_comigt_sd:
9595   case Intrinsic::x86_sse2_comige_sd:
9596   case Intrinsic::x86_sse2_comineq_sd:
9597   case Intrinsic::x86_sse2_ucomieq_sd:
9598   case Intrinsic::x86_sse2_ucomilt_sd:
9599   case Intrinsic::x86_sse2_ucomile_sd:
9600   case Intrinsic::x86_sse2_ucomigt_sd:
9601   case Intrinsic::x86_sse2_ucomige_sd:
9602   case Intrinsic::x86_sse2_ucomineq_sd: {
9603     unsigned Opc;
9604     ISD::CondCode CC;
9605     switch (IntNo) {
9606     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9607     case Intrinsic::x86_sse_comieq_ss:
9608     case Intrinsic::x86_sse2_comieq_sd:
9609       Opc = X86ISD::COMI;
9610       CC = ISD::SETEQ;
9611       break;
9612     case Intrinsic::x86_sse_comilt_ss:
9613     case Intrinsic::x86_sse2_comilt_sd:
9614       Opc = X86ISD::COMI;
9615       CC = ISD::SETLT;
9616       break;
9617     case Intrinsic::x86_sse_comile_ss:
9618     case Intrinsic::x86_sse2_comile_sd:
9619       Opc = X86ISD::COMI;
9620       CC = ISD::SETLE;
9621       break;
9622     case Intrinsic::x86_sse_comigt_ss:
9623     case Intrinsic::x86_sse2_comigt_sd:
9624       Opc = X86ISD::COMI;
9625       CC = ISD::SETGT;
9626       break;
9627     case Intrinsic::x86_sse_comige_ss:
9628     case Intrinsic::x86_sse2_comige_sd:
9629       Opc = X86ISD::COMI;
9630       CC = ISD::SETGE;
9631       break;
9632     case Intrinsic::x86_sse_comineq_ss:
9633     case Intrinsic::x86_sse2_comineq_sd:
9634       Opc = X86ISD::COMI;
9635       CC = ISD::SETNE;
9636       break;
9637     case Intrinsic::x86_sse_ucomieq_ss:
9638     case Intrinsic::x86_sse2_ucomieq_sd:
9639       Opc = X86ISD::UCOMI;
9640       CC = ISD::SETEQ;
9641       break;
9642     case Intrinsic::x86_sse_ucomilt_ss:
9643     case Intrinsic::x86_sse2_ucomilt_sd:
9644       Opc = X86ISD::UCOMI;
9645       CC = ISD::SETLT;
9646       break;
9647     case Intrinsic::x86_sse_ucomile_ss:
9648     case Intrinsic::x86_sse2_ucomile_sd:
9649       Opc = X86ISD::UCOMI;
9650       CC = ISD::SETLE;
9651       break;
9652     case Intrinsic::x86_sse_ucomigt_ss:
9653     case Intrinsic::x86_sse2_ucomigt_sd:
9654       Opc = X86ISD::UCOMI;
9655       CC = ISD::SETGT;
9656       break;
9657     case Intrinsic::x86_sse_ucomige_ss:
9658     case Intrinsic::x86_sse2_ucomige_sd:
9659       Opc = X86ISD::UCOMI;
9660       CC = ISD::SETGE;
9661       break;
9662     case Intrinsic::x86_sse_ucomineq_ss:
9663     case Intrinsic::x86_sse2_ucomineq_sd:
9664       Opc = X86ISD::UCOMI;
9665       CC = ISD::SETNE;
9666       break;
9667     }
9668
9669     SDValue LHS = Op.getOperand(1);
9670     SDValue RHS = Op.getOperand(2);
9671     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9672     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9673     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9674     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9675                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9676     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9677   }
9678
9679   // Arithmetic intrinsics.
9680   case Intrinsic::x86_sse2_pmulu_dq:
9681   case Intrinsic::x86_avx2_pmulu_dq:
9682     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9683                        Op.getOperand(1), Op.getOperand(2));
9684
9685   // SSE3/AVX horizontal add/sub intrinsics
9686   case Intrinsic::x86_sse3_hadd_ps:
9687   case Intrinsic::x86_sse3_hadd_pd:
9688   case Intrinsic::x86_avx_hadd_ps_256:
9689   case Intrinsic::x86_avx_hadd_pd_256:
9690   case Intrinsic::x86_sse3_hsub_ps:
9691   case Intrinsic::x86_sse3_hsub_pd:
9692   case Intrinsic::x86_avx_hsub_ps_256:
9693   case Intrinsic::x86_avx_hsub_pd_256:
9694   case Intrinsic::x86_ssse3_phadd_w_128:
9695   case Intrinsic::x86_ssse3_phadd_d_128:
9696   case Intrinsic::x86_avx2_phadd_w:
9697   case Intrinsic::x86_avx2_phadd_d:
9698   case Intrinsic::x86_ssse3_phsub_w_128:
9699   case Intrinsic::x86_ssse3_phsub_d_128:
9700   case Intrinsic::x86_avx2_phsub_w:
9701   case Intrinsic::x86_avx2_phsub_d: {
9702     unsigned Opcode;
9703     switch (IntNo) {
9704     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9705     case Intrinsic::x86_sse3_hadd_ps:
9706     case Intrinsic::x86_sse3_hadd_pd:
9707     case Intrinsic::x86_avx_hadd_ps_256:
9708     case Intrinsic::x86_avx_hadd_pd_256:
9709       Opcode = X86ISD::FHADD;
9710       break;
9711     case Intrinsic::x86_sse3_hsub_ps:
9712     case Intrinsic::x86_sse3_hsub_pd:
9713     case Intrinsic::x86_avx_hsub_ps_256:
9714     case Intrinsic::x86_avx_hsub_pd_256:
9715       Opcode = X86ISD::FHSUB;
9716       break;
9717     case Intrinsic::x86_ssse3_phadd_w_128:
9718     case Intrinsic::x86_ssse3_phadd_d_128:
9719     case Intrinsic::x86_avx2_phadd_w:
9720     case Intrinsic::x86_avx2_phadd_d:
9721       Opcode = X86ISD::HADD;
9722       break;
9723     case Intrinsic::x86_ssse3_phsub_w_128:
9724     case Intrinsic::x86_ssse3_phsub_d_128:
9725     case Intrinsic::x86_avx2_phsub_w:
9726     case Intrinsic::x86_avx2_phsub_d:
9727       Opcode = X86ISD::HSUB;
9728       break;
9729     }
9730     return DAG.getNode(Opcode, dl, Op.getValueType(),
9731                        Op.getOperand(1), Op.getOperand(2));
9732   }
9733
9734   // AVX2 variable shift intrinsics
9735   case Intrinsic::x86_avx2_psllv_d:
9736   case Intrinsic::x86_avx2_psllv_q:
9737   case Intrinsic::x86_avx2_psllv_d_256:
9738   case Intrinsic::x86_avx2_psllv_q_256:
9739   case Intrinsic::x86_avx2_psrlv_d:
9740   case Intrinsic::x86_avx2_psrlv_q:
9741   case Intrinsic::x86_avx2_psrlv_d_256:
9742   case Intrinsic::x86_avx2_psrlv_q_256:
9743   case Intrinsic::x86_avx2_psrav_d:
9744   case Intrinsic::x86_avx2_psrav_d_256: {
9745     unsigned Opcode;
9746     switch (IntNo) {
9747     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9748     case Intrinsic::x86_avx2_psllv_d:
9749     case Intrinsic::x86_avx2_psllv_q:
9750     case Intrinsic::x86_avx2_psllv_d_256:
9751     case Intrinsic::x86_avx2_psllv_q_256:
9752       Opcode = ISD::SHL;
9753       break;
9754     case Intrinsic::x86_avx2_psrlv_d:
9755     case Intrinsic::x86_avx2_psrlv_q:
9756     case Intrinsic::x86_avx2_psrlv_d_256:
9757     case Intrinsic::x86_avx2_psrlv_q_256:
9758       Opcode = ISD::SRL;
9759       break;
9760     case Intrinsic::x86_avx2_psrav_d:
9761     case Intrinsic::x86_avx2_psrav_d_256:
9762       Opcode = ISD::SRA;
9763       break;
9764     }
9765     return DAG.getNode(Opcode, dl, Op.getValueType(),
9766                        Op.getOperand(1), Op.getOperand(2));
9767   }
9768
9769   case Intrinsic::x86_ssse3_pshuf_b_128:
9770   case Intrinsic::x86_avx2_pshuf_b:
9771     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9772                        Op.getOperand(1), Op.getOperand(2));
9773
9774   case Intrinsic::x86_ssse3_psign_b_128:
9775   case Intrinsic::x86_ssse3_psign_w_128:
9776   case Intrinsic::x86_ssse3_psign_d_128:
9777   case Intrinsic::x86_avx2_psign_b:
9778   case Intrinsic::x86_avx2_psign_w:
9779   case Intrinsic::x86_avx2_psign_d:
9780     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9781                        Op.getOperand(1), Op.getOperand(2));
9782
9783   case Intrinsic::x86_sse41_insertps:
9784     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9785                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9786
9787   case Intrinsic::x86_avx_vperm2f128_ps_256:
9788   case Intrinsic::x86_avx_vperm2f128_pd_256:
9789   case Intrinsic::x86_avx_vperm2f128_si_256:
9790   case Intrinsic::x86_avx2_vperm2i128:
9791     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9792                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9793
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;
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   case Intrinsic::x86_sse2_psrl_w:
9875   case Intrinsic::x86_sse2_psrl_d:
9876   case Intrinsic::x86_sse2_psrl_q:
9877   case Intrinsic::x86_avx2_psrl_w:
9878   case Intrinsic::x86_avx2_psrl_d:
9879   case Intrinsic::x86_avx2_psrl_q:
9880   case Intrinsic::x86_sse2_psra_w:
9881   case Intrinsic::x86_sse2_psra_d:
9882   case Intrinsic::x86_avx2_psra_w:
9883   case Intrinsic::x86_avx2_psra_d: {
9884     unsigned Opcode;
9885     switch (IntNo) {
9886     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9887     case Intrinsic::x86_sse2_psll_w:
9888     case Intrinsic::x86_sse2_psll_d:
9889     case Intrinsic::x86_sse2_psll_q:
9890     case Intrinsic::x86_avx2_psll_w:
9891     case Intrinsic::x86_avx2_psll_d:
9892     case Intrinsic::x86_avx2_psll_q:
9893       Opcode = X86ISD::VSHL;
9894       break;
9895     case Intrinsic::x86_sse2_psrl_w:
9896     case Intrinsic::x86_sse2_psrl_d:
9897     case Intrinsic::x86_sse2_psrl_q:
9898     case Intrinsic::x86_avx2_psrl_w:
9899     case Intrinsic::x86_avx2_psrl_d:
9900     case Intrinsic::x86_avx2_psrl_q:
9901       Opcode = X86ISD::VSRL;
9902       break;
9903     case Intrinsic::x86_sse2_psra_w:
9904     case Intrinsic::x86_sse2_psra_d:
9905     case Intrinsic::x86_avx2_psra_w:
9906     case Intrinsic::x86_avx2_psra_d:
9907       Opcode = X86ISD::VSRA;
9908       break;
9909     }
9910     return DAG.getNode(Opcode, dl, Op.getValueType(),
9911                        Op.getOperand(1), Op.getOperand(2));
9912   }
9913
9914   // SSE/AVX immediate shift intrinsics
9915   case Intrinsic::x86_sse2_pslli_w:
9916   case Intrinsic::x86_sse2_pslli_d:
9917   case Intrinsic::x86_sse2_pslli_q:
9918   case Intrinsic::x86_avx2_pslli_w:
9919   case Intrinsic::x86_avx2_pslli_d:
9920   case Intrinsic::x86_avx2_pslli_q:
9921   case Intrinsic::x86_sse2_psrli_w:
9922   case Intrinsic::x86_sse2_psrli_d:
9923   case Intrinsic::x86_sse2_psrli_q:
9924   case Intrinsic::x86_avx2_psrli_w:
9925   case Intrinsic::x86_avx2_psrli_d:
9926   case Intrinsic::x86_avx2_psrli_q:
9927   case Intrinsic::x86_sse2_psrai_w:
9928   case Intrinsic::x86_sse2_psrai_d:
9929   case Intrinsic::x86_avx2_psrai_w:
9930   case Intrinsic::x86_avx2_psrai_d: {
9931     unsigned Opcode;
9932     switch (IntNo) {
9933     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9934     case Intrinsic::x86_sse2_pslli_w:
9935     case Intrinsic::x86_sse2_pslli_d:
9936     case Intrinsic::x86_sse2_pslli_q:
9937     case Intrinsic::x86_avx2_pslli_w:
9938     case Intrinsic::x86_avx2_pslli_d:
9939     case Intrinsic::x86_avx2_pslli_q:
9940       Opcode = X86ISD::VSHLI;
9941       break;
9942     case Intrinsic::x86_sse2_psrli_w:
9943     case Intrinsic::x86_sse2_psrli_d:
9944     case Intrinsic::x86_sse2_psrli_q:
9945     case Intrinsic::x86_avx2_psrli_w:
9946     case Intrinsic::x86_avx2_psrli_d:
9947     case Intrinsic::x86_avx2_psrli_q:
9948       Opcode = X86ISD::VSRLI;
9949       break;
9950     case Intrinsic::x86_sse2_psrai_w:
9951     case Intrinsic::x86_sse2_psrai_d:
9952     case Intrinsic::x86_avx2_psrai_w:
9953     case Intrinsic::x86_avx2_psrai_d:
9954       Opcode = X86ISD::VSRAI;
9955       break;
9956     }
9957     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
9958                                Op.getOperand(1), Op.getOperand(2), DAG);
9959   }
9960
9961   case Intrinsic::x86_sse42_pcmpistria128:
9962   case Intrinsic::x86_sse42_pcmpestria128:
9963   case Intrinsic::x86_sse42_pcmpistric128:
9964   case Intrinsic::x86_sse42_pcmpestric128:
9965   case Intrinsic::x86_sse42_pcmpistrio128:
9966   case Intrinsic::x86_sse42_pcmpestrio128:
9967   case Intrinsic::x86_sse42_pcmpistris128:
9968   case Intrinsic::x86_sse42_pcmpestris128:
9969   case Intrinsic::x86_sse42_pcmpistriz128:
9970   case Intrinsic::x86_sse42_pcmpestriz128: {
9971     unsigned Opcode;
9972     unsigned X86CC;
9973     switch (IntNo) {
9974     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9975     case Intrinsic::x86_sse42_pcmpistria128:
9976       Opcode = X86ISD::PCMPISTRI;
9977       X86CC = X86::COND_A;
9978       break;
9979     case Intrinsic::x86_sse42_pcmpestria128:
9980       Opcode = X86ISD::PCMPESTRI;
9981       X86CC = X86::COND_A;
9982       break;
9983     case Intrinsic::x86_sse42_pcmpistric128:
9984       Opcode = X86ISD::PCMPISTRI;
9985       X86CC = X86::COND_B;
9986       break;
9987     case Intrinsic::x86_sse42_pcmpestric128:
9988       Opcode = X86ISD::PCMPESTRI;
9989       X86CC = X86::COND_B;
9990       break;
9991     case Intrinsic::x86_sse42_pcmpistrio128:
9992       Opcode = X86ISD::PCMPISTRI;
9993       X86CC = X86::COND_O;
9994       break;
9995     case Intrinsic::x86_sse42_pcmpestrio128:
9996       Opcode = X86ISD::PCMPESTRI;
9997       X86CC = X86::COND_O;
9998       break;
9999     case Intrinsic::x86_sse42_pcmpistris128:
10000       Opcode = X86ISD::PCMPISTRI;
10001       X86CC = X86::COND_S;
10002       break;
10003     case Intrinsic::x86_sse42_pcmpestris128:
10004       Opcode = X86ISD::PCMPESTRI;
10005       X86CC = X86::COND_S;
10006       break;
10007     case Intrinsic::x86_sse42_pcmpistriz128:
10008       Opcode = X86ISD::PCMPISTRI;
10009       X86CC = X86::COND_E;
10010       break;
10011     case Intrinsic::x86_sse42_pcmpestriz128:
10012       Opcode = X86ISD::PCMPESTRI;
10013       X86CC = X86::COND_E;
10014       break;
10015     }
10016     SmallVector<SDValue, 5> NewOps;
10017     NewOps.append(Op->op_begin()+1, Op->op_end());
10018     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10019     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10020     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10021                                 DAG.getConstant(X86CC, MVT::i8),
10022                                 SDValue(PCMP.getNode(), 1));
10023     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10024   }
10025
10026   case Intrinsic::x86_sse42_pcmpistri128:
10027   case Intrinsic::x86_sse42_pcmpestri128: {
10028     unsigned Opcode;
10029     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10030       Opcode = X86ISD::PCMPISTRI;
10031     else
10032       Opcode = X86ISD::PCMPESTRI;
10033
10034     SmallVector<SDValue, 5> NewOps;
10035     NewOps.append(Op->op_begin()+1, Op->op_end());
10036     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10037     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10038   }
10039   case Intrinsic::x86_fma_vfmadd_ps:
10040   case Intrinsic::x86_fma_vfmadd_pd:
10041   case Intrinsic::x86_fma_vfmsub_ps:
10042   case Intrinsic::x86_fma_vfmsub_pd:
10043   case Intrinsic::x86_fma_vfnmadd_ps:
10044   case Intrinsic::x86_fma_vfnmadd_pd:
10045   case Intrinsic::x86_fma_vfnmsub_ps:
10046   case Intrinsic::x86_fma_vfnmsub_pd:
10047   case Intrinsic::x86_fma_vfmaddsub_ps:
10048   case Intrinsic::x86_fma_vfmaddsub_pd:
10049   case Intrinsic::x86_fma_vfmsubadd_ps:
10050   case Intrinsic::x86_fma_vfmsubadd_pd:
10051   case Intrinsic::x86_fma_vfmadd_ps_256:
10052   case Intrinsic::x86_fma_vfmadd_pd_256:
10053   case Intrinsic::x86_fma_vfmsub_ps_256:
10054   case Intrinsic::x86_fma_vfmsub_pd_256:
10055   case Intrinsic::x86_fma_vfnmadd_ps_256:
10056   case Intrinsic::x86_fma_vfnmadd_pd_256:
10057   case Intrinsic::x86_fma_vfnmsub_ps_256:
10058   case Intrinsic::x86_fma_vfnmsub_pd_256:
10059   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10060   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10061   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10062   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10063     unsigned Opc;
10064     switch (IntNo) {
10065     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10066     case Intrinsic::x86_fma_vfmadd_ps:
10067     case Intrinsic::x86_fma_vfmadd_pd:
10068     case Intrinsic::x86_fma_vfmadd_ps_256:
10069     case Intrinsic::x86_fma_vfmadd_pd_256:
10070       Opc = X86ISD::FMADD;
10071       break;
10072     case Intrinsic::x86_fma_vfmsub_ps:
10073     case Intrinsic::x86_fma_vfmsub_pd:
10074     case Intrinsic::x86_fma_vfmsub_ps_256:
10075     case Intrinsic::x86_fma_vfmsub_pd_256:
10076       Opc = X86ISD::FMSUB;
10077       break;
10078     case Intrinsic::x86_fma_vfnmadd_ps:
10079     case Intrinsic::x86_fma_vfnmadd_pd:
10080     case Intrinsic::x86_fma_vfnmadd_ps_256:
10081     case Intrinsic::x86_fma_vfnmadd_pd_256:
10082       Opc = X86ISD::FNMADD;
10083       break;
10084     case Intrinsic::x86_fma_vfnmsub_ps:
10085     case Intrinsic::x86_fma_vfnmsub_pd:
10086     case Intrinsic::x86_fma_vfnmsub_ps_256:
10087     case Intrinsic::x86_fma_vfnmsub_pd_256:
10088       Opc = X86ISD::FNMSUB;
10089       break;
10090     case Intrinsic::x86_fma_vfmaddsub_ps:
10091     case Intrinsic::x86_fma_vfmaddsub_pd:
10092     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10093     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10094       Opc = X86ISD::FMADDSUB;
10095       break;
10096     case Intrinsic::x86_fma_vfmsubadd_ps:
10097     case Intrinsic::x86_fma_vfmsubadd_pd:
10098     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10099     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10100       Opc = X86ISD::FMSUBADD;
10101       break;
10102     }
10103
10104     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10105                        Op.getOperand(2), Op.getOperand(3));
10106   }
10107   }
10108 }
10109
10110 SDValue
10111 X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
10112   DebugLoc dl = Op.getDebugLoc();
10113   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10114   switch (IntNo) {
10115   default: return SDValue();    // Don't custom lower most intrinsics.
10116
10117   // RDRAND intrinsics.
10118   case Intrinsic::x86_rdrand_16:
10119   case Intrinsic::x86_rdrand_32:
10120   case Intrinsic::x86_rdrand_64: {
10121     // Emit the node with the right value type.
10122     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10123     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10124
10125     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10126     // return the value from Rand, which is always 0, casted to i32.
10127     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10128                       DAG.getConstant(1, Op->getValueType(1)),
10129                       DAG.getConstant(X86::COND_B, MVT::i32),
10130                       SDValue(Result.getNode(), 1) };
10131     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10132                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10133                                   Ops, 4);
10134
10135     // Return { result, isValid, chain }.
10136     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10137                        SDValue(Result.getNode(), 2));
10138   }
10139   }
10140 }
10141
10142 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10143                                            SelectionDAG &DAG) const {
10144   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10145   MFI->setReturnAddressIsTaken(true);
10146
10147   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10148   DebugLoc dl = Op.getDebugLoc();
10149
10150   if (Depth > 0) {
10151     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10152     SDValue Offset =
10153       DAG.getConstant(TD->getPointerSize(),
10154                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10155     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10156                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10157                                    FrameAddr, Offset),
10158                        MachinePointerInfo(), false, false, false, 0);
10159   }
10160
10161   // Just load the return address.
10162   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10163   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10164                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10165 }
10166
10167 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10168   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10169   MFI->setFrameAddressIsTaken(true);
10170
10171   EVT VT = Op.getValueType();
10172   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10173   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10174   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10175   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10176   while (Depth--)
10177     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10178                             MachinePointerInfo(),
10179                             false, false, false, 0);
10180   return FrameAddr;
10181 }
10182
10183 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10184                                                      SelectionDAG &DAG) const {
10185   return DAG.getIntPtrConstant(2*TD->getPointerSize());
10186 }
10187
10188 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10189   SDValue Chain     = Op.getOperand(0);
10190   SDValue Offset    = Op.getOperand(1);
10191   SDValue Handler   = Op.getOperand(2);
10192   DebugLoc dl       = Op.getDebugLoc();
10193
10194   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10195                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10196                                      getPointerTy());
10197   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10198
10199   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10200                                   DAG.getIntPtrConstant(TD->getPointerSize()));
10201   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10202   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10203                        false, false, 0);
10204   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10205
10206   return DAG.getNode(X86ISD::EH_RETURN, dl,
10207                      MVT::Other,
10208                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10209 }
10210
10211 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
10212                                                   SelectionDAG &DAG) const {
10213   return Op.getOperand(0);
10214 }
10215
10216 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10217                                                 SelectionDAG &DAG) const {
10218   SDValue Root = Op.getOperand(0);
10219   SDValue Trmp = Op.getOperand(1); // trampoline
10220   SDValue FPtr = Op.getOperand(2); // nested function
10221   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10222   DebugLoc dl  = Op.getDebugLoc();
10223
10224   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10225
10226   if (Subtarget->is64Bit()) {
10227     SDValue OutChains[6];
10228
10229     // Large code-model.
10230     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10231     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10232
10233     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10234     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10235
10236     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10237
10238     // Load the pointer to the nested function into R11.
10239     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10240     SDValue Addr = Trmp;
10241     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10242                                 Addr, MachinePointerInfo(TrmpAddr),
10243                                 false, false, 0);
10244
10245     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10246                        DAG.getConstant(2, MVT::i64));
10247     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10248                                 MachinePointerInfo(TrmpAddr, 2),
10249                                 false, false, 2);
10250
10251     // Load the 'nest' parameter value into R10.
10252     // R10 is specified in X86CallingConv.td
10253     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10254     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10255                        DAG.getConstant(10, MVT::i64));
10256     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10257                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10258                                 false, false, 0);
10259
10260     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10261                        DAG.getConstant(12, MVT::i64));
10262     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10263                                 MachinePointerInfo(TrmpAddr, 12),
10264                                 false, false, 2);
10265
10266     // Jump to the nested function.
10267     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10268     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10269                        DAG.getConstant(20, MVT::i64));
10270     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10271                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10272                                 false, false, 0);
10273
10274     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10275     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10276                        DAG.getConstant(22, MVT::i64));
10277     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10278                                 MachinePointerInfo(TrmpAddr, 22),
10279                                 false, false, 0);
10280
10281     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10282   } else {
10283     const Function *Func =
10284       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10285     CallingConv::ID CC = Func->getCallingConv();
10286     unsigned NestReg;
10287
10288     switch (CC) {
10289     default:
10290       llvm_unreachable("Unsupported calling convention");
10291     case CallingConv::C:
10292     case CallingConv::X86_StdCall: {
10293       // Pass 'nest' parameter in ECX.
10294       // Must be kept in sync with X86CallingConv.td
10295       NestReg = X86::ECX;
10296
10297       // Check that ECX wasn't needed by an 'inreg' parameter.
10298       FunctionType *FTy = Func->getFunctionType();
10299       const AttrListPtr &Attrs = Func->getAttributes();
10300
10301       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10302         unsigned InRegCount = 0;
10303         unsigned Idx = 1;
10304
10305         for (FunctionType::param_iterator I = FTy->param_begin(),
10306              E = FTy->param_end(); I != E; ++I, ++Idx)
10307           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10308             // FIXME: should only count parameters that are lowered to integers.
10309             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10310
10311         if (InRegCount > 2) {
10312           report_fatal_error("Nest register in use - reduce number of inreg"
10313                              " parameters!");
10314         }
10315       }
10316       break;
10317     }
10318     case CallingConv::X86_FastCall:
10319     case CallingConv::X86_ThisCall:
10320     case CallingConv::Fast:
10321       // Pass 'nest' parameter in EAX.
10322       // Must be kept in sync with X86CallingConv.td
10323       NestReg = X86::EAX;
10324       break;
10325     }
10326
10327     SDValue OutChains[4];
10328     SDValue Addr, Disp;
10329
10330     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10331                        DAG.getConstant(10, MVT::i32));
10332     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10333
10334     // This is storing the opcode for MOV32ri.
10335     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10336     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10337     OutChains[0] = DAG.getStore(Root, dl,
10338                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10339                                 Trmp, MachinePointerInfo(TrmpAddr),
10340                                 false, false, 0);
10341
10342     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10343                        DAG.getConstant(1, MVT::i32));
10344     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10345                                 MachinePointerInfo(TrmpAddr, 1),
10346                                 false, false, 1);
10347
10348     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10349     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10350                        DAG.getConstant(5, MVT::i32));
10351     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10352                                 MachinePointerInfo(TrmpAddr, 5),
10353                                 false, false, 1);
10354
10355     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10356                        DAG.getConstant(6, MVT::i32));
10357     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10358                                 MachinePointerInfo(TrmpAddr, 6),
10359                                 false, false, 1);
10360
10361     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10362   }
10363 }
10364
10365 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10366                                             SelectionDAG &DAG) const {
10367   /*
10368    The rounding mode is in bits 11:10 of FPSR, and has the following
10369    settings:
10370      00 Round to nearest
10371      01 Round to -inf
10372      10 Round to +inf
10373      11 Round to 0
10374
10375   FLT_ROUNDS, on the other hand, expects the following:
10376     -1 Undefined
10377      0 Round to 0
10378      1 Round to nearest
10379      2 Round to +inf
10380      3 Round to -inf
10381
10382   To perform the conversion, we do:
10383     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10384   */
10385
10386   MachineFunction &MF = DAG.getMachineFunction();
10387   const TargetMachine &TM = MF.getTarget();
10388   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10389   unsigned StackAlignment = TFI.getStackAlignment();
10390   EVT VT = Op.getValueType();
10391   DebugLoc DL = Op.getDebugLoc();
10392
10393   // Save FP Control Word to stack slot
10394   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10395   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10396
10397
10398   MachineMemOperand *MMO =
10399    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10400                            MachineMemOperand::MOStore, 2, 2);
10401
10402   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10403   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10404                                           DAG.getVTList(MVT::Other),
10405                                           Ops, 2, MVT::i16, MMO);
10406
10407   // Load FP Control Word from stack slot
10408   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10409                             MachinePointerInfo(), false, false, false, 0);
10410
10411   // Transform as necessary
10412   SDValue CWD1 =
10413     DAG.getNode(ISD::SRL, DL, MVT::i16,
10414                 DAG.getNode(ISD::AND, DL, MVT::i16,
10415                             CWD, DAG.getConstant(0x800, MVT::i16)),
10416                 DAG.getConstant(11, MVT::i8));
10417   SDValue CWD2 =
10418     DAG.getNode(ISD::SRL, DL, MVT::i16,
10419                 DAG.getNode(ISD::AND, DL, MVT::i16,
10420                             CWD, DAG.getConstant(0x400, MVT::i16)),
10421                 DAG.getConstant(9, MVT::i8));
10422
10423   SDValue RetVal =
10424     DAG.getNode(ISD::AND, DL, MVT::i16,
10425                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10426                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10427                             DAG.getConstant(1, MVT::i16)),
10428                 DAG.getConstant(3, MVT::i16));
10429
10430
10431   return DAG.getNode((VT.getSizeInBits() < 16 ?
10432                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10433 }
10434
10435 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10436   EVT VT = Op.getValueType();
10437   EVT OpVT = VT;
10438   unsigned NumBits = VT.getSizeInBits();
10439   DebugLoc dl = Op.getDebugLoc();
10440
10441   Op = Op.getOperand(0);
10442   if (VT == MVT::i8) {
10443     // Zero extend to i32 since there is not an i8 bsr.
10444     OpVT = MVT::i32;
10445     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10446   }
10447
10448   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10449   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10450   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10451
10452   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10453   SDValue Ops[] = {
10454     Op,
10455     DAG.getConstant(NumBits+NumBits-1, OpVT),
10456     DAG.getConstant(X86::COND_E, MVT::i8),
10457     Op.getValue(1)
10458   };
10459   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10460
10461   // Finally xor with NumBits-1.
10462   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10463
10464   if (VT == MVT::i8)
10465     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10466   return Op;
10467 }
10468
10469 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10470                                                 SelectionDAG &DAG) const {
10471   EVT VT = Op.getValueType();
10472   EVT OpVT = VT;
10473   unsigned NumBits = VT.getSizeInBits();
10474   DebugLoc dl = Op.getDebugLoc();
10475
10476   Op = Op.getOperand(0);
10477   if (VT == MVT::i8) {
10478     // Zero extend to i32 since there is not an i8 bsr.
10479     OpVT = MVT::i32;
10480     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10481   }
10482
10483   // Issue a bsr (scan bits in reverse).
10484   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10485   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10486
10487   // And xor with NumBits-1.
10488   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10489
10490   if (VT == MVT::i8)
10491     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10492   return Op;
10493 }
10494
10495 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10496   EVT VT = Op.getValueType();
10497   unsigned NumBits = VT.getSizeInBits();
10498   DebugLoc dl = Op.getDebugLoc();
10499   Op = Op.getOperand(0);
10500
10501   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10502   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10503   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10504
10505   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10506   SDValue Ops[] = {
10507     Op,
10508     DAG.getConstant(NumBits, VT),
10509     DAG.getConstant(X86::COND_E, MVT::i8),
10510     Op.getValue(1)
10511   };
10512   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10513 }
10514
10515 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10516 // ones, and then concatenate the result back.
10517 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10518   EVT VT = Op.getValueType();
10519
10520   assert(VT.is256BitVector() && VT.isInteger() &&
10521          "Unsupported value type for operation");
10522
10523   unsigned NumElems = VT.getVectorNumElements();
10524   DebugLoc dl = Op.getDebugLoc();
10525
10526   // Extract the LHS vectors
10527   SDValue LHS = Op.getOperand(0);
10528   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10529   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10530
10531   // Extract the RHS vectors
10532   SDValue RHS = Op.getOperand(1);
10533   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10534   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10535
10536   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10537   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10538
10539   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10540                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10541                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10542 }
10543
10544 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10545   assert(Op.getValueType().is256BitVector() &&
10546          Op.getValueType().isInteger() &&
10547          "Only handle AVX 256-bit vector integer operation");
10548   return Lower256IntArith(Op, DAG);
10549 }
10550
10551 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10552   assert(Op.getValueType().is256BitVector() &&
10553          Op.getValueType().isInteger() &&
10554          "Only handle AVX 256-bit vector integer operation");
10555   return Lower256IntArith(Op, DAG);
10556 }
10557
10558 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10559   EVT VT = Op.getValueType();
10560
10561   // Decompose 256-bit ops into smaller 128-bit ops.
10562   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10563     return Lower256IntArith(Op, DAG);
10564
10565   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10566          "Only know how to lower V2I64/V4I64 multiply");
10567
10568   DebugLoc dl = Op.getDebugLoc();
10569
10570   //  Ahi = psrlqi(a, 32);
10571   //  Bhi = psrlqi(b, 32);
10572   //
10573   //  AloBlo = pmuludq(a, b);
10574   //  AloBhi = pmuludq(a, Bhi);
10575   //  AhiBlo = pmuludq(Ahi, b);
10576
10577   //  AloBhi = psllqi(AloBhi, 32);
10578   //  AhiBlo = psllqi(AhiBlo, 32);
10579   //  return AloBlo + AloBhi + AhiBlo;
10580
10581   SDValue A = Op.getOperand(0);
10582   SDValue B = Op.getOperand(1);
10583
10584   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10585
10586   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10587   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10588
10589   // Bit cast to 32-bit vectors for MULUDQ
10590   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10591   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10592   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10593   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10594   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10595
10596   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10597   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10598   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10599
10600   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10601   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10602
10603   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10604   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10605 }
10606
10607 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10608
10609   EVT VT = Op.getValueType();
10610   DebugLoc dl = Op.getDebugLoc();
10611   SDValue R = Op.getOperand(0);
10612   SDValue Amt = Op.getOperand(1);
10613   LLVMContext *Context = DAG.getContext();
10614
10615   if (!Subtarget->hasSSE2())
10616     return SDValue();
10617
10618   // Optimize shl/srl/sra with constant shift amount.
10619   if (isSplatVector(Amt.getNode())) {
10620     SDValue SclrAmt = Amt->getOperand(0);
10621     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10622       uint64_t ShiftAmt = C->getZExtValue();
10623
10624       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10625           (Subtarget->hasAVX2() &&
10626            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10627         if (Op.getOpcode() == ISD::SHL)
10628           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10629                              DAG.getConstant(ShiftAmt, MVT::i32));
10630         if (Op.getOpcode() == ISD::SRL)
10631           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10632                              DAG.getConstant(ShiftAmt, MVT::i32));
10633         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10634           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10635                              DAG.getConstant(ShiftAmt, MVT::i32));
10636       }
10637
10638       if (VT == MVT::v16i8) {
10639         if (Op.getOpcode() == ISD::SHL) {
10640           // Make a large shift.
10641           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10642                                     DAG.getConstant(ShiftAmt, MVT::i32));
10643           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10644           // Zero out the rightmost bits.
10645           SmallVector<SDValue, 16> V(16,
10646                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10647                                                      MVT::i8));
10648           return DAG.getNode(ISD::AND, dl, VT, SHL,
10649                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10650         }
10651         if (Op.getOpcode() == ISD::SRL) {
10652           // Make a large shift.
10653           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10654                                     DAG.getConstant(ShiftAmt, MVT::i32));
10655           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10656           // Zero out the leftmost bits.
10657           SmallVector<SDValue, 16> V(16,
10658                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10659                                                      MVT::i8));
10660           return DAG.getNode(ISD::AND, dl, VT, SRL,
10661                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10662         }
10663         if (Op.getOpcode() == ISD::SRA) {
10664           if (ShiftAmt == 7) {
10665             // R s>> 7  ===  R s< 0
10666             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10667             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10668           }
10669
10670           // R s>> a === ((R u>> a) ^ m) - m
10671           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10672           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10673                                                          MVT::i8));
10674           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10675           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10676           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10677           return Res;
10678         }
10679         llvm_unreachable("Unknown shift opcode.");
10680       }
10681
10682       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10683         if (Op.getOpcode() == ISD::SHL) {
10684           // Make a large shift.
10685           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10686                                     DAG.getConstant(ShiftAmt, MVT::i32));
10687           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10688           // Zero out the rightmost bits.
10689           SmallVector<SDValue, 32> V(32,
10690                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10691                                                      MVT::i8));
10692           return DAG.getNode(ISD::AND, dl, VT, SHL,
10693                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10694         }
10695         if (Op.getOpcode() == ISD::SRL) {
10696           // Make a large shift.
10697           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10698                                     DAG.getConstant(ShiftAmt, MVT::i32));
10699           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10700           // Zero out the leftmost bits.
10701           SmallVector<SDValue, 32> V(32,
10702                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10703                                                      MVT::i8));
10704           return DAG.getNode(ISD::AND, dl, VT, SRL,
10705                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10706         }
10707         if (Op.getOpcode() == ISD::SRA) {
10708           if (ShiftAmt == 7) {
10709             // R s>> 7  ===  R s< 0
10710             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10711             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10712           }
10713
10714           // R s>> a === ((R u>> a) ^ m) - m
10715           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10716           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10717                                                          MVT::i8));
10718           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10719           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10720           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10721           return Res;
10722         }
10723         llvm_unreachable("Unknown shift opcode.");
10724       }
10725     }
10726   }
10727
10728   // Lower SHL with variable shift amount.
10729   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10730     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10731                      DAG.getConstant(23, MVT::i32));
10732
10733     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10734     Constant *C = ConstantDataVector::get(*Context, CV);
10735     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10736     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10737                                  MachinePointerInfo::getConstantPool(),
10738                                  false, false, false, 16);
10739
10740     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10741     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10742     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10743     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10744   }
10745   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10746     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10747
10748     // a = a << 5;
10749     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10750                      DAG.getConstant(5, MVT::i32));
10751     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10752
10753     // Turn 'a' into a mask suitable for VSELECT
10754     SDValue VSelM = DAG.getConstant(0x80, VT);
10755     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10756     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10757
10758     SDValue CM1 = DAG.getConstant(0x0f, VT);
10759     SDValue CM2 = DAG.getConstant(0x3f, VT);
10760
10761     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10762     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10763     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10764                             DAG.getConstant(4, MVT::i32), DAG);
10765     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10766     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10767
10768     // a += a
10769     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10770     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10771     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10772
10773     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10774     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10775     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10776                             DAG.getConstant(2, MVT::i32), DAG);
10777     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10778     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10779
10780     // a += a
10781     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10782     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10783     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10784
10785     // return VSELECT(r, r+r, a);
10786     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10787                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10788     return R;
10789   }
10790
10791   // Decompose 256-bit shifts into smaller 128-bit shifts.
10792   if (VT.is256BitVector()) {
10793     unsigned NumElems = VT.getVectorNumElements();
10794     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10795     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10796
10797     // Extract the two vectors
10798     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10799     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10800
10801     // Recreate the shift amount vectors
10802     SDValue Amt1, Amt2;
10803     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10804       // Constant shift amount
10805       SmallVector<SDValue, 4> Amt1Csts;
10806       SmallVector<SDValue, 4> Amt2Csts;
10807       for (unsigned i = 0; i != NumElems/2; ++i)
10808         Amt1Csts.push_back(Amt->getOperand(i));
10809       for (unsigned i = NumElems/2; i != NumElems; ++i)
10810         Amt2Csts.push_back(Amt->getOperand(i));
10811
10812       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10813                                  &Amt1Csts[0], NumElems/2);
10814       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10815                                  &Amt2Csts[0], NumElems/2);
10816     } else {
10817       // Variable shift amount
10818       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10819       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10820     }
10821
10822     // Issue new vector shifts for the smaller types
10823     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10824     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10825
10826     // Concatenate the result back
10827     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10828   }
10829
10830   return SDValue();
10831 }
10832
10833 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10834   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10835   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10836   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10837   // has only one use.
10838   SDNode *N = Op.getNode();
10839   SDValue LHS = N->getOperand(0);
10840   SDValue RHS = N->getOperand(1);
10841   unsigned BaseOp = 0;
10842   unsigned Cond = 0;
10843   DebugLoc DL = Op.getDebugLoc();
10844   switch (Op.getOpcode()) {
10845   default: llvm_unreachable("Unknown ovf instruction!");
10846   case ISD::SADDO:
10847     // A subtract of one will be selected as a INC. Note that INC doesn't
10848     // set CF, so we can't do this for UADDO.
10849     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10850       if (C->isOne()) {
10851         BaseOp = X86ISD::INC;
10852         Cond = X86::COND_O;
10853         break;
10854       }
10855     BaseOp = X86ISD::ADD;
10856     Cond = X86::COND_O;
10857     break;
10858   case ISD::UADDO:
10859     BaseOp = X86ISD::ADD;
10860     Cond = X86::COND_B;
10861     break;
10862   case ISD::SSUBO:
10863     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10864     // set CF, so we can't do this for USUBO.
10865     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10866       if (C->isOne()) {
10867         BaseOp = X86ISD::DEC;
10868         Cond = X86::COND_O;
10869         break;
10870       }
10871     BaseOp = X86ISD::SUB;
10872     Cond = X86::COND_O;
10873     break;
10874   case ISD::USUBO:
10875     BaseOp = X86ISD::SUB;
10876     Cond = X86::COND_B;
10877     break;
10878   case ISD::SMULO:
10879     BaseOp = X86ISD::SMUL;
10880     Cond = X86::COND_O;
10881     break;
10882   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10883     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10884                                  MVT::i32);
10885     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10886
10887     SDValue SetCC =
10888       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10889                   DAG.getConstant(X86::COND_O, MVT::i32),
10890                   SDValue(Sum.getNode(), 2));
10891
10892     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10893   }
10894   }
10895
10896   // Also sets EFLAGS.
10897   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10898   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10899
10900   SDValue SetCC =
10901     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10902                 DAG.getConstant(Cond, MVT::i32),
10903                 SDValue(Sum.getNode(), 1));
10904
10905   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10906 }
10907
10908 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10909                                                   SelectionDAG &DAG) const {
10910   DebugLoc dl = Op.getDebugLoc();
10911   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10912   EVT VT = Op.getValueType();
10913
10914   if (!Subtarget->hasSSE2() || !VT.isVector())
10915     return SDValue();
10916
10917   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10918                       ExtraVT.getScalarType().getSizeInBits();
10919   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10920
10921   switch (VT.getSimpleVT().SimpleTy) {
10922     default: return SDValue();
10923     case MVT::v8i32:
10924     case MVT::v16i16:
10925       if (!Subtarget->hasAVX())
10926         return SDValue();
10927       if (!Subtarget->hasAVX2()) {
10928         // needs to be split
10929         unsigned NumElems = VT.getVectorNumElements();
10930
10931         // Extract the LHS vectors
10932         SDValue LHS = Op.getOperand(0);
10933         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10934         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10935
10936         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10937         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10938
10939         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10940         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10941         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10942                                    ExtraNumElems/2);
10943         SDValue Extra = DAG.getValueType(ExtraVT);
10944
10945         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10946         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10947
10948         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10949       }
10950       // fall through
10951     case MVT::v4i32:
10952     case MVT::v8i16: {
10953       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10954                                          Op.getOperand(0), ShAmt, DAG);
10955       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10956     }
10957   }
10958 }
10959
10960
10961 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10962   DebugLoc dl = Op.getDebugLoc();
10963
10964   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10965   // There isn't any reason to disable it if the target processor supports it.
10966   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10967     SDValue Chain = Op.getOperand(0);
10968     SDValue Zero = DAG.getConstant(0, MVT::i32);
10969     SDValue Ops[] = {
10970       DAG.getRegister(X86::ESP, MVT::i32), // Base
10971       DAG.getTargetConstant(1, MVT::i8),   // Scale
10972       DAG.getRegister(0, MVT::i32),        // Index
10973       DAG.getTargetConstant(0, MVT::i32),  // Disp
10974       DAG.getRegister(0, MVT::i32),        // Segment.
10975       Zero,
10976       Chain
10977     };
10978     SDNode *Res =
10979       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10980                           array_lengthof(Ops));
10981     return SDValue(Res, 0);
10982   }
10983
10984   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10985   if (!isDev)
10986     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10987
10988   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10989   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10990   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10991   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10992
10993   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10994   if (!Op1 && !Op2 && !Op3 && Op4)
10995     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10996
10997   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10998   if (Op1 && !Op2 && !Op3 && !Op4)
10999     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11000
11001   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11002   //           (MFENCE)>;
11003   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11004 }
11005
11006 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
11007                                              SelectionDAG &DAG) const {
11008   DebugLoc dl = Op.getDebugLoc();
11009   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11010     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11011   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11012     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11013
11014   // The only fence that needs an instruction is a sequentially-consistent
11015   // cross-thread fence.
11016   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11017     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11018     // no-sse2). There isn't any reason to disable it if the target processor
11019     // supports it.
11020     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11021       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11022
11023     SDValue Chain = Op.getOperand(0);
11024     SDValue Zero = DAG.getConstant(0, MVT::i32);
11025     SDValue Ops[] = {
11026       DAG.getRegister(X86::ESP, MVT::i32), // Base
11027       DAG.getTargetConstant(1, MVT::i8),   // Scale
11028       DAG.getRegister(0, MVT::i32),        // Index
11029       DAG.getTargetConstant(0, MVT::i32),  // Disp
11030       DAG.getRegister(0, MVT::i32),        // Segment.
11031       Zero,
11032       Chain
11033     };
11034     SDNode *Res =
11035       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11036                          array_lengthof(Ops));
11037     return SDValue(Res, 0);
11038   }
11039
11040   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11041   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11042 }
11043
11044
11045 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
11046   EVT T = Op.getValueType();
11047   DebugLoc DL = Op.getDebugLoc();
11048   unsigned Reg = 0;
11049   unsigned size = 0;
11050   switch(T.getSimpleVT().SimpleTy) {
11051   default: llvm_unreachable("Invalid value type!");
11052   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11053   case MVT::i16: Reg = X86::AX;  size = 2; break;
11054   case MVT::i32: Reg = X86::EAX; size = 4; break;
11055   case MVT::i64:
11056     assert(Subtarget->is64Bit() && "Node not type legal!");
11057     Reg = X86::RAX; size = 8;
11058     break;
11059   }
11060   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11061                                     Op.getOperand(2), SDValue());
11062   SDValue Ops[] = { cpIn.getValue(0),
11063                     Op.getOperand(1),
11064                     Op.getOperand(3),
11065                     DAG.getTargetConstant(size, MVT::i8),
11066                     cpIn.getValue(1) };
11067   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11068   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11069   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11070                                            Ops, 5, T, MMO);
11071   SDValue cpOut =
11072     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11073   return cpOut;
11074 }
11075
11076 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
11077                                                  SelectionDAG &DAG) const {
11078   assert(Subtarget->is64Bit() && "Result not type legalized?");
11079   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11080   SDValue TheChain = Op.getOperand(0);
11081   DebugLoc dl = Op.getDebugLoc();
11082   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11083   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11084   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11085                                    rax.getValue(2));
11086   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11087                             DAG.getConstant(32, MVT::i8));
11088   SDValue Ops[] = {
11089     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11090     rdx.getValue(1)
11091   };
11092   return DAG.getMergeValues(Ops, 2, dl);
11093 }
11094
11095 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
11096                                             SelectionDAG &DAG) const {
11097   EVT SrcVT = Op.getOperand(0).getValueType();
11098   EVT DstVT = Op.getValueType();
11099   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11100          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11101   assert((DstVT == MVT::i64 ||
11102           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11103          "Unexpected custom BITCAST");
11104   // i64 <=> MMX conversions are Legal.
11105   if (SrcVT==MVT::i64 && DstVT.isVector())
11106     return Op;
11107   if (DstVT==MVT::i64 && SrcVT.isVector())
11108     return Op;
11109   // MMX <=> MMX conversions are Legal.
11110   if (SrcVT.isVector() && DstVT.isVector())
11111     return Op;
11112   // All other conversions need to be expanded.
11113   return SDValue();
11114 }
11115
11116 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
11117   SDNode *Node = Op.getNode();
11118   DebugLoc dl = Node->getDebugLoc();
11119   EVT T = Node->getValueType(0);
11120   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11121                               DAG.getConstant(0, T), Node->getOperand(2));
11122   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11123                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11124                        Node->getOperand(0),
11125                        Node->getOperand(1), negOp,
11126                        cast<AtomicSDNode>(Node)->getSrcValue(),
11127                        cast<AtomicSDNode>(Node)->getAlignment(),
11128                        cast<AtomicSDNode>(Node)->getOrdering(),
11129                        cast<AtomicSDNode>(Node)->getSynchScope());
11130 }
11131
11132 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11133   SDNode *Node = Op.getNode();
11134   DebugLoc dl = Node->getDebugLoc();
11135   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11136
11137   // Convert seq_cst store -> xchg
11138   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11139   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11140   //        (The only way to get a 16-byte store is cmpxchg16b)
11141   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11142   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11143       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11144     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11145                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11146                                  Node->getOperand(0),
11147                                  Node->getOperand(1), Node->getOperand(2),
11148                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11149                                  cast<AtomicSDNode>(Node)->getOrdering(),
11150                                  cast<AtomicSDNode>(Node)->getSynchScope());
11151     return Swap.getValue(1);
11152   }
11153   // Other atomic stores have a simple pattern.
11154   return Op;
11155 }
11156
11157 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11158   EVT VT = Op.getNode()->getValueType(0);
11159
11160   // Let legalize expand this if it isn't a legal type yet.
11161   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11162     return SDValue();
11163
11164   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11165
11166   unsigned Opc;
11167   bool ExtraOp = false;
11168   switch (Op.getOpcode()) {
11169   default: llvm_unreachable("Invalid code");
11170   case ISD::ADDC: Opc = X86ISD::ADD; break;
11171   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11172   case ISD::SUBC: Opc = X86ISD::SUB; break;
11173   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11174   }
11175
11176   if (!ExtraOp)
11177     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11178                        Op.getOperand(1));
11179   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11180                      Op.getOperand(1), Op.getOperand(2));
11181 }
11182
11183 /// LowerOperation - Provide custom lowering hooks for some operations.
11184 ///
11185 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11186   switch (Op.getOpcode()) {
11187   default: llvm_unreachable("Should not custom lower this!");
11188   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11189   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
11190   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
11191   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
11192   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11193   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11194   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11195   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11196   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11197   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11198   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11199   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
11200   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
11201   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11202   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11203   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11204   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11205   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11206   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11207   case ISD::SHL_PARTS:
11208   case ISD::SRA_PARTS:
11209   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11210   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11211   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11212   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11213   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11214   case ISD::FABS:               return LowerFABS(Op, DAG);
11215   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11216   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11217   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11218   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11219   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11220   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11221   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11222   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11223   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11224   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11225   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11226   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11227   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11228   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11229   case ISD::FRAME_TO_ARGS_OFFSET:
11230                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11231   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11232   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11233   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11234   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11235   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11236   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11237   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11238   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11239   case ISD::MUL:                return LowerMUL(Op, DAG);
11240   case ISD::SRA:
11241   case ISD::SRL:
11242   case ISD::SHL:                return LowerShift(Op, DAG);
11243   case ISD::SADDO:
11244   case ISD::UADDO:
11245   case ISD::SSUBO:
11246   case ISD::USUBO:
11247   case ISD::SMULO:
11248   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11249   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
11250   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11251   case ISD::ADDC:
11252   case ISD::ADDE:
11253   case ISD::SUBC:
11254   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11255   case ISD::ADD:                return LowerADD(Op, DAG);
11256   case ISD::SUB:                return LowerSUB(Op, DAG);
11257   }
11258 }
11259
11260 static void ReplaceATOMIC_LOAD(SDNode *Node,
11261                                   SmallVectorImpl<SDValue> &Results,
11262                                   SelectionDAG &DAG) {
11263   DebugLoc dl = Node->getDebugLoc();
11264   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11265
11266   // Convert wide load -> cmpxchg8b/cmpxchg16b
11267   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11268   //        (The only way to get a 16-byte load is cmpxchg16b)
11269   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11270   SDValue Zero = DAG.getConstant(0, VT);
11271   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11272                                Node->getOperand(0),
11273                                Node->getOperand(1), Zero, Zero,
11274                                cast<AtomicSDNode>(Node)->getMemOperand(),
11275                                cast<AtomicSDNode>(Node)->getOrdering(),
11276                                cast<AtomicSDNode>(Node)->getSynchScope());
11277   Results.push_back(Swap.getValue(0));
11278   Results.push_back(Swap.getValue(1));
11279 }
11280
11281 static void
11282 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11283                         SelectionDAG &DAG, unsigned NewOp) {
11284   DebugLoc dl = Node->getDebugLoc();
11285   assert (Node->getValueType(0) == MVT::i64 &&
11286           "Only know how to expand i64 atomics");
11287
11288   SDValue Chain = Node->getOperand(0);
11289   SDValue In1 = Node->getOperand(1);
11290   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11291                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11292   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11293                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11294   SDValue Ops[] = { Chain, In1, In2L, In2H };
11295   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11296   SDValue Result =
11297     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11298                             cast<MemSDNode>(Node)->getMemOperand());
11299   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11300   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11301   Results.push_back(Result.getValue(2));
11302 }
11303
11304 /// ReplaceNodeResults - Replace a node with an illegal result type
11305 /// with a new node built out of custom code.
11306 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11307                                            SmallVectorImpl<SDValue>&Results,
11308                                            SelectionDAG &DAG) const {
11309   DebugLoc dl = N->getDebugLoc();
11310   switch (N->getOpcode()) {
11311   default:
11312     llvm_unreachable("Do not know how to custom type legalize this operation!");
11313   case ISD::SIGN_EXTEND_INREG:
11314   case ISD::ADDC:
11315   case ISD::ADDE:
11316   case ISD::SUBC:
11317   case ISD::SUBE:
11318     // We don't want to expand or promote these.
11319     return;
11320   case ISD::FP_TO_SINT:
11321   case ISD::FP_TO_UINT: {
11322     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11323
11324     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11325       return;
11326
11327     std::pair<SDValue,SDValue> Vals =
11328         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11329     SDValue FIST = Vals.first, StackSlot = Vals.second;
11330     if (FIST.getNode() != 0) {
11331       EVT VT = N->getValueType(0);
11332       // Return a load from the stack slot.
11333       if (StackSlot.getNode() != 0)
11334         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11335                                       MachinePointerInfo(),
11336                                       false, false, false, 0));
11337       else
11338         Results.push_back(FIST);
11339     }
11340     return;
11341   }
11342   case ISD::READCYCLECOUNTER: {
11343     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11344     SDValue TheChain = N->getOperand(0);
11345     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11346     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11347                                      rd.getValue(1));
11348     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11349                                      eax.getValue(2));
11350     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11351     SDValue Ops[] = { eax, edx };
11352     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11353     Results.push_back(edx.getValue(1));
11354     return;
11355   }
11356   case ISD::ATOMIC_CMP_SWAP: {
11357     EVT T = N->getValueType(0);
11358     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11359     bool Regs64bit = T == MVT::i128;
11360     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11361     SDValue cpInL, cpInH;
11362     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11363                         DAG.getConstant(0, HalfT));
11364     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11365                         DAG.getConstant(1, HalfT));
11366     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11367                              Regs64bit ? X86::RAX : X86::EAX,
11368                              cpInL, SDValue());
11369     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11370                              Regs64bit ? X86::RDX : X86::EDX,
11371                              cpInH, cpInL.getValue(1));
11372     SDValue swapInL, swapInH;
11373     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11374                           DAG.getConstant(0, HalfT));
11375     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11376                           DAG.getConstant(1, HalfT));
11377     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11378                                Regs64bit ? X86::RBX : X86::EBX,
11379                                swapInL, cpInH.getValue(1));
11380     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11381                                Regs64bit ? X86::RCX : X86::ECX,
11382                                swapInH, swapInL.getValue(1));
11383     SDValue Ops[] = { swapInH.getValue(0),
11384                       N->getOperand(1),
11385                       swapInH.getValue(1) };
11386     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11387     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11388     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11389                                   X86ISD::LCMPXCHG8_DAG;
11390     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11391                                              Ops, 3, T, MMO);
11392     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11393                                         Regs64bit ? X86::RAX : X86::EAX,
11394                                         HalfT, Result.getValue(1));
11395     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11396                                         Regs64bit ? X86::RDX : X86::EDX,
11397                                         HalfT, cpOutL.getValue(2));
11398     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11399     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11400     Results.push_back(cpOutH.getValue(1));
11401     return;
11402   }
11403   case ISD::ATOMIC_LOAD_ADD:
11404   case ISD::ATOMIC_LOAD_AND:
11405   case ISD::ATOMIC_LOAD_NAND:
11406   case ISD::ATOMIC_LOAD_OR:
11407   case ISD::ATOMIC_LOAD_SUB:
11408   case ISD::ATOMIC_LOAD_XOR:
11409   case ISD::ATOMIC_SWAP: {
11410     unsigned Opc;
11411     switch (N->getOpcode()) {
11412     default: llvm_unreachable("Unexpected opcode");
11413     case ISD::ATOMIC_LOAD_ADD:
11414       Opc = X86ISD::ATOMADD64_DAG;
11415       break;
11416     case ISD::ATOMIC_LOAD_AND:
11417       Opc = X86ISD::ATOMAND64_DAG;
11418       break;
11419     case ISD::ATOMIC_LOAD_NAND:
11420       Opc = X86ISD::ATOMNAND64_DAG;
11421       break;
11422     case ISD::ATOMIC_LOAD_OR:
11423       Opc = X86ISD::ATOMOR64_DAG;
11424       break;
11425     case ISD::ATOMIC_LOAD_SUB:
11426       Opc = X86ISD::ATOMSUB64_DAG;
11427       break;
11428     case ISD::ATOMIC_LOAD_XOR:
11429       Opc = X86ISD::ATOMXOR64_DAG;
11430       break;
11431     case ISD::ATOMIC_SWAP:
11432       Opc = X86ISD::ATOMSWAP64_DAG;
11433       break;
11434     }
11435     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11436     return;
11437   }
11438   case ISD::ATOMIC_LOAD:
11439     ReplaceATOMIC_LOAD(N, Results, DAG);
11440   }
11441 }
11442
11443 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11444   switch (Opcode) {
11445   default: return NULL;
11446   case X86ISD::BSF:                return "X86ISD::BSF";
11447   case X86ISD::BSR:                return "X86ISD::BSR";
11448   case X86ISD::SHLD:               return "X86ISD::SHLD";
11449   case X86ISD::SHRD:               return "X86ISD::SHRD";
11450   case X86ISD::FAND:               return "X86ISD::FAND";
11451   case X86ISD::FOR:                return "X86ISD::FOR";
11452   case X86ISD::FXOR:               return "X86ISD::FXOR";
11453   case X86ISD::FSRL:               return "X86ISD::FSRL";
11454   case X86ISD::FILD:               return "X86ISD::FILD";
11455   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11456   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11457   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11458   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11459   case X86ISD::FLD:                return "X86ISD::FLD";
11460   case X86ISD::FST:                return "X86ISD::FST";
11461   case X86ISD::CALL:               return "X86ISD::CALL";
11462   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11463   case X86ISD::BT:                 return "X86ISD::BT";
11464   case X86ISD::CMP:                return "X86ISD::CMP";
11465   case X86ISD::COMI:               return "X86ISD::COMI";
11466   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11467   case X86ISD::SETCC:              return "X86ISD::SETCC";
11468   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11469   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11470   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11471   case X86ISD::CMOV:               return "X86ISD::CMOV";
11472   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11473   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11474   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11475   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11476   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11477   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11478   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11479   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11480   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11481   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11482   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11483   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11484   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11485   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11486   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11487   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11488   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11489   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11490   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11491   case X86ISD::HADD:               return "X86ISD::HADD";
11492   case X86ISD::HSUB:               return "X86ISD::HSUB";
11493   case X86ISD::FHADD:              return "X86ISD::FHADD";
11494   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11495   case X86ISD::FMAX:               return "X86ISD::FMAX";
11496   case X86ISD::FMIN:               return "X86ISD::FMIN";
11497   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11498   case X86ISD::FMINC:              return "X86ISD::FMINC";
11499   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11500   case X86ISD::FRCP:               return "X86ISD::FRCP";
11501   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11502   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11503   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11504   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11505   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11506   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11507   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11508   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11509   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11510   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11511   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11512   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11513   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11514   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11515   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11516   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11517   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11518   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11519   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11520   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11521   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11522   case X86ISD::VSHL:               return "X86ISD::VSHL";
11523   case X86ISD::VSRL:               return "X86ISD::VSRL";
11524   case X86ISD::VSRA:               return "X86ISD::VSRA";
11525   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11526   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11527   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11528   case X86ISD::CMPP:               return "X86ISD::CMPP";
11529   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11530   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11531   case X86ISD::ADD:                return "X86ISD::ADD";
11532   case X86ISD::SUB:                return "X86ISD::SUB";
11533   case X86ISD::ADC:                return "X86ISD::ADC";
11534   case X86ISD::SBB:                return "X86ISD::SBB";
11535   case X86ISD::SMUL:               return "X86ISD::SMUL";
11536   case X86ISD::UMUL:               return "X86ISD::UMUL";
11537   case X86ISD::INC:                return "X86ISD::INC";
11538   case X86ISD::DEC:                return "X86ISD::DEC";
11539   case X86ISD::OR:                 return "X86ISD::OR";
11540   case X86ISD::XOR:                return "X86ISD::XOR";
11541   case X86ISD::AND:                return "X86ISD::AND";
11542   case X86ISD::ANDN:               return "X86ISD::ANDN";
11543   case X86ISD::BLSI:               return "X86ISD::BLSI";
11544   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11545   case X86ISD::BLSR:               return "X86ISD::BLSR";
11546   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11547   case X86ISD::PTEST:              return "X86ISD::PTEST";
11548   case X86ISD::TESTP:              return "X86ISD::TESTP";
11549   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11550   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11551   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11552   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11553   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11554   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11555   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11556   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11557   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11558   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11559   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11560   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11561   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11562   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11563   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11564   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11565   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11566   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11567   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11568   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11569   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11570   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11571   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11572   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11573   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11574   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11575   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11576   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11577   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11578   case X86ISD::SAHF:               return "X86ISD::SAHF";
11579   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11580   case X86ISD::FMADD:              return "X86ISD::FMADD";
11581   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11582   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11583   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11584   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11585   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11586   }
11587 }
11588
11589 // isLegalAddressingMode - Return true if the addressing mode represented
11590 // by AM is legal for this target, for a load/store of the specified type.
11591 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11592                                               Type *Ty) const {
11593   // X86 supports extremely general addressing modes.
11594   CodeModel::Model M = getTargetMachine().getCodeModel();
11595   Reloc::Model R = getTargetMachine().getRelocationModel();
11596
11597   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11598   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11599     return false;
11600
11601   if (AM.BaseGV) {
11602     unsigned GVFlags =
11603       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11604
11605     // If a reference to this global requires an extra load, we can't fold it.
11606     if (isGlobalStubReference(GVFlags))
11607       return false;
11608
11609     // If BaseGV requires a register for the PIC base, we cannot also have a
11610     // BaseReg specified.
11611     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11612       return false;
11613
11614     // If lower 4G is not available, then we must use rip-relative addressing.
11615     if ((M != CodeModel::Small || R != Reloc::Static) &&
11616         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11617       return false;
11618   }
11619
11620   switch (AM.Scale) {
11621   case 0:
11622   case 1:
11623   case 2:
11624   case 4:
11625   case 8:
11626     // These scales always work.
11627     break;
11628   case 3:
11629   case 5:
11630   case 9:
11631     // These scales are formed with basereg+scalereg.  Only accept if there is
11632     // no basereg yet.
11633     if (AM.HasBaseReg)
11634       return false;
11635     break;
11636   default:  // Other stuff never works.
11637     return false;
11638   }
11639
11640   return true;
11641 }
11642
11643
11644 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11645   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11646     return false;
11647   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11648   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11649   if (NumBits1 <= NumBits2)
11650     return false;
11651   return true;
11652 }
11653
11654 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11655   return Imm == (int32_t)Imm;
11656 }
11657
11658 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11659   // Can also use sub to handle negated immediates.
11660   return Imm == (int32_t)Imm;
11661 }
11662
11663 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11664   if (!VT1.isInteger() || !VT2.isInteger())
11665     return false;
11666   unsigned NumBits1 = VT1.getSizeInBits();
11667   unsigned NumBits2 = VT2.getSizeInBits();
11668   if (NumBits1 <= NumBits2)
11669     return false;
11670   return true;
11671 }
11672
11673 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11674   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11675   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11676 }
11677
11678 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11679   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11680   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11681 }
11682
11683 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11684   // i16 instructions are longer (0x66 prefix) and potentially slower.
11685   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11686 }
11687
11688 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11689 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11690 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11691 /// are assumed to be legal.
11692 bool
11693 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11694                                       EVT VT) const {
11695   // Very little shuffling can be done for 64-bit vectors right now.
11696   if (VT.getSizeInBits() == 64)
11697     return false;
11698
11699   // FIXME: pshufb, blends, shifts.
11700   return (VT.getVectorNumElements() == 2 ||
11701           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11702           isMOVLMask(M, VT) ||
11703           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11704           isPSHUFDMask(M, VT) ||
11705           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11706           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11707           isPALIGNRMask(M, VT, Subtarget) ||
11708           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11709           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11710           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11711           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11712 }
11713
11714 bool
11715 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11716                                           EVT VT) const {
11717   unsigned NumElts = VT.getVectorNumElements();
11718   // FIXME: This collection of masks seems suspect.
11719   if (NumElts == 2)
11720     return true;
11721   if (NumElts == 4 && VT.is128BitVector()) {
11722     return (isMOVLMask(Mask, VT)  ||
11723             isCommutedMOVLMask(Mask, VT, true) ||
11724             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11725             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11726   }
11727   return false;
11728 }
11729
11730 //===----------------------------------------------------------------------===//
11731 //                           X86 Scheduler Hooks
11732 //===----------------------------------------------------------------------===//
11733
11734 // private utility function
11735 MachineBasicBlock *
11736 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11737                                                        MachineBasicBlock *MBB,
11738                                                        unsigned regOpc,
11739                                                        unsigned immOpc,
11740                                                        unsigned LoadOpc,
11741                                                        unsigned CXchgOpc,
11742                                                        unsigned notOpc,
11743                                                        unsigned EAXreg,
11744                                                  const TargetRegisterClass *RC,
11745                                                        bool Invert) const {
11746   // For the atomic bitwise operator, we generate
11747   //   thisMBB:
11748   //   newMBB:
11749   //     ld  t1 = [bitinstr.addr]
11750   //     op  t2 = t1, [bitinstr.val]
11751   //     not t3 = t2  (if Invert)
11752   //     mov EAX = t1
11753   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11754   //     bz  newMBB
11755   //     fallthrough -->nextMBB
11756   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11757   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11758   MachineFunction::iterator MBBIter = MBB;
11759   ++MBBIter;
11760
11761   /// First build the CFG
11762   MachineFunction *F = MBB->getParent();
11763   MachineBasicBlock *thisMBB = MBB;
11764   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11765   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11766   F->insert(MBBIter, newMBB);
11767   F->insert(MBBIter, nextMBB);
11768
11769   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11770   nextMBB->splice(nextMBB->begin(), thisMBB,
11771                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11772                   thisMBB->end());
11773   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11774
11775   // Update thisMBB to fall through to newMBB
11776   thisMBB->addSuccessor(newMBB);
11777
11778   // newMBB jumps to itself and fall through to nextMBB
11779   newMBB->addSuccessor(nextMBB);
11780   newMBB->addSuccessor(newMBB);
11781
11782   // Insert instructions into newMBB based on incoming instruction
11783   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11784          "unexpected number of operands");
11785   DebugLoc dl = bInstr->getDebugLoc();
11786   MachineOperand& destOper = bInstr->getOperand(0);
11787   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11788   int numArgs = bInstr->getNumOperands() - 1;
11789   for (int i=0; i < numArgs; ++i)
11790     argOpers[i] = &bInstr->getOperand(i+1);
11791
11792   // x86 address has 4 operands: base, index, scale, and displacement
11793   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11794   int valArgIndx = lastAddrIndx + 1;
11795
11796   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11797   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11798   for (int i=0; i <= lastAddrIndx; ++i)
11799     (*MIB).addOperand(*argOpers[i]);
11800
11801   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11802   assert((argOpers[valArgIndx]->isReg() ||
11803           argOpers[valArgIndx]->isImm()) &&
11804          "invalid operand");
11805   if (argOpers[valArgIndx]->isReg())
11806     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11807   else
11808     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11809   MIB.addReg(t1);
11810   (*MIB).addOperand(*argOpers[valArgIndx]);
11811
11812   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11813   if (Invert) {
11814     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11815   }
11816   else
11817     t3 = t2;
11818
11819   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11820   MIB.addReg(t1);
11821
11822   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11823   for (int i=0; i <= lastAddrIndx; ++i)
11824     (*MIB).addOperand(*argOpers[i]);
11825   MIB.addReg(t3);
11826   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11827   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11828                     bInstr->memoperands_end());
11829
11830   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11831   MIB.addReg(EAXreg);
11832
11833   // insert branch
11834   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11835
11836   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11837   return nextMBB;
11838 }
11839
11840 // private utility function:  64 bit atomics on 32 bit host.
11841 MachineBasicBlock *
11842 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11843                                                        MachineBasicBlock *MBB,
11844                                                        unsigned regOpcL,
11845                                                        unsigned regOpcH,
11846                                                        unsigned immOpcL,
11847                                                        unsigned immOpcH,
11848                                                        bool Invert) const {
11849   // For the atomic bitwise operator, we generate
11850   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11851   //     ld t1,t2 = [bitinstr.addr]
11852   //   newMBB:
11853   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11854   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11855   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11856   //     neg t7, t8 < t5, t6  (if Invert)
11857   //     mov ECX, EBX <- t5, t6
11858   //     mov EAX, EDX <- t1, t2
11859   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11860   //     mov t3, t4 <- EAX, EDX
11861   //     bz  newMBB
11862   //     result in out1, out2
11863   //     fallthrough -->nextMBB
11864
11865   const TargetRegisterClass *RC = &X86::GR32RegClass;
11866   const unsigned LoadOpc = X86::MOV32rm;
11867   const unsigned NotOpc = X86::NOT32r;
11868   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11869   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11870   MachineFunction::iterator MBBIter = MBB;
11871   ++MBBIter;
11872
11873   /// First build the CFG
11874   MachineFunction *F = MBB->getParent();
11875   MachineBasicBlock *thisMBB = MBB;
11876   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11877   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11878   F->insert(MBBIter, newMBB);
11879   F->insert(MBBIter, nextMBB);
11880
11881   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11882   nextMBB->splice(nextMBB->begin(), thisMBB,
11883                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11884                   thisMBB->end());
11885   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11886
11887   // Update thisMBB to fall through to newMBB
11888   thisMBB->addSuccessor(newMBB);
11889
11890   // newMBB jumps to itself and fall through to nextMBB
11891   newMBB->addSuccessor(nextMBB);
11892   newMBB->addSuccessor(newMBB);
11893
11894   DebugLoc dl = bInstr->getDebugLoc();
11895   // Insert instructions into newMBB based on incoming instruction
11896   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11897   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11898          "unexpected number of operands");
11899   MachineOperand& dest1Oper = bInstr->getOperand(0);
11900   MachineOperand& dest2Oper = bInstr->getOperand(1);
11901   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11902   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11903     argOpers[i] = &bInstr->getOperand(i+2);
11904
11905     // We use some of the operands multiple times, so conservatively just
11906     // clear any kill flags that might be present.
11907     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11908       argOpers[i]->setIsKill(false);
11909   }
11910
11911   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11912   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11913
11914   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11915   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11916   for (int i=0; i <= lastAddrIndx; ++i)
11917     (*MIB).addOperand(*argOpers[i]);
11918   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11919   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11920   // add 4 to displacement.
11921   for (int i=0; i <= lastAddrIndx-2; ++i)
11922     (*MIB).addOperand(*argOpers[i]);
11923   MachineOperand newOp3 = *(argOpers[3]);
11924   if (newOp3.isImm())
11925     newOp3.setImm(newOp3.getImm()+4);
11926   else
11927     newOp3.setOffset(newOp3.getOffset()+4);
11928   (*MIB).addOperand(newOp3);
11929   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11930
11931   // t3/4 are defined later, at the bottom of the loop
11932   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11933   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11934   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11935     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11936   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11937     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11938
11939   // The subsequent operations should be using the destination registers of
11940   // the PHI instructions.
11941   t1 = dest1Oper.getReg();
11942   t2 = dest2Oper.getReg();
11943
11944   int valArgIndx = lastAddrIndx + 1;
11945   assert((argOpers[valArgIndx]->isReg() ||
11946           argOpers[valArgIndx]->isImm()) &&
11947          "invalid operand");
11948   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11949   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11950   if (argOpers[valArgIndx]->isReg())
11951     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11952   else
11953     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11954   if (regOpcL != X86::MOV32rr)
11955     MIB.addReg(t1);
11956   (*MIB).addOperand(*argOpers[valArgIndx]);
11957   assert(argOpers[valArgIndx + 1]->isReg() ==
11958          argOpers[valArgIndx]->isReg());
11959   assert(argOpers[valArgIndx + 1]->isImm() ==
11960          argOpers[valArgIndx]->isImm());
11961   if (argOpers[valArgIndx + 1]->isReg())
11962     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11963   else
11964     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11965   if (regOpcH != X86::MOV32rr)
11966     MIB.addReg(t2);
11967   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11968
11969   unsigned t7, t8;
11970   if (Invert) {
11971     t7 = F->getRegInfo().createVirtualRegister(RC);
11972     t8 = F->getRegInfo().createVirtualRegister(RC);
11973     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11974     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11975   } else {
11976     t7 = t5;
11977     t8 = t6;
11978   }
11979
11980   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11981   MIB.addReg(t1);
11982   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11983   MIB.addReg(t2);
11984
11985   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11986   MIB.addReg(t7);
11987   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11988   MIB.addReg(t8);
11989
11990   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11991   for (int i=0; i <= lastAddrIndx; ++i)
11992     (*MIB).addOperand(*argOpers[i]);
11993
11994   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11995   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11996                     bInstr->memoperands_end());
11997
11998   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11999   MIB.addReg(X86::EAX);
12000   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
12001   MIB.addReg(X86::EDX);
12002
12003   // insert branch
12004   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12005
12006   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
12007   return nextMBB;
12008 }
12009
12010 // private utility function
12011 MachineBasicBlock *
12012 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
12013                                                       MachineBasicBlock *MBB,
12014                                                       unsigned cmovOpc) const {
12015   // For the atomic min/max operator, we generate
12016   //   thisMBB:
12017   //   newMBB:
12018   //     ld t1 = [min/max.addr]
12019   //     mov t2 = [min/max.val]
12020   //     cmp  t1, t2
12021   //     cmov[cond] t2 = t1
12022   //     mov EAX = t1
12023   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
12024   //     bz   newMBB
12025   //     fallthrough -->nextMBB
12026   //
12027   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12028   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12029   MachineFunction::iterator MBBIter = MBB;
12030   ++MBBIter;
12031
12032   /// First build the CFG
12033   MachineFunction *F = MBB->getParent();
12034   MachineBasicBlock *thisMBB = MBB;
12035   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
12036   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
12037   F->insert(MBBIter, newMBB);
12038   F->insert(MBBIter, nextMBB);
12039
12040   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
12041   nextMBB->splice(nextMBB->begin(), thisMBB,
12042                   llvm::next(MachineBasicBlock::iterator(mInstr)),
12043                   thisMBB->end());
12044   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12045
12046   // Update thisMBB to fall through to newMBB
12047   thisMBB->addSuccessor(newMBB);
12048
12049   // newMBB jumps to newMBB and fall through to nextMBB
12050   newMBB->addSuccessor(nextMBB);
12051   newMBB->addSuccessor(newMBB);
12052
12053   DebugLoc dl = mInstr->getDebugLoc();
12054   // Insert instructions into newMBB based on incoming instruction
12055   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
12056          "unexpected number of operands");
12057   MachineOperand& destOper = mInstr->getOperand(0);
12058   MachineOperand* argOpers[2 + X86::AddrNumOperands];
12059   int numArgs = mInstr->getNumOperands() - 1;
12060   for (int i=0; i < numArgs; ++i)
12061     argOpers[i] = &mInstr->getOperand(i+1);
12062
12063   // x86 address has 4 operands: base, index, scale, and displacement
12064   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
12065   int valArgIndx = lastAddrIndx + 1;
12066
12067   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12068   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
12069   for (int i=0; i <= lastAddrIndx; ++i)
12070     (*MIB).addOperand(*argOpers[i]);
12071
12072   // We only support register and immediate values
12073   assert((argOpers[valArgIndx]->isReg() ||
12074           argOpers[valArgIndx]->isImm()) &&
12075          "invalid operand");
12076
12077   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12078   if (argOpers[valArgIndx]->isReg())
12079     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
12080   else
12081     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
12082   (*MIB).addOperand(*argOpers[valArgIndx]);
12083
12084   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12085   MIB.addReg(t1);
12086
12087   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
12088   MIB.addReg(t1);
12089   MIB.addReg(t2);
12090
12091   // Generate movc
12092   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12093   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
12094   MIB.addReg(t2);
12095   MIB.addReg(t1);
12096
12097   // Cmp and exchange if none has modified the memory location
12098   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
12099   for (int i=0; i <= lastAddrIndx; ++i)
12100     (*MIB).addOperand(*argOpers[i]);
12101   MIB.addReg(t3);
12102   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12103   (*MIB).setMemRefs(mInstr->memoperands_begin(),
12104                     mInstr->memoperands_end());
12105
12106   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
12107   MIB.addReg(X86::EAX);
12108
12109   // insert branch
12110   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12111
12112   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
12113   return nextMBB;
12114 }
12115
12116 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12117 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12118 // in the .td file.
12119 MachineBasicBlock *
12120 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12121                             unsigned numArgs, bool memArg) const {
12122   assert(Subtarget->hasSSE42() &&
12123          "Target must have SSE4.2 or AVX features enabled");
12124
12125   DebugLoc dl = MI->getDebugLoc();
12126   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12127   unsigned Opc;
12128   if (!Subtarget->hasAVX()) {
12129     if (memArg)
12130       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12131     else
12132       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12133   } else {
12134     if (memArg)
12135       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12136     else
12137       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12138   }
12139
12140   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12141   for (unsigned i = 0; i < numArgs; ++i) {
12142     MachineOperand &Op = MI->getOperand(i+1);
12143     if (!(Op.isReg() && Op.isImplicit()))
12144       MIB.addOperand(Op);
12145   }
12146   BuildMI(*BB, MI, dl,
12147     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12148     .addReg(X86::XMM0);
12149
12150   MI->eraseFromParent();
12151   return BB;
12152 }
12153
12154 MachineBasicBlock *
12155 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12156   DebugLoc dl = MI->getDebugLoc();
12157   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12158
12159   // Address into RAX/EAX, other two args into ECX, EDX.
12160   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12161   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12162   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12163   for (int i = 0; i < X86::AddrNumOperands; ++i)
12164     MIB.addOperand(MI->getOperand(i));
12165
12166   unsigned ValOps = X86::AddrNumOperands;
12167   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12168     .addReg(MI->getOperand(ValOps).getReg());
12169   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12170     .addReg(MI->getOperand(ValOps+1).getReg());
12171
12172   // The instruction doesn't actually take any operands though.
12173   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12174
12175   MI->eraseFromParent(); // The pseudo is gone now.
12176   return BB;
12177 }
12178
12179 MachineBasicBlock *
12180 X86TargetLowering::EmitVAARG64WithCustomInserter(
12181                    MachineInstr *MI,
12182                    MachineBasicBlock *MBB) const {
12183   // Emit va_arg instruction on X86-64.
12184
12185   // Operands to this pseudo-instruction:
12186   // 0  ) Output        : destination address (reg)
12187   // 1-5) Input         : va_list address (addr, i64mem)
12188   // 6  ) ArgSize       : Size (in bytes) of vararg type
12189   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12190   // 8  ) Align         : Alignment of type
12191   // 9  ) EFLAGS (implicit-def)
12192
12193   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12194   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12195
12196   unsigned DestReg = MI->getOperand(0).getReg();
12197   MachineOperand &Base = MI->getOperand(1);
12198   MachineOperand &Scale = MI->getOperand(2);
12199   MachineOperand &Index = MI->getOperand(3);
12200   MachineOperand &Disp = MI->getOperand(4);
12201   MachineOperand &Segment = MI->getOperand(5);
12202   unsigned ArgSize = MI->getOperand(6).getImm();
12203   unsigned ArgMode = MI->getOperand(7).getImm();
12204   unsigned Align = MI->getOperand(8).getImm();
12205
12206   // Memory Reference
12207   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12208   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12209   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12210
12211   // Machine Information
12212   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12213   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12214   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12215   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12216   DebugLoc DL = MI->getDebugLoc();
12217
12218   // struct va_list {
12219   //   i32   gp_offset
12220   //   i32   fp_offset
12221   //   i64   overflow_area (address)
12222   //   i64   reg_save_area (address)
12223   // }
12224   // sizeof(va_list) = 24
12225   // alignment(va_list) = 8
12226
12227   unsigned TotalNumIntRegs = 6;
12228   unsigned TotalNumXMMRegs = 8;
12229   bool UseGPOffset = (ArgMode == 1);
12230   bool UseFPOffset = (ArgMode == 2);
12231   unsigned MaxOffset = TotalNumIntRegs * 8 +
12232                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12233
12234   /* Align ArgSize to a multiple of 8 */
12235   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12236   bool NeedsAlign = (Align > 8);
12237
12238   MachineBasicBlock *thisMBB = MBB;
12239   MachineBasicBlock *overflowMBB;
12240   MachineBasicBlock *offsetMBB;
12241   MachineBasicBlock *endMBB;
12242
12243   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12244   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12245   unsigned OffsetReg = 0;
12246
12247   if (!UseGPOffset && !UseFPOffset) {
12248     // If we only pull from the overflow region, we don't create a branch.
12249     // We don't need to alter control flow.
12250     OffsetDestReg = 0; // unused
12251     OverflowDestReg = DestReg;
12252
12253     offsetMBB = NULL;
12254     overflowMBB = thisMBB;
12255     endMBB = thisMBB;
12256   } else {
12257     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12258     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12259     // If not, pull from overflow_area. (branch to overflowMBB)
12260     //
12261     //       thisMBB
12262     //         |     .
12263     //         |        .
12264     //     offsetMBB   overflowMBB
12265     //         |        .
12266     //         |     .
12267     //        endMBB
12268
12269     // Registers for the PHI in endMBB
12270     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12271     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12272
12273     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12274     MachineFunction *MF = MBB->getParent();
12275     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12276     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12277     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12278
12279     MachineFunction::iterator MBBIter = MBB;
12280     ++MBBIter;
12281
12282     // Insert the new basic blocks
12283     MF->insert(MBBIter, offsetMBB);
12284     MF->insert(MBBIter, overflowMBB);
12285     MF->insert(MBBIter, endMBB);
12286
12287     // Transfer the remainder of MBB and its successor edges to endMBB.
12288     endMBB->splice(endMBB->begin(), thisMBB,
12289                     llvm::next(MachineBasicBlock::iterator(MI)),
12290                     thisMBB->end());
12291     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12292
12293     // Make offsetMBB and overflowMBB successors of thisMBB
12294     thisMBB->addSuccessor(offsetMBB);
12295     thisMBB->addSuccessor(overflowMBB);
12296
12297     // endMBB is a successor of both offsetMBB and overflowMBB
12298     offsetMBB->addSuccessor(endMBB);
12299     overflowMBB->addSuccessor(endMBB);
12300
12301     // Load the offset value into a register
12302     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12303     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12304       .addOperand(Base)
12305       .addOperand(Scale)
12306       .addOperand(Index)
12307       .addDisp(Disp, UseFPOffset ? 4 : 0)
12308       .addOperand(Segment)
12309       .setMemRefs(MMOBegin, MMOEnd);
12310
12311     // Check if there is enough room left to pull this argument.
12312     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12313       .addReg(OffsetReg)
12314       .addImm(MaxOffset + 8 - ArgSizeA8);
12315
12316     // Branch to "overflowMBB" if offset >= max
12317     // Fall through to "offsetMBB" otherwise
12318     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12319       .addMBB(overflowMBB);
12320   }
12321
12322   // In offsetMBB, emit code to use the reg_save_area.
12323   if (offsetMBB) {
12324     assert(OffsetReg != 0);
12325
12326     // Read the reg_save_area address.
12327     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12328     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12329       .addOperand(Base)
12330       .addOperand(Scale)
12331       .addOperand(Index)
12332       .addDisp(Disp, 16)
12333       .addOperand(Segment)
12334       .setMemRefs(MMOBegin, MMOEnd);
12335
12336     // Zero-extend the offset
12337     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12338       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12339         .addImm(0)
12340         .addReg(OffsetReg)
12341         .addImm(X86::sub_32bit);
12342
12343     // Add the offset to the reg_save_area to get the final address.
12344     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12345       .addReg(OffsetReg64)
12346       .addReg(RegSaveReg);
12347
12348     // Compute the offset for the next argument
12349     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12350     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12351       .addReg(OffsetReg)
12352       .addImm(UseFPOffset ? 16 : 8);
12353
12354     // Store it back into the va_list.
12355     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12356       .addOperand(Base)
12357       .addOperand(Scale)
12358       .addOperand(Index)
12359       .addDisp(Disp, UseFPOffset ? 4 : 0)
12360       .addOperand(Segment)
12361       .addReg(NextOffsetReg)
12362       .setMemRefs(MMOBegin, MMOEnd);
12363
12364     // Jump to endMBB
12365     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12366       .addMBB(endMBB);
12367   }
12368
12369   //
12370   // Emit code to use overflow area
12371   //
12372
12373   // Load the overflow_area address into a register.
12374   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12375   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12376     .addOperand(Base)
12377     .addOperand(Scale)
12378     .addOperand(Index)
12379     .addDisp(Disp, 8)
12380     .addOperand(Segment)
12381     .setMemRefs(MMOBegin, MMOEnd);
12382
12383   // If we need to align it, do so. Otherwise, just copy the address
12384   // to OverflowDestReg.
12385   if (NeedsAlign) {
12386     // Align the overflow address
12387     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12388     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12389
12390     // aligned_addr = (addr + (align-1)) & ~(align-1)
12391     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12392       .addReg(OverflowAddrReg)
12393       .addImm(Align-1);
12394
12395     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12396       .addReg(TmpReg)
12397       .addImm(~(uint64_t)(Align-1));
12398   } else {
12399     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12400       .addReg(OverflowAddrReg);
12401   }
12402
12403   // Compute the next overflow address after this argument.
12404   // (the overflow address should be kept 8-byte aligned)
12405   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12406   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12407     .addReg(OverflowDestReg)
12408     .addImm(ArgSizeA8);
12409
12410   // Store the new overflow address.
12411   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12412     .addOperand(Base)
12413     .addOperand(Scale)
12414     .addOperand(Index)
12415     .addDisp(Disp, 8)
12416     .addOperand(Segment)
12417     .addReg(NextAddrReg)
12418     .setMemRefs(MMOBegin, MMOEnd);
12419
12420   // If we branched, emit the PHI to the front of endMBB.
12421   if (offsetMBB) {
12422     BuildMI(*endMBB, endMBB->begin(), DL,
12423             TII->get(X86::PHI), DestReg)
12424       .addReg(OffsetDestReg).addMBB(offsetMBB)
12425       .addReg(OverflowDestReg).addMBB(overflowMBB);
12426   }
12427
12428   // Erase the pseudo instruction
12429   MI->eraseFromParent();
12430
12431   return endMBB;
12432 }
12433
12434 MachineBasicBlock *
12435 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12436                                                  MachineInstr *MI,
12437                                                  MachineBasicBlock *MBB) const {
12438   // Emit code to save XMM registers to the stack. The ABI says that the
12439   // number of registers to save is given in %al, so it's theoretically
12440   // possible to do an indirect jump trick to avoid saving all of them,
12441   // however this code takes a simpler approach and just executes all
12442   // of the stores if %al is non-zero. It's less code, and it's probably
12443   // easier on the hardware branch predictor, and stores aren't all that
12444   // expensive anyway.
12445
12446   // Create the new basic blocks. One block contains all the XMM stores,
12447   // and one block is the final destination regardless of whether any
12448   // stores were performed.
12449   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12450   MachineFunction *F = MBB->getParent();
12451   MachineFunction::iterator MBBIter = MBB;
12452   ++MBBIter;
12453   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12454   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12455   F->insert(MBBIter, XMMSaveMBB);
12456   F->insert(MBBIter, EndMBB);
12457
12458   // Transfer the remainder of MBB and its successor edges to EndMBB.
12459   EndMBB->splice(EndMBB->begin(), MBB,
12460                  llvm::next(MachineBasicBlock::iterator(MI)),
12461                  MBB->end());
12462   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12463
12464   // The original block will now fall through to the XMM save block.
12465   MBB->addSuccessor(XMMSaveMBB);
12466   // The XMMSaveMBB will fall through to the end block.
12467   XMMSaveMBB->addSuccessor(EndMBB);
12468
12469   // Now add the instructions.
12470   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12471   DebugLoc DL = MI->getDebugLoc();
12472
12473   unsigned CountReg = MI->getOperand(0).getReg();
12474   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12475   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12476
12477   if (!Subtarget->isTargetWin64()) {
12478     // If %al is 0, branch around the XMM save block.
12479     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12480     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12481     MBB->addSuccessor(EndMBB);
12482   }
12483
12484   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12485   // In the XMM save block, save all the XMM argument registers.
12486   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12487     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12488     MachineMemOperand *MMO =
12489       F->getMachineMemOperand(
12490           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12491         MachineMemOperand::MOStore,
12492         /*Size=*/16, /*Align=*/16);
12493     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12494       .addFrameIndex(RegSaveFrameIndex)
12495       .addImm(/*Scale=*/1)
12496       .addReg(/*IndexReg=*/0)
12497       .addImm(/*Disp=*/Offset)
12498       .addReg(/*Segment=*/0)
12499       .addReg(MI->getOperand(i).getReg())
12500       .addMemOperand(MMO);
12501   }
12502
12503   MI->eraseFromParent();   // The pseudo instruction is gone now.
12504
12505   return EndMBB;
12506 }
12507
12508 // The EFLAGS operand of SelectItr might be missing a kill marker
12509 // because there were multiple uses of EFLAGS, and ISel didn't know
12510 // which to mark. Figure out whether SelectItr should have had a
12511 // kill marker, and set it if it should. Returns the correct kill
12512 // marker value.
12513 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12514                                      MachineBasicBlock* BB,
12515                                      const TargetRegisterInfo* TRI) {
12516   // Scan forward through BB for a use/def of EFLAGS.
12517   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12518   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12519     const MachineInstr& mi = *miI;
12520     if (mi.readsRegister(X86::EFLAGS))
12521       return false;
12522     if (mi.definesRegister(X86::EFLAGS))
12523       break; // Should have kill-flag - update below.
12524   }
12525
12526   // If we hit the end of the block, check whether EFLAGS is live into a
12527   // successor.
12528   if (miI == BB->end()) {
12529     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12530                                           sEnd = BB->succ_end();
12531          sItr != sEnd; ++sItr) {
12532       MachineBasicBlock* succ = *sItr;
12533       if (succ->isLiveIn(X86::EFLAGS))
12534         return false;
12535     }
12536   }
12537
12538   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12539   // out. SelectMI should have a kill flag on EFLAGS.
12540   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12541   return true;
12542 }
12543
12544 MachineBasicBlock *
12545 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12546                                      MachineBasicBlock *BB) const {
12547   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12548   DebugLoc DL = MI->getDebugLoc();
12549
12550   // To "insert" a SELECT_CC instruction, we actually have to insert the
12551   // diamond control-flow pattern.  The incoming instruction knows the
12552   // destination vreg to set, the condition code register to branch on, the
12553   // true/false values to select between, and a branch opcode to use.
12554   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12555   MachineFunction::iterator It = BB;
12556   ++It;
12557
12558   //  thisMBB:
12559   //  ...
12560   //   TrueVal = ...
12561   //   cmpTY ccX, r1, r2
12562   //   bCC copy1MBB
12563   //   fallthrough --> copy0MBB
12564   MachineBasicBlock *thisMBB = BB;
12565   MachineFunction *F = BB->getParent();
12566   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12567   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12568   F->insert(It, copy0MBB);
12569   F->insert(It, sinkMBB);
12570
12571   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12572   // live into the sink and copy blocks.
12573   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12574   if (!MI->killsRegister(X86::EFLAGS) &&
12575       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12576     copy0MBB->addLiveIn(X86::EFLAGS);
12577     sinkMBB->addLiveIn(X86::EFLAGS);
12578   }
12579
12580   // Transfer the remainder of BB and its successor edges to sinkMBB.
12581   sinkMBB->splice(sinkMBB->begin(), BB,
12582                   llvm::next(MachineBasicBlock::iterator(MI)),
12583                   BB->end());
12584   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12585
12586   // Add the true and fallthrough blocks as its successors.
12587   BB->addSuccessor(copy0MBB);
12588   BB->addSuccessor(sinkMBB);
12589
12590   // Create the conditional branch instruction.
12591   unsigned Opc =
12592     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12593   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12594
12595   //  copy0MBB:
12596   //   %FalseValue = ...
12597   //   # fallthrough to sinkMBB
12598   copy0MBB->addSuccessor(sinkMBB);
12599
12600   //  sinkMBB:
12601   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12602   //  ...
12603   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12604           TII->get(X86::PHI), MI->getOperand(0).getReg())
12605     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12606     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12607
12608   MI->eraseFromParent();   // The pseudo instruction is gone now.
12609   return sinkMBB;
12610 }
12611
12612 MachineBasicBlock *
12613 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12614                                         bool Is64Bit) const {
12615   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12616   DebugLoc DL = MI->getDebugLoc();
12617   MachineFunction *MF = BB->getParent();
12618   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12619
12620   assert(getTargetMachine().Options.EnableSegmentedStacks);
12621
12622   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12623   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12624
12625   // BB:
12626   //  ... [Till the alloca]
12627   // If stacklet is not large enough, jump to mallocMBB
12628   //
12629   // bumpMBB:
12630   //  Allocate by subtracting from RSP
12631   //  Jump to continueMBB
12632   //
12633   // mallocMBB:
12634   //  Allocate by call to runtime
12635   //
12636   // continueMBB:
12637   //  ...
12638   //  [rest of original BB]
12639   //
12640
12641   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12642   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12643   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12644
12645   MachineRegisterInfo &MRI = MF->getRegInfo();
12646   const TargetRegisterClass *AddrRegClass =
12647     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12648
12649   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12650     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12651     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12652     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12653     sizeVReg = MI->getOperand(1).getReg(),
12654     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12655
12656   MachineFunction::iterator MBBIter = BB;
12657   ++MBBIter;
12658
12659   MF->insert(MBBIter, bumpMBB);
12660   MF->insert(MBBIter, mallocMBB);
12661   MF->insert(MBBIter, continueMBB);
12662
12663   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12664                       (MachineBasicBlock::iterator(MI)), BB->end());
12665   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12666
12667   // Add code to the main basic block to check if the stack limit has been hit,
12668   // and if so, jump to mallocMBB otherwise to bumpMBB.
12669   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12670   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12671     .addReg(tmpSPVReg).addReg(sizeVReg);
12672   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12673     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12674     .addReg(SPLimitVReg);
12675   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12676
12677   // bumpMBB simply decreases the stack pointer, since we know the current
12678   // stacklet has enough space.
12679   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12680     .addReg(SPLimitVReg);
12681   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12682     .addReg(SPLimitVReg);
12683   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12684
12685   // Calls into a routine in libgcc to allocate more space from the heap.
12686   const uint32_t *RegMask =
12687     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12688   if (Is64Bit) {
12689     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12690       .addReg(sizeVReg);
12691     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12692       .addExternalSymbol("__morestack_allocate_stack_space")
12693       .addRegMask(RegMask)
12694       .addReg(X86::RDI, RegState::Implicit)
12695       .addReg(X86::RAX, RegState::ImplicitDefine);
12696   } else {
12697     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12698       .addImm(12);
12699     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12700     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12701       .addExternalSymbol("__morestack_allocate_stack_space")
12702       .addRegMask(RegMask)
12703       .addReg(X86::EAX, RegState::ImplicitDefine);
12704   }
12705
12706   if (!Is64Bit)
12707     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12708       .addImm(16);
12709
12710   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12711     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12712   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12713
12714   // Set up the CFG correctly.
12715   BB->addSuccessor(bumpMBB);
12716   BB->addSuccessor(mallocMBB);
12717   mallocMBB->addSuccessor(continueMBB);
12718   bumpMBB->addSuccessor(continueMBB);
12719
12720   // Take care of the PHI nodes.
12721   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12722           MI->getOperand(0).getReg())
12723     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12724     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12725
12726   // Delete the original pseudo instruction.
12727   MI->eraseFromParent();
12728
12729   // And we're done.
12730   return continueMBB;
12731 }
12732
12733 MachineBasicBlock *
12734 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12735                                           MachineBasicBlock *BB) const {
12736   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12737   DebugLoc DL = MI->getDebugLoc();
12738
12739   assert(!Subtarget->isTargetEnvMacho());
12740
12741   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12742   // non-trivial part is impdef of ESP.
12743
12744   if (Subtarget->isTargetWin64()) {
12745     if (Subtarget->isTargetCygMing()) {
12746       // ___chkstk(Mingw64):
12747       // Clobbers R10, R11, RAX and EFLAGS.
12748       // Updates RSP.
12749       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12750         .addExternalSymbol("___chkstk")
12751         .addReg(X86::RAX, RegState::Implicit)
12752         .addReg(X86::RSP, RegState::Implicit)
12753         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12754         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12755         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12756     } else {
12757       // __chkstk(MSVCRT): does not update stack pointer.
12758       // Clobbers R10, R11 and EFLAGS.
12759       // FIXME: RAX(allocated size) might be reused and not killed.
12760       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12761         .addExternalSymbol("__chkstk")
12762         .addReg(X86::RAX, RegState::Implicit)
12763         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12764       // RAX has the offset to subtracted from RSP.
12765       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12766         .addReg(X86::RSP)
12767         .addReg(X86::RAX);
12768     }
12769   } else {
12770     const char *StackProbeSymbol =
12771       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12772
12773     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12774       .addExternalSymbol(StackProbeSymbol)
12775       .addReg(X86::EAX, RegState::Implicit)
12776       .addReg(X86::ESP, RegState::Implicit)
12777       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12778       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12779       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12780   }
12781
12782   MI->eraseFromParent();   // The pseudo instruction is gone now.
12783   return BB;
12784 }
12785
12786 MachineBasicBlock *
12787 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12788                                       MachineBasicBlock *BB) const {
12789   // This is pretty easy.  We're taking the value that we received from
12790   // our load from the relocation, sticking it in either RDI (x86-64)
12791   // or EAX and doing an indirect call.  The return value will then
12792   // be in the normal return register.
12793   const X86InstrInfo *TII
12794     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12795   DebugLoc DL = MI->getDebugLoc();
12796   MachineFunction *F = BB->getParent();
12797
12798   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12799   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12800
12801   // Get a register mask for the lowered call.
12802   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12803   // proper register mask.
12804   const uint32_t *RegMask =
12805     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12806   if (Subtarget->is64Bit()) {
12807     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12808                                       TII->get(X86::MOV64rm), X86::RDI)
12809     .addReg(X86::RIP)
12810     .addImm(0).addReg(0)
12811     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12812                       MI->getOperand(3).getTargetFlags())
12813     .addReg(0);
12814     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12815     addDirectMem(MIB, X86::RDI);
12816     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12817   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12818     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12819                                       TII->get(X86::MOV32rm), X86::EAX)
12820     .addReg(0)
12821     .addImm(0).addReg(0)
12822     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12823                       MI->getOperand(3).getTargetFlags())
12824     .addReg(0);
12825     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12826     addDirectMem(MIB, X86::EAX);
12827     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12828   } else {
12829     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12830                                       TII->get(X86::MOV32rm), X86::EAX)
12831     .addReg(TII->getGlobalBaseReg(F))
12832     .addImm(0).addReg(0)
12833     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12834                       MI->getOperand(3).getTargetFlags())
12835     .addReg(0);
12836     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12837     addDirectMem(MIB, X86::EAX);
12838     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12839   }
12840
12841   MI->eraseFromParent(); // The pseudo instruction is gone now.
12842   return BB;
12843 }
12844
12845 MachineBasicBlock *
12846 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12847                                                MachineBasicBlock *BB) const {
12848   switch (MI->getOpcode()) {
12849   default: llvm_unreachable("Unexpected instr type to insert");
12850   case X86::TAILJMPd64:
12851   case X86::TAILJMPr64:
12852   case X86::TAILJMPm64:
12853     llvm_unreachable("TAILJMP64 would not be touched here.");
12854   case X86::TCRETURNdi64:
12855   case X86::TCRETURNri64:
12856   case X86::TCRETURNmi64:
12857     return BB;
12858   case X86::WIN_ALLOCA:
12859     return EmitLoweredWinAlloca(MI, BB);
12860   case X86::SEG_ALLOCA_32:
12861     return EmitLoweredSegAlloca(MI, BB, false);
12862   case X86::SEG_ALLOCA_64:
12863     return EmitLoweredSegAlloca(MI, BB, true);
12864   case X86::TLSCall_32:
12865   case X86::TLSCall_64:
12866     return EmitLoweredTLSCall(MI, BB);
12867   case X86::CMOV_GR8:
12868   case X86::CMOV_FR32:
12869   case X86::CMOV_FR64:
12870   case X86::CMOV_V4F32:
12871   case X86::CMOV_V2F64:
12872   case X86::CMOV_V2I64:
12873   case X86::CMOV_V8F32:
12874   case X86::CMOV_V4F64:
12875   case X86::CMOV_V4I64:
12876   case X86::CMOV_GR16:
12877   case X86::CMOV_GR32:
12878   case X86::CMOV_RFP32:
12879   case X86::CMOV_RFP64:
12880   case X86::CMOV_RFP80:
12881     return EmitLoweredSelect(MI, BB);
12882
12883   case X86::FP32_TO_INT16_IN_MEM:
12884   case X86::FP32_TO_INT32_IN_MEM:
12885   case X86::FP32_TO_INT64_IN_MEM:
12886   case X86::FP64_TO_INT16_IN_MEM:
12887   case X86::FP64_TO_INT32_IN_MEM:
12888   case X86::FP64_TO_INT64_IN_MEM:
12889   case X86::FP80_TO_INT16_IN_MEM:
12890   case X86::FP80_TO_INT32_IN_MEM:
12891   case X86::FP80_TO_INT64_IN_MEM: {
12892     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12893     DebugLoc DL = MI->getDebugLoc();
12894
12895     // Change the floating point control register to use "round towards zero"
12896     // mode when truncating to an integer value.
12897     MachineFunction *F = BB->getParent();
12898     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12899     addFrameReference(BuildMI(*BB, MI, DL,
12900                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12901
12902     // Load the old value of the high byte of the control word...
12903     unsigned OldCW =
12904       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12905     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12906                       CWFrameIdx);
12907
12908     // Set the high part to be round to zero...
12909     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12910       .addImm(0xC7F);
12911
12912     // Reload the modified control word now...
12913     addFrameReference(BuildMI(*BB, MI, DL,
12914                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12915
12916     // Restore the memory image of control word to original value
12917     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12918       .addReg(OldCW);
12919
12920     // Get the X86 opcode to use.
12921     unsigned Opc;
12922     switch (MI->getOpcode()) {
12923     default: llvm_unreachable("illegal opcode!");
12924     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12925     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12926     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12927     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12928     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12929     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12930     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12931     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12932     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12933     }
12934
12935     X86AddressMode AM;
12936     MachineOperand &Op = MI->getOperand(0);
12937     if (Op.isReg()) {
12938       AM.BaseType = X86AddressMode::RegBase;
12939       AM.Base.Reg = Op.getReg();
12940     } else {
12941       AM.BaseType = X86AddressMode::FrameIndexBase;
12942       AM.Base.FrameIndex = Op.getIndex();
12943     }
12944     Op = MI->getOperand(1);
12945     if (Op.isImm())
12946       AM.Scale = Op.getImm();
12947     Op = MI->getOperand(2);
12948     if (Op.isImm())
12949       AM.IndexReg = Op.getImm();
12950     Op = MI->getOperand(3);
12951     if (Op.isGlobal()) {
12952       AM.GV = Op.getGlobal();
12953     } else {
12954       AM.Disp = Op.getImm();
12955     }
12956     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12957                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12958
12959     // Reload the original control word now.
12960     addFrameReference(BuildMI(*BB, MI, DL,
12961                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12962
12963     MI->eraseFromParent();   // The pseudo instruction is gone now.
12964     return BB;
12965   }
12966     // String/text processing lowering.
12967   case X86::PCMPISTRM128REG:
12968   case X86::VPCMPISTRM128REG:
12969   case X86::PCMPISTRM128MEM:
12970   case X86::VPCMPISTRM128MEM:
12971   case X86::PCMPESTRM128REG:
12972   case X86::VPCMPESTRM128REG:
12973   case X86::PCMPESTRM128MEM:
12974   case X86::VPCMPESTRM128MEM: {
12975     unsigned NumArgs;
12976     bool MemArg;
12977     switch (MI->getOpcode()) {
12978     default: llvm_unreachable("illegal opcode!");
12979     case X86::PCMPISTRM128REG:
12980     case X86::VPCMPISTRM128REG:
12981       NumArgs = 3; MemArg = false; break;
12982     case X86::PCMPISTRM128MEM:
12983     case X86::VPCMPISTRM128MEM:
12984       NumArgs = 3; MemArg = true; break;
12985     case X86::PCMPESTRM128REG:
12986     case X86::VPCMPESTRM128REG:
12987       NumArgs = 5; MemArg = false; break;
12988     case X86::PCMPESTRM128MEM:
12989     case X86::VPCMPESTRM128MEM:
12990       NumArgs = 5; MemArg = true; break;
12991     }
12992     return EmitPCMP(MI, BB, NumArgs, MemArg);
12993   }
12994
12995     // Thread synchronization.
12996   case X86::MONITOR:
12997     return EmitMonitor(MI, BB);
12998
12999     // Atomic Lowering.
13000   case X86::ATOMMIN32:
13001   case X86::ATOMMAX32:
13002   case X86::ATOMUMIN32:
13003   case X86::ATOMUMAX32:
13004   case X86::ATOMMIN16:
13005   case X86::ATOMMAX16:
13006   case X86::ATOMUMIN16:
13007   case X86::ATOMUMAX16:
13008   case X86::ATOMMIN64:
13009   case X86::ATOMMAX64:
13010   case X86::ATOMUMIN64:
13011   case X86::ATOMUMAX64: {
13012     unsigned Opc;
13013     switch (MI->getOpcode()) {
13014     default: llvm_unreachable("illegal opcode!");
13015     case X86::ATOMMIN32:  Opc = X86::CMOVL32rr; break;
13016     case X86::ATOMMAX32:  Opc = X86::CMOVG32rr; break;
13017     case X86::ATOMUMIN32: Opc = X86::CMOVB32rr; break;
13018     case X86::ATOMUMAX32: Opc = X86::CMOVA32rr; break;
13019     case X86::ATOMMIN16:  Opc = X86::CMOVL16rr; break;
13020     case X86::ATOMMAX16:  Opc = X86::CMOVG16rr; break;
13021     case X86::ATOMUMIN16: Opc = X86::CMOVB16rr; break;
13022     case X86::ATOMUMAX16: Opc = X86::CMOVA16rr; break;
13023     case X86::ATOMMIN64:  Opc = X86::CMOVL64rr; break;
13024     case X86::ATOMMAX64:  Opc = X86::CMOVG64rr; break;
13025     case X86::ATOMUMIN64: Opc = X86::CMOVB64rr; break;
13026     case X86::ATOMUMAX64: Opc = X86::CMOVA64rr; break;
13027     // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
13028     }
13029     return EmitAtomicMinMaxWithCustomInserter(MI, BB, Opc);
13030   }
13031
13032   case X86::ATOMAND32:
13033   case X86::ATOMOR32:
13034   case X86::ATOMXOR32:
13035   case X86::ATOMNAND32: {
13036     bool Invert = false;
13037     unsigned RegOpc, ImmOpc;
13038     switch (MI->getOpcode()) {
13039     default: llvm_unreachable("illegal opcode!");
13040     case X86::ATOMAND32:
13041       RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; break;
13042     case X86::ATOMOR32:
13043       RegOpc = X86::OR32rr;  ImmOpc = X86::OR32ri; break;
13044     case X86::ATOMXOR32:
13045       RegOpc = X86::XOR32rr; ImmOpc = X86::XOR32ri; break;
13046     case X86::ATOMNAND32:
13047       RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; Invert = true; break;
13048     }
13049     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13050                                                X86::MOV32rm, X86::LCMPXCHG32,
13051                                                X86::NOT32r, X86::EAX,
13052                                                &X86::GR32RegClass, Invert);
13053   }
13054
13055   case X86::ATOMAND16:
13056   case X86::ATOMOR16:
13057   case X86::ATOMXOR16:
13058   case X86::ATOMNAND16: {
13059     bool Invert = false;
13060     unsigned RegOpc, ImmOpc;
13061     switch (MI->getOpcode()) {
13062     default: llvm_unreachable("illegal opcode!");
13063     case X86::ATOMAND16:
13064       RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; break;
13065     case X86::ATOMOR16:
13066       RegOpc = X86::OR16rr;  ImmOpc = X86::OR16ri; break;
13067     case X86::ATOMXOR16:
13068       RegOpc = X86::XOR16rr; ImmOpc = X86::XOR16ri; break;
13069     case X86::ATOMNAND16:
13070       RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; Invert = true; break;
13071     }
13072     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13073                                                X86::MOV16rm, X86::LCMPXCHG16,
13074                                                X86::NOT16r, X86::AX,
13075                                                &X86::GR16RegClass, Invert);
13076   }
13077
13078   case X86::ATOMAND8:
13079   case X86::ATOMOR8:
13080   case X86::ATOMXOR8:
13081   case X86::ATOMNAND8: {
13082     bool Invert = false;
13083     unsigned RegOpc, ImmOpc;
13084     switch (MI->getOpcode()) {
13085     default: llvm_unreachable("illegal opcode!");
13086     case X86::ATOMAND8:
13087       RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; break;
13088     case X86::ATOMOR8:
13089       RegOpc = X86::OR8rr;  ImmOpc = X86::OR8ri; break;
13090     case X86::ATOMXOR8:
13091       RegOpc = X86::XOR8rr; ImmOpc = X86::XOR8ri; break;
13092     case X86::ATOMNAND8:
13093       RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; Invert = true; break;
13094     }
13095     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13096                                                X86::MOV8rm, X86::LCMPXCHG8,
13097                                                X86::NOT8r, X86::AL,
13098                                                &X86::GR8RegClass, Invert);
13099   }
13100
13101   // This group is for 64-bit host.
13102   case X86::ATOMAND64:
13103   case X86::ATOMOR64:
13104   case X86::ATOMXOR64:
13105   case X86::ATOMNAND64: {
13106     bool Invert = false;
13107     unsigned RegOpc, ImmOpc;
13108     switch (MI->getOpcode()) {
13109     default: llvm_unreachable("illegal opcode!");
13110     case X86::ATOMAND64:
13111       RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; break;
13112     case X86::ATOMOR64:
13113       RegOpc = X86::OR64rr;  ImmOpc = X86::OR64ri32; break;
13114     case X86::ATOMXOR64:
13115       RegOpc = X86::XOR64rr; ImmOpc = X86::XOR64ri32; break;
13116     case X86::ATOMNAND64:
13117       RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; Invert = true; break;
13118     }
13119     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13120                                                X86::MOV64rm, X86::LCMPXCHG64,
13121                                                X86::NOT64r, X86::RAX,
13122                                                &X86::GR64RegClass, Invert);
13123   }
13124
13125   // This group does 64-bit operations on a 32-bit host.
13126   case X86::ATOMAND6432:
13127   case X86::ATOMOR6432:
13128   case X86::ATOMXOR6432:
13129   case X86::ATOMNAND6432:
13130   case X86::ATOMADD6432:
13131   case X86::ATOMSUB6432:
13132   case X86::ATOMSWAP6432: {
13133     bool Invert = false;
13134     unsigned RegOpcL, RegOpcH, ImmOpcL, ImmOpcH;
13135     switch (MI->getOpcode()) {
13136     default: llvm_unreachable("illegal opcode!");
13137     case X86::ATOMAND6432:
13138       RegOpcL = RegOpcH = X86::AND32rr;
13139       ImmOpcL = ImmOpcH = X86::AND32ri;
13140       break;
13141     case X86::ATOMOR6432:
13142       RegOpcL = RegOpcH = X86::OR32rr;
13143       ImmOpcL = ImmOpcH = X86::OR32ri;
13144       break;
13145     case X86::ATOMXOR6432:
13146       RegOpcL = RegOpcH = X86::XOR32rr;
13147       ImmOpcL = ImmOpcH = X86::XOR32ri;
13148       break;
13149     case X86::ATOMNAND6432:
13150       RegOpcL = RegOpcH = X86::AND32rr;
13151       ImmOpcL = ImmOpcH = X86::AND32ri;
13152       Invert = true;
13153       break;
13154     case X86::ATOMADD6432:
13155       RegOpcL = X86::ADD32rr; RegOpcH = X86::ADC32rr;
13156       ImmOpcL = X86::ADD32ri; ImmOpcH = X86::ADC32ri;
13157       break;
13158     case X86::ATOMSUB6432:
13159       RegOpcL = X86::SUB32rr; RegOpcH = X86::SBB32rr;
13160       ImmOpcL = X86::SUB32ri; ImmOpcH = X86::SBB32ri;
13161       break;
13162     case X86::ATOMSWAP6432:
13163       RegOpcL = RegOpcH = X86::MOV32rr;
13164       ImmOpcL = ImmOpcH = X86::MOV32ri;
13165       break;
13166     }
13167     return EmitAtomicBit6432WithCustomInserter(MI, BB, RegOpcL, RegOpcH,
13168                                                ImmOpcL, ImmOpcH, Invert);
13169   }
13170
13171   case X86::VASTART_SAVE_XMM_REGS:
13172     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13173
13174   case X86::VAARG_64:
13175     return EmitVAARG64WithCustomInserter(MI, BB);
13176   }
13177 }
13178
13179 //===----------------------------------------------------------------------===//
13180 //                           X86 Optimization Hooks
13181 //===----------------------------------------------------------------------===//
13182
13183 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13184                                                        APInt &KnownZero,
13185                                                        APInt &KnownOne,
13186                                                        const SelectionDAG &DAG,
13187                                                        unsigned Depth) const {
13188   unsigned BitWidth = KnownZero.getBitWidth();
13189   unsigned Opc = Op.getOpcode();
13190   assert((Opc >= ISD::BUILTIN_OP_END ||
13191           Opc == ISD::INTRINSIC_WO_CHAIN ||
13192           Opc == ISD::INTRINSIC_W_CHAIN ||
13193           Opc == ISD::INTRINSIC_VOID) &&
13194          "Should use MaskedValueIsZero if you don't know whether Op"
13195          " is a target node!");
13196
13197   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13198   switch (Opc) {
13199   default: break;
13200   case X86ISD::ADD:
13201   case X86ISD::SUB:
13202   case X86ISD::ADC:
13203   case X86ISD::SBB:
13204   case X86ISD::SMUL:
13205   case X86ISD::UMUL:
13206   case X86ISD::INC:
13207   case X86ISD::DEC:
13208   case X86ISD::OR:
13209   case X86ISD::XOR:
13210   case X86ISD::AND:
13211     // These nodes' second result is a boolean.
13212     if (Op.getResNo() == 0)
13213       break;
13214     // Fallthrough
13215   case X86ISD::SETCC:
13216     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13217     break;
13218   case ISD::INTRINSIC_WO_CHAIN: {
13219     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13220     unsigned NumLoBits = 0;
13221     switch (IntId) {
13222     default: break;
13223     case Intrinsic::x86_sse_movmsk_ps:
13224     case Intrinsic::x86_avx_movmsk_ps_256:
13225     case Intrinsic::x86_sse2_movmsk_pd:
13226     case Intrinsic::x86_avx_movmsk_pd_256:
13227     case Intrinsic::x86_mmx_pmovmskb:
13228     case Intrinsic::x86_sse2_pmovmskb_128:
13229     case Intrinsic::x86_avx2_pmovmskb: {
13230       // High bits of movmskp{s|d}, pmovmskb are known zero.
13231       switch (IntId) {
13232         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13233         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13234         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13235         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13236         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13237         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13238         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13239         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13240       }
13241       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13242       break;
13243     }
13244     }
13245     break;
13246   }
13247   }
13248 }
13249
13250 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13251                                                          unsigned Depth) const {
13252   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13253   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13254     return Op.getValueType().getScalarType().getSizeInBits();
13255
13256   // Fallback case.
13257   return 1;
13258 }
13259
13260 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13261 /// node is a GlobalAddress + offset.
13262 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13263                                        const GlobalValue* &GA,
13264                                        int64_t &Offset) const {
13265   if (N->getOpcode() == X86ISD::Wrapper) {
13266     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13267       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13268       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13269       return true;
13270     }
13271   }
13272   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13273 }
13274
13275 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13276 /// same as extracting the high 128-bit part of 256-bit vector and then
13277 /// inserting the result into the low part of a new 256-bit vector
13278 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13279   EVT VT = SVOp->getValueType(0);
13280   unsigned NumElems = VT.getVectorNumElements();
13281
13282   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13283   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13284     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13285         SVOp->getMaskElt(j) >= 0)
13286       return false;
13287
13288   return true;
13289 }
13290
13291 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13292 /// same as extracting the low 128-bit part of 256-bit vector and then
13293 /// inserting the result into the high part of a new 256-bit vector
13294 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13295   EVT VT = SVOp->getValueType(0);
13296   unsigned NumElems = VT.getVectorNumElements();
13297
13298   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13299   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13300     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13301         SVOp->getMaskElt(j) >= 0)
13302       return false;
13303
13304   return true;
13305 }
13306
13307 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13308 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13309                                         TargetLowering::DAGCombinerInfo &DCI,
13310                                         const X86Subtarget* Subtarget) {
13311   DebugLoc dl = N->getDebugLoc();
13312   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13313   SDValue V1 = SVOp->getOperand(0);
13314   SDValue V2 = SVOp->getOperand(1);
13315   EVT VT = SVOp->getValueType(0);
13316   unsigned NumElems = VT.getVectorNumElements();
13317
13318   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13319       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13320     //
13321     //                   0,0,0,...
13322     //                      |
13323     //    V      UNDEF    BUILD_VECTOR    UNDEF
13324     //     \      /           \           /
13325     //  CONCAT_VECTOR         CONCAT_VECTOR
13326     //         \                  /
13327     //          \                /
13328     //          RESULT: V + zero extended
13329     //
13330     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13331         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13332         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13333       return SDValue();
13334
13335     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13336       return SDValue();
13337
13338     // To match the shuffle mask, the first half of the mask should
13339     // be exactly the first vector, and all the rest a splat with the
13340     // first element of the second one.
13341     for (unsigned i = 0; i != NumElems/2; ++i)
13342       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13343           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13344         return SDValue();
13345
13346     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13347     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13348       if (Ld->hasNUsesOfValue(1, 0)) {
13349         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13350         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13351         SDValue ResNode =
13352           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13353                                   Ld->getMemoryVT(),
13354                                   Ld->getPointerInfo(),
13355                                   Ld->getAlignment(),
13356                                   false/*isVolatile*/, true/*ReadMem*/,
13357                                   false/*WriteMem*/);
13358         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13359       }
13360     }
13361
13362     // Emit a zeroed vector and insert the desired subvector on its
13363     // first half.
13364     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13365     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13366     return DCI.CombineTo(N, InsV);
13367   }
13368
13369   //===--------------------------------------------------------------------===//
13370   // Combine some shuffles into subvector extracts and inserts:
13371   //
13372
13373   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13374   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13375     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13376     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13377     return DCI.CombineTo(N, InsV);
13378   }
13379
13380   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13381   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13382     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13383     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13384     return DCI.CombineTo(N, InsV);
13385   }
13386
13387   return SDValue();
13388 }
13389
13390 /// PerformShuffleCombine - Performs several different shuffle combines.
13391 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13392                                      TargetLowering::DAGCombinerInfo &DCI,
13393                                      const X86Subtarget *Subtarget) {
13394   DebugLoc dl = N->getDebugLoc();
13395   EVT VT = N->getValueType(0);
13396
13397   // Don't create instructions with illegal types after legalize types has run.
13398   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13399   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13400     return SDValue();
13401
13402   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13403   if (Subtarget->hasAVX() && VT.is256BitVector() &&
13404       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13405     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13406
13407   // Only handle 128 wide vector from here on.
13408   if (!VT.is128BitVector())
13409     return SDValue();
13410
13411   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13412   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13413   // consecutive, non-overlapping, and in the right order.
13414   SmallVector<SDValue, 16> Elts;
13415   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13416     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13417
13418   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13419 }
13420
13421
13422 /// DCI, PerformTruncateCombine - Converts truncate operation to
13423 /// a sequence of vector shuffle operations.
13424 /// It is possible when we truncate 256-bit vector to 128-bit vector
13425
13426 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13427                                                   DAGCombinerInfo &DCI) const {
13428   if (!DCI.isBeforeLegalizeOps())
13429     return SDValue();
13430
13431   if (!Subtarget->hasAVX())
13432     return SDValue();
13433
13434   EVT VT = N->getValueType(0);
13435   SDValue Op = N->getOperand(0);
13436   EVT OpVT = Op.getValueType();
13437   DebugLoc dl = N->getDebugLoc();
13438
13439   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13440
13441     if (Subtarget->hasAVX2()) {
13442       // AVX2: v4i64 -> v4i32
13443
13444       // VPERMD
13445       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13446
13447       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13448       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13449                                 ShufMask);
13450
13451       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13452                          DAG.getIntPtrConstant(0));
13453     }
13454
13455     // AVX: v4i64 -> v4i32
13456     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13457                                DAG.getIntPtrConstant(0));
13458
13459     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13460                                DAG.getIntPtrConstant(2));
13461
13462     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13463     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13464
13465     // PSHUFD
13466     static const int ShufMask1[] = {0, 2, 0, 0};
13467
13468     SDValue Undef = DAG.getUNDEF(VT);
13469     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13470     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13471
13472     // MOVLHPS
13473     static const int ShufMask2[] = {0, 1, 4, 5};
13474
13475     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13476   }
13477
13478   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13479
13480     if (Subtarget->hasAVX2()) {
13481       // AVX2: v8i32 -> v8i16
13482
13483       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13484
13485       // PSHUFB
13486       SmallVector<SDValue,32> pshufbMask;
13487       for (unsigned i = 0; i < 2; ++i) {
13488         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13489         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13490         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13491         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13492         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13493         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13494         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13495         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13496         for (unsigned j = 0; j < 8; ++j)
13497           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13498       }
13499       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13500                                &pshufbMask[0], 32);
13501       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13502
13503       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13504
13505       static const int ShufMask[] = {0,  2,  -1,  -1};
13506       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13507                                 &ShufMask[0]);
13508
13509       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13510                        DAG.getIntPtrConstant(0));
13511
13512       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13513     }
13514
13515     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13516                                DAG.getIntPtrConstant(0));
13517
13518     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13519                                DAG.getIntPtrConstant(4));
13520
13521     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13522     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13523
13524     // PSHUFB
13525     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13526                                    -1, -1, -1, -1, -1, -1, -1, -1};
13527
13528     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13529     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13530     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13531
13532     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13533     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13534
13535     // MOVLHPS
13536     static const int ShufMask2[] = {0, 1, 4, 5};
13537
13538     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13539     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13540   }
13541
13542   return SDValue();
13543 }
13544
13545 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13546 /// specific shuffle of a load can be folded into a single element load.
13547 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13548 /// shuffles have been customed lowered so we need to handle those here.
13549 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13550                                          TargetLowering::DAGCombinerInfo &DCI) {
13551   if (DCI.isBeforeLegalizeOps())
13552     return SDValue();
13553
13554   SDValue InVec = N->getOperand(0);
13555   SDValue EltNo = N->getOperand(1);
13556
13557   if (!isa<ConstantSDNode>(EltNo))
13558     return SDValue();
13559
13560   EVT VT = InVec.getValueType();
13561
13562   bool HasShuffleIntoBitcast = false;
13563   if (InVec.getOpcode() == ISD::BITCAST) {
13564     // Don't duplicate a load with other uses.
13565     if (!InVec.hasOneUse())
13566       return SDValue();
13567     EVT BCVT = InVec.getOperand(0).getValueType();
13568     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13569       return SDValue();
13570     InVec = InVec.getOperand(0);
13571     HasShuffleIntoBitcast = true;
13572   }
13573
13574   if (!isTargetShuffle(InVec.getOpcode()))
13575     return SDValue();
13576
13577   // Don't duplicate a load with other uses.
13578   if (!InVec.hasOneUse())
13579     return SDValue();
13580
13581   SmallVector<int, 16> ShuffleMask;
13582   bool UnaryShuffle;
13583   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13584                             UnaryShuffle))
13585     return SDValue();
13586
13587   // Select the input vector, guarding against out of range extract vector.
13588   unsigned NumElems = VT.getVectorNumElements();
13589   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13590   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13591   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13592                                          : InVec.getOperand(1);
13593
13594   // If inputs to shuffle are the same for both ops, then allow 2 uses
13595   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13596
13597   if (LdNode.getOpcode() == ISD::BITCAST) {
13598     // Don't duplicate a load with other uses.
13599     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13600       return SDValue();
13601
13602     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13603     LdNode = LdNode.getOperand(0);
13604   }
13605
13606   if (!ISD::isNormalLoad(LdNode.getNode()))
13607     return SDValue();
13608
13609   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13610
13611   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13612     return SDValue();
13613
13614   if (HasShuffleIntoBitcast) {
13615     // If there's a bitcast before the shuffle, check if the load type and
13616     // alignment is valid.
13617     unsigned Align = LN0->getAlignment();
13618     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13619     unsigned NewAlign = TLI.getTargetData()->
13620       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13621
13622     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13623       return SDValue();
13624   }
13625
13626   // All checks match so transform back to vector_shuffle so that DAG combiner
13627   // can finish the job
13628   DebugLoc dl = N->getDebugLoc();
13629
13630   // Create shuffle node taking into account the case that its a unary shuffle
13631   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13632   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13633                                  InVec.getOperand(0), Shuffle,
13634                                  &ShuffleMask[0]);
13635   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13636   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13637                      EltNo);
13638 }
13639
13640 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13641 /// generation and convert it from being a bunch of shuffles and extracts
13642 /// to a simple store and scalar loads to extract the elements.
13643 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13644                                          TargetLowering::DAGCombinerInfo &DCI) {
13645   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13646   if (NewOp.getNode())
13647     return NewOp;
13648
13649   SDValue InputVector = N->getOperand(0);
13650
13651   // Only operate on vectors of 4 elements, where the alternative shuffling
13652   // gets to be more expensive.
13653   if (InputVector.getValueType() != MVT::v4i32)
13654     return SDValue();
13655
13656   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13657   // single use which is a sign-extend or zero-extend, and all elements are
13658   // used.
13659   SmallVector<SDNode *, 4> Uses;
13660   unsigned ExtractedElements = 0;
13661   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13662        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13663     if (UI.getUse().getResNo() != InputVector.getResNo())
13664       return SDValue();
13665
13666     SDNode *Extract = *UI;
13667     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13668       return SDValue();
13669
13670     if (Extract->getValueType(0) != MVT::i32)
13671       return SDValue();
13672     if (!Extract->hasOneUse())
13673       return SDValue();
13674     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13675         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13676       return SDValue();
13677     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13678       return SDValue();
13679
13680     // Record which element was extracted.
13681     ExtractedElements |=
13682       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13683
13684     Uses.push_back(Extract);
13685   }
13686
13687   // If not all the elements were used, this may not be worthwhile.
13688   if (ExtractedElements != 15)
13689     return SDValue();
13690
13691   // Ok, we've now decided to do the transformation.
13692   DebugLoc dl = InputVector.getDebugLoc();
13693
13694   // Store the value to a temporary stack slot.
13695   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13696   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13697                             MachinePointerInfo(), false, false, 0);
13698
13699   // Replace each use (extract) with a load of the appropriate element.
13700   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13701        UE = Uses.end(); UI != UE; ++UI) {
13702     SDNode *Extract = *UI;
13703
13704     // cOMpute the element's address.
13705     SDValue Idx = Extract->getOperand(1);
13706     unsigned EltSize =
13707         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13708     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13709     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13710     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13711
13712     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13713                                      StackPtr, OffsetVal);
13714
13715     // Load the scalar.
13716     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13717                                      ScalarAddr, MachinePointerInfo(),
13718                                      false, false, false, 0);
13719
13720     // Replace the exact with the load.
13721     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13722   }
13723
13724   // The replacement was made in place; don't return anything.
13725   return SDValue();
13726 }
13727
13728 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13729 /// nodes.
13730 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13731                                     TargetLowering::DAGCombinerInfo &DCI,
13732                                     const X86Subtarget *Subtarget) {
13733   DebugLoc DL = N->getDebugLoc();
13734   SDValue Cond = N->getOperand(0);
13735   // Get the LHS/RHS of the select.
13736   SDValue LHS = N->getOperand(1);
13737   SDValue RHS = N->getOperand(2);
13738   EVT VT = LHS.getValueType();
13739
13740   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13741   // instructions match the semantics of the common C idiom x<y?x:y but not
13742   // x<=y?x:y, because of how they handle negative zero (which can be
13743   // ignored in unsafe-math mode).
13744   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13745       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13746       (Subtarget->hasSSE2() ||
13747        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13748     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13749
13750     unsigned Opcode = 0;
13751     // Check for x CC y ? x : y.
13752     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13753         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13754       switch (CC) {
13755       default: break;
13756       case ISD::SETULT:
13757         // Converting this to a min would handle NaNs incorrectly, and swapping
13758         // the operands would cause it to handle comparisons between positive
13759         // and negative zero incorrectly.
13760         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13761           if (!DAG.getTarget().Options.UnsafeFPMath &&
13762               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13763             break;
13764           std::swap(LHS, RHS);
13765         }
13766         Opcode = X86ISD::FMIN;
13767         break;
13768       case ISD::SETOLE:
13769         // Converting this to a min would handle comparisons between positive
13770         // and negative zero incorrectly.
13771         if (!DAG.getTarget().Options.UnsafeFPMath &&
13772             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13773           break;
13774         Opcode = X86ISD::FMIN;
13775         break;
13776       case ISD::SETULE:
13777         // Converting this to a min would handle both negative zeros and NaNs
13778         // incorrectly, but we can swap the operands to fix both.
13779         std::swap(LHS, RHS);
13780       case ISD::SETOLT:
13781       case ISD::SETLT:
13782       case ISD::SETLE:
13783         Opcode = X86ISD::FMIN;
13784         break;
13785
13786       case ISD::SETOGE:
13787         // Converting this to a max would handle comparisons between positive
13788         // and negative zero incorrectly.
13789         if (!DAG.getTarget().Options.UnsafeFPMath &&
13790             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13791           break;
13792         Opcode = X86ISD::FMAX;
13793         break;
13794       case ISD::SETUGT:
13795         // Converting this to a max would handle NaNs incorrectly, and swapping
13796         // the operands would cause it to handle comparisons between positive
13797         // and negative zero incorrectly.
13798         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13799           if (!DAG.getTarget().Options.UnsafeFPMath &&
13800               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13801             break;
13802           std::swap(LHS, RHS);
13803         }
13804         Opcode = X86ISD::FMAX;
13805         break;
13806       case ISD::SETUGE:
13807         // Converting this to a max would handle both negative zeros and NaNs
13808         // incorrectly, but we can swap the operands to fix both.
13809         std::swap(LHS, RHS);
13810       case ISD::SETOGT:
13811       case ISD::SETGT:
13812       case ISD::SETGE:
13813         Opcode = X86ISD::FMAX;
13814         break;
13815       }
13816     // Check for x CC y ? y : x -- a min/max with reversed arms.
13817     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13818                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13819       switch (CC) {
13820       default: break;
13821       case ISD::SETOGE:
13822         // Converting this to a min would handle comparisons between positive
13823         // and negative zero incorrectly, and swapping the operands would
13824         // cause it to handle NaNs incorrectly.
13825         if (!DAG.getTarget().Options.UnsafeFPMath &&
13826             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13827           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13828             break;
13829           std::swap(LHS, RHS);
13830         }
13831         Opcode = X86ISD::FMIN;
13832         break;
13833       case ISD::SETUGT:
13834         // Converting this to a min would handle NaNs incorrectly.
13835         if (!DAG.getTarget().Options.UnsafeFPMath &&
13836             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13837           break;
13838         Opcode = X86ISD::FMIN;
13839         break;
13840       case ISD::SETUGE:
13841         // Converting this to a min would handle both negative zeros and NaNs
13842         // incorrectly, but we can swap the operands to fix both.
13843         std::swap(LHS, RHS);
13844       case ISD::SETOGT:
13845       case ISD::SETGT:
13846       case ISD::SETGE:
13847         Opcode = X86ISD::FMIN;
13848         break;
13849
13850       case ISD::SETULT:
13851         // Converting this to a max would handle NaNs incorrectly.
13852         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13853           break;
13854         Opcode = X86ISD::FMAX;
13855         break;
13856       case ISD::SETOLE:
13857         // Converting this to a max would handle comparisons between positive
13858         // and negative zero incorrectly, and swapping the operands would
13859         // cause it to handle NaNs incorrectly.
13860         if (!DAG.getTarget().Options.UnsafeFPMath &&
13861             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13862           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13863             break;
13864           std::swap(LHS, RHS);
13865         }
13866         Opcode = X86ISD::FMAX;
13867         break;
13868       case ISD::SETULE:
13869         // Converting this to a max would handle both negative zeros and NaNs
13870         // incorrectly, but we can swap the operands to fix both.
13871         std::swap(LHS, RHS);
13872       case ISD::SETOLT:
13873       case ISD::SETLT:
13874       case ISD::SETLE:
13875         Opcode = X86ISD::FMAX;
13876         break;
13877       }
13878     }
13879
13880     if (Opcode)
13881       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13882   }
13883
13884   // If this is a select between two integer constants, try to do some
13885   // optimizations.
13886   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13887     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13888       // Don't do this for crazy integer types.
13889       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13890         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13891         // so that TrueC (the true value) is larger than FalseC.
13892         bool NeedsCondInvert = false;
13893
13894         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13895             // Efficiently invertible.
13896             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13897              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13898               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13899           NeedsCondInvert = true;
13900           std::swap(TrueC, FalseC);
13901         }
13902
13903         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13904         if (FalseC->getAPIntValue() == 0 &&
13905             TrueC->getAPIntValue().isPowerOf2()) {
13906           if (NeedsCondInvert) // Invert the condition if needed.
13907             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13908                                DAG.getConstant(1, Cond.getValueType()));
13909
13910           // Zero extend the condition if needed.
13911           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13912
13913           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13914           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13915                              DAG.getConstant(ShAmt, MVT::i8));
13916         }
13917
13918         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13919         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13920           if (NeedsCondInvert) // Invert the condition if needed.
13921             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13922                                DAG.getConstant(1, Cond.getValueType()));
13923
13924           // Zero extend the condition if needed.
13925           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13926                              FalseC->getValueType(0), Cond);
13927           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13928                              SDValue(FalseC, 0));
13929         }
13930
13931         // Optimize cases that will turn into an LEA instruction.  This requires
13932         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13933         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13934           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13935           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13936
13937           bool isFastMultiplier = false;
13938           if (Diff < 10) {
13939             switch ((unsigned char)Diff) {
13940               default: break;
13941               case 1:  // result = add base, cond
13942               case 2:  // result = lea base(    , cond*2)
13943               case 3:  // result = lea base(cond, cond*2)
13944               case 4:  // result = lea base(    , cond*4)
13945               case 5:  // result = lea base(cond, cond*4)
13946               case 8:  // result = lea base(    , cond*8)
13947               case 9:  // result = lea base(cond, cond*8)
13948                 isFastMultiplier = true;
13949                 break;
13950             }
13951           }
13952
13953           if (isFastMultiplier) {
13954             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13955             if (NeedsCondInvert) // Invert the condition if needed.
13956               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13957                                  DAG.getConstant(1, Cond.getValueType()));
13958
13959             // Zero extend the condition if needed.
13960             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13961                                Cond);
13962             // Scale the condition by the difference.
13963             if (Diff != 1)
13964               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13965                                  DAG.getConstant(Diff, Cond.getValueType()));
13966
13967             // Add the base if non-zero.
13968             if (FalseC->getAPIntValue() != 0)
13969               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13970                                  SDValue(FalseC, 0));
13971             return Cond;
13972           }
13973         }
13974       }
13975   }
13976
13977   // Canonicalize max and min:
13978   // (x > y) ? x : y -> (x >= y) ? x : y
13979   // (x < y) ? x : y -> (x <= y) ? x : y
13980   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13981   // the need for an extra compare
13982   // against zero. e.g.
13983   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13984   // subl   %esi, %edi
13985   // testl  %edi, %edi
13986   // movl   $0, %eax
13987   // cmovgl %edi, %eax
13988   // =>
13989   // xorl   %eax, %eax
13990   // subl   %esi, $edi
13991   // cmovsl %eax, %edi
13992   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13993       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13994       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13995     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13996     switch (CC) {
13997     default: break;
13998     case ISD::SETLT:
13999     case ISD::SETGT: {
14000       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14001       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14002                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14003       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14004     }
14005     }
14006   }
14007
14008   // If we know that this node is legal then we know that it is going to be
14009   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14010   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14011   // to simplify previous instructions.
14012   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14013   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14014       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14015     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14016
14017     // Don't optimize vector selects that map to mask-registers.
14018     if (BitWidth == 1)
14019       return SDValue();
14020
14021     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14022     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14023
14024     APInt KnownZero, KnownOne;
14025     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14026                                           DCI.isBeforeLegalizeOps());
14027     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14028         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14029       DCI.CommitTargetLoweringOpt(TLO);
14030   }
14031
14032   return SDValue();
14033 }
14034
14035 // Check whether a boolean test is testing a boolean value generated by
14036 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14037 // code.
14038 //
14039 // Simplify the following patterns:
14040 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14041 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14042 // to (Op EFLAGS Cond)
14043 //
14044 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14045 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14046 // to (Op EFLAGS !Cond)
14047 //
14048 // where Op could be BRCOND or CMOV.
14049 //
14050 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14051   // Quit if not CMP and SUB with its value result used.
14052   if (Cmp.getOpcode() != X86ISD::CMP &&
14053       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14054       return SDValue();
14055
14056   // Quit if not used as a boolean value.
14057   if (CC != X86::COND_E && CC != X86::COND_NE)
14058     return SDValue();
14059
14060   // Check CMP operands. One of them should be 0 or 1 and the other should be
14061   // an SetCC or extended from it.
14062   SDValue Op1 = Cmp.getOperand(0);
14063   SDValue Op2 = Cmp.getOperand(1);
14064
14065   SDValue SetCC;
14066   const ConstantSDNode* C = 0;
14067   bool needOppositeCond = (CC == X86::COND_E);
14068
14069   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14070     SetCC = Op2;
14071   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14072     SetCC = Op1;
14073   else // Quit if all operands are not constants.
14074     return SDValue();
14075
14076   if (C->getZExtValue() == 1)
14077     needOppositeCond = !needOppositeCond;
14078   else if (C->getZExtValue() != 0)
14079     // Quit if the constant is neither 0 or 1.
14080     return SDValue();
14081
14082   // Skip 'zext' node.
14083   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14084     SetCC = SetCC.getOperand(0);
14085
14086   // Quit if not SETCC.
14087   // FIXME: So far we only handle the boolean value generated from SETCC. If
14088   // there is other ways to generate boolean values, we need handle them here
14089   // as well.
14090   if (SetCC.getOpcode() != X86ISD::SETCC)
14091     return SDValue();
14092
14093   // Set the condition code or opposite one if necessary.
14094   CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14095   if (needOppositeCond)
14096     CC = X86::GetOppositeBranchCondition(CC);
14097
14098   return SetCC.getOperand(1);
14099 }
14100
14101 /// checkFlaggedOrCombine - DAG combination on X86ISD::OR, i.e. with EFLAGS
14102 /// updated. If only flag result is used and the result is evaluated from a
14103 /// series of element extraction, try to combine it into a PTEST.
14104 static SDValue checkFlaggedOrCombine(SDValue Or, X86::CondCode &CC,
14105                                      SelectionDAG &DAG,
14106                                      const X86Subtarget *Subtarget) {
14107   SDNode *N = Or.getNode();
14108   DebugLoc DL = N->getDebugLoc();
14109
14110   // Only SSE4.1 and beyond supports PTEST or like.
14111   if (!Subtarget->hasSSE41())
14112     return SDValue();
14113
14114   if (N->getOpcode() != X86ISD::OR)
14115     return SDValue();
14116
14117   // Quit if the value result of OR is used.
14118   if (N->hasAnyUseOfValue(0))
14119     return SDValue();
14120
14121   // Quit if not used as a boolean value.
14122   if (CC != X86::COND_E && CC != X86::COND_NE)
14123     return SDValue();
14124
14125   SmallVector<SDValue, 8> Opnds;
14126   SDValue VecIn;
14127   EVT VT = MVT::Other;
14128   unsigned Mask = 0;
14129
14130   // Recognize a special case where a vector is casted into wide integer to
14131   // test all 0s.
14132   Opnds.push_back(N->getOperand(0));
14133   Opnds.push_back(N->getOperand(1));
14134
14135   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14136     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
14137     // BFS traverse all OR'd operands.
14138     if (I->getOpcode() == ISD::OR) {
14139       Opnds.push_back(I->getOperand(0));
14140       Opnds.push_back(I->getOperand(1));
14141       // Re-evaluate the number of nodes to be traversed.
14142       e += 2; // 2 more nodes (LHS and RHS) are pushed.
14143       continue;
14144     }
14145
14146     // Quit if a non-EXTRACT_VECTOR_ELT
14147     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14148       return SDValue();
14149
14150     // Quit if without a constant index.
14151     SDValue Idx = I->getOperand(1);
14152     if (!isa<ConstantSDNode>(Idx))
14153       return SDValue();
14154
14155     // Check if all elements are extracted from the same vector.
14156     SDValue ExtractedFromVec = I->getOperand(0);
14157     if (VecIn.getNode() == 0) {
14158       VT = ExtractedFromVec.getValueType();
14159       // FIXME: only 128-bit vector is supported so far.
14160       if (!VT.is128BitVector())
14161         return SDValue();
14162       VecIn = ExtractedFromVec;
14163     } else if (VecIn != ExtractedFromVec)
14164       return SDValue();
14165
14166     // Record the constant index.
14167     Mask |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14168   }
14169
14170   assert(VT.is128BitVector() && "Only 128-bit vector PTEST is supported so far.");
14171
14172   // Quit if not all elements are used.
14173   if (Mask != (1U << VT.getVectorNumElements()) - 1U)
14174     return SDValue();
14175
14176   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, VecIn, VecIn);
14177 }
14178
14179 static bool isValidFCMOVCondition(X86::CondCode CC) {
14180   switch (CC) {
14181   default:
14182     return false;
14183   case X86::COND_B:
14184   case X86::COND_BE:
14185   case X86::COND_E:
14186   case X86::COND_P:
14187   case X86::COND_AE:
14188   case X86::COND_A:
14189   case X86::COND_NE:
14190   case X86::COND_NP:
14191     return true;
14192   }
14193 }
14194
14195 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14196 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14197                                   TargetLowering::DAGCombinerInfo &DCI,
14198                                   const X86Subtarget *Subtarget) {
14199   DebugLoc DL = N->getDebugLoc();
14200
14201   // If the flag operand isn't dead, don't touch this CMOV.
14202   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14203     return SDValue();
14204
14205   SDValue FalseOp = N->getOperand(0);
14206   SDValue TrueOp = N->getOperand(1);
14207   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14208   SDValue Cond = N->getOperand(3);
14209
14210   if (CC == X86::COND_E || CC == X86::COND_NE) {
14211     switch (Cond.getOpcode()) {
14212     default: break;
14213     case X86ISD::BSR:
14214     case X86ISD::BSF:
14215       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14216       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14217         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14218     }
14219   }
14220
14221   SDValue Flags;
14222
14223   Flags = checkBoolTestSetCCCombine(Cond, CC);
14224   if (Flags.getNode() &&
14225       // Extra check as FCMOV only supports a subset of X86 cond.
14226       (FalseOp.getValueType() != MVT::f80 || isValidFCMOVCondition(CC))) {
14227     SDValue Ops[] = { FalseOp, TrueOp,
14228                       DAG.getConstant(CC, MVT::i8), Flags };
14229     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14230                        Ops, array_lengthof(Ops));
14231   }
14232
14233   Flags = checkFlaggedOrCombine(Cond, CC, DAG, Subtarget);
14234   if (Flags.getNode()) {
14235     SDValue Ops[] = { FalseOp, TrueOp,
14236                       DAG.getConstant(CC, MVT::i8), Flags };
14237     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14238                        Ops, array_lengthof(Ops));
14239   }
14240
14241   // If this is a select between two integer constants, try to do some
14242   // optimizations.  Note that the operands are ordered the opposite of SELECT
14243   // operands.
14244   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14245     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14246       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14247       // larger than FalseC (the false value).
14248       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14249         CC = X86::GetOppositeBranchCondition(CC);
14250         std::swap(TrueC, FalseC);
14251       }
14252
14253       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14254       // This is efficient for any integer data type (including i8/i16) and
14255       // shift amount.
14256       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14257         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14258                            DAG.getConstant(CC, MVT::i8), Cond);
14259
14260         // Zero extend the condition if needed.
14261         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14262
14263         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14264         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14265                            DAG.getConstant(ShAmt, MVT::i8));
14266         if (N->getNumValues() == 2)  // Dead flag value?
14267           return DCI.CombineTo(N, Cond, SDValue());
14268         return Cond;
14269       }
14270
14271       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14272       // for any integer data type, including i8/i16.
14273       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14274         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14275                            DAG.getConstant(CC, MVT::i8), Cond);
14276
14277         // Zero extend the condition if needed.
14278         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14279                            FalseC->getValueType(0), Cond);
14280         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14281                            SDValue(FalseC, 0));
14282
14283         if (N->getNumValues() == 2)  // Dead flag value?
14284           return DCI.CombineTo(N, Cond, SDValue());
14285         return Cond;
14286       }
14287
14288       // Optimize cases that will turn into an LEA instruction.  This requires
14289       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14290       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14291         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14292         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14293
14294         bool isFastMultiplier = false;
14295         if (Diff < 10) {
14296           switch ((unsigned char)Diff) {
14297           default: break;
14298           case 1:  // result = add base, cond
14299           case 2:  // result = lea base(    , cond*2)
14300           case 3:  // result = lea base(cond, cond*2)
14301           case 4:  // result = lea base(    , cond*4)
14302           case 5:  // result = lea base(cond, cond*4)
14303           case 8:  // result = lea base(    , cond*8)
14304           case 9:  // result = lea base(cond, cond*8)
14305             isFastMultiplier = true;
14306             break;
14307           }
14308         }
14309
14310         if (isFastMultiplier) {
14311           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14312           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14313                              DAG.getConstant(CC, MVT::i8), Cond);
14314           // Zero extend the condition if needed.
14315           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14316                              Cond);
14317           // Scale the condition by the difference.
14318           if (Diff != 1)
14319             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14320                                DAG.getConstant(Diff, Cond.getValueType()));
14321
14322           // Add the base if non-zero.
14323           if (FalseC->getAPIntValue() != 0)
14324             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14325                                SDValue(FalseC, 0));
14326           if (N->getNumValues() == 2)  // Dead flag value?
14327             return DCI.CombineTo(N, Cond, SDValue());
14328           return Cond;
14329         }
14330       }
14331     }
14332   }
14333   return SDValue();
14334 }
14335
14336
14337 /// PerformMulCombine - Optimize a single multiply with constant into two
14338 /// in order to implement it with two cheaper instructions, e.g.
14339 /// LEA + SHL, LEA + LEA.
14340 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14341                                  TargetLowering::DAGCombinerInfo &DCI) {
14342   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14343     return SDValue();
14344
14345   EVT VT = N->getValueType(0);
14346   if (VT != MVT::i64)
14347     return SDValue();
14348
14349   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14350   if (!C)
14351     return SDValue();
14352   uint64_t MulAmt = C->getZExtValue();
14353   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14354     return SDValue();
14355
14356   uint64_t MulAmt1 = 0;
14357   uint64_t MulAmt2 = 0;
14358   if ((MulAmt % 9) == 0) {
14359     MulAmt1 = 9;
14360     MulAmt2 = MulAmt / 9;
14361   } else if ((MulAmt % 5) == 0) {
14362     MulAmt1 = 5;
14363     MulAmt2 = MulAmt / 5;
14364   } else if ((MulAmt % 3) == 0) {
14365     MulAmt1 = 3;
14366     MulAmt2 = MulAmt / 3;
14367   }
14368   if (MulAmt2 &&
14369       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14370     DebugLoc DL = N->getDebugLoc();
14371
14372     if (isPowerOf2_64(MulAmt2) &&
14373         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14374       // If second multiplifer is pow2, issue it first. We want the multiply by
14375       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14376       // is an add.
14377       std::swap(MulAmt1, MulAmt2);
14378
14379     SDValue NewMul;
14380     if (isPowerOf2_64(MulAmt1))
14381       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14382                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14383     else
14384       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14385                            DAG.getConstant(MulAmt1, VT));
14386
14387     if (isPowerOf2_64(MulAmt2))
14388       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14389                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14390     else
14391       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14392                            DAG.getConstant(MulAmt2, VT));
14393
14394     // Do not add new nodes to DAG combiner worklist.
14395     DCI.CombineTo(N, NewMul, false);
14396   }
14397   return SDValue();
14398 }
14399
14400 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14401   SDValue N0 = N->getOperand(0);
14402   SDValue N1 = N->getOperand(1);
14403   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14404   EVT VT = N0.getValueType();
14405
14406   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14407   // since the result of setcc_c is all zero's or all ones.
14408   if (VT.isInteger() && !VT.isVector() &&
14409       N1C && N0.getOpcode() == ISD::AND &&
14410       N0.getOperand(1).getOpcode() == ISD::Constant) {
14411     SDValue N00 = N0.getOperand(0);
14412     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14413         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14414           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14415          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14416       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14417       APInt ShAmt = N1C->getAPIntValue();
14418       Mask = Mask.shl(ShAmt);
14419       if (Mask != 0)
14420         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14421                            N00, DAG.getConstant(Mask, VT));
14422     }
14423   }
14424
14425
14426   // Hardware support for vector shifts is sparse which makes us scalarize the
14427   // vector operations in many cases. Also, on sandybridge ADD is faster than
14428   // shl.
14429   // (shl V, 1) -> add V,V
14430   if (isSplatVector(N1.getNode())) {
14431     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14432     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14433     // We shift all of the values by one. In many cases we do not have
14434     // hardware support for this operation. This is better expressed as an ADD
14435     // of two values.
14436     if (N1C && (1 == N1C->getZExtValue())) {
14437       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14438     }
14439   }
14440
14441   return SDValue();
14442 }
14443
14444 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14445 ///                       when possible.
14446 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14447                                    TargetLowering::DAGCombinerInfo &DCI,
14448                                    const X86Subtarget *Subtarget) {
14449   EVT VT = N->getValueType(0);
14450   if (N->getOpcode() == ISD::SHL) {
14451     SDValue V = PerformSHLCombine(N, DAG);
14452     if (V.getNode()) return V;
14453   }
14454
14455   // On X86 with SSE2 support, we can transform this to a vector shift if
14456   // all elements are shifted by the same amount.  We can't do this in legalize
14457   // because the a constant vector is typically transformed to a constant pool
14458   // so we have no knowledge of the shift amount.
14459   if (!Subtarget->hasSSE2())
14460     return SDValue();
14461
14462   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14463       (!Subtarget->hasAVX2() ||
14464        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14465     return SDValue();
14466
14467   SDValue ShAmtOp = N->getOperand(1);
14468   EVT EltVT = VT.getVectorElementType();
14469   DebugLoc DL = N->getDebugLoc();
14470   SDValue BaseShAmt = SDValue();
14471   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14472     unsigned NumElts = VT.getVectorNumElements();
14473     unsigned i = 0;
14474     for (; i != NumElts; ++i) {
14475       SDValue Arg = ShAmtOp.getOperand(i);
14476       if (Arg.getOpcode() == ISD::UNDEF) continue;
14477       BaseShAmt = Arg;
14478       break;
14479     }
14480     // Handle the case where the build_vector is all undef
14481     // FIXME: Should DAG allow this?
14482     if (i == NumElts)
14483       return SDValue();
14484
14485     for (; i != NumElts; ++i) {
14486       SDValue Arg = ShAmtOp.getOperand(i);
14487       if (Arg.getOpcode() == ISD::UNDEF) continue;
14488       if (Arg != BaseShAmt) {
14489         return SDValue();
14490       }
14491     }
14492   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14493              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14494     SDValue InVec = ShAmtOp.getOperand(0);
14495     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14496       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14497       unsigned i = 0;
14498       for (; i != NumElts; ++i) {
14499         SDValue Arg = InVec.getOperand(i);
14500         if (Arg.getOpcode() == ISD::UNDEF) continue;
14501         BaseShAmt = Arg;
14502         break;
14503       }
14504     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14505        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14506          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14507          if (C->getZExtValue() == SplatIdx)
14508            BaseShAmt = InVec.getOperand(1);
14509        }
14510     }
14511     if (BaseShAmt.getNode() == 0) {
14512       // Don't create instructions with illegal types after legalize
14513       // types has run.
14514       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14515           !DCI.isBeforeLegalize())
14516         return SDValue();
14517
14518       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14519                               DAG.getIntPtrConstant(0));
14520     }
14521   } else
14522     return SDValue();
14523
14524   // The shift amount is an i32.
14525   if (EltVT.bitsGT(MVT::i32))
14526     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14527   else if (EltVT.bitsLT(MVT::i32))
14528     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14529
14530   // The shift amount is identical so we can do a vector shift.
14531   SDValue  ValOp = N->getOperand(0);
14532   switch (N->getOpcode()) {
14533   default:
14534     llvm_unreachable("Unknown shift opcode!");
14535   case ISD::SHL:
14536     switch (VT.getSimpleVT().SimpleTy) {
14537     default: return SDValue();
14538     case MVT::v2i64:
14539     case MVT::v4i32:
14540     case MVT::v8i16:
14541     case MVT::v4i64:
14542     case MVT::v8i32:
14543     case MVT::v16i16:
14544       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14545     }
14546   case ISD::SRA:
14547     switch (VT.getSimpleVT().SimpleTy) {
14548     default: return SDValue();
14549     case MVT::v4i32:
14550     case MVT::v8i16:
14551     case MVT::v8i32:
14552     case MVT::v16i16:
14553       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14554     }
14555   case ISD::SRL:
14556     switch (VT.getSimpleVT().SimpleTy) {
14557     default: return SDValue();
14558     case MVT::v2i64:
14559     case MVT::v4i32:
14560     case MVT::v8i16:
14561     case MVT::v4i64:
14562     case MVT::v8i32:
14563     case MVT::v16i16:
14564       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14565     }
14566   }
14567 }
14568
14569
14570 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14571 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14572 // and friends.  Likewise for OR -> CMPNEQSS.
14573 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14574                             TargetLowering::DAGCombinerInfo &DCI,
14575                             const X86Subtarget *Subtarget) {
14576   unsigned opcode;
14577
14578   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14579   // we're requiring SSE2 for both.
14580   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14581     SDValue N0 = N->getOperand(0);
14582     SDValue N1 = N->getOperand(1);
14583     SDValue CMP0 = N0->getOperand(1);
14584     SDValue CMP1 = N1->getOperand(1);
14585     DebugLoc DL = N->getDebugLoc();
14586
14587     // The SETCCs should both refer to the same CMP.
14588     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14589       return SDValue();
14590
14591     SDValue CMP00 = CMP0->getOperand(0);
14592     SDValue CMP01 = CMP0->getOperand(1);
14593     EVT     VT    = CMP00.getValueType();
14594
14595     if (VT == MVT::f32 || VT == MVT::f64) {
14596       bool ExpectingFlags = false;
14597       // Check for any users that want flags:
14598       for (SDNode::use_iterator UI = N->use_begin(),
14599              UE = N->use_end();
14600            !ExpectingFlags && UI != UE; ++UI)
14601         switch (UI->getOpcode()) {
14602         default:
14603         case ISD::BR_CC:
14604         case ISD::BRCOND:
14605         case ISD::SELECT:
14606           ExpectingFlags = true;
14607           break;
14608         case ISD::CopyToReg:
14609         case ISD::SIGN_EXTEND:
14610         case ISD::ZERO_EXTEND:
14611         case ISD::ANY_EXTEND:
14612           break;
14613         }
14614
14615       if (!ExpectingFlags) {
14616         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14617         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14618
14619         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14620           X86::CondCode tmp = cc0;
14621           cc0 = cc1;
14622           cc1 = tmp;
14623         }
14624
14625         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14626             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14627           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14628           X86ISD::NodeType NTOperator = is64BitFP ?
14629             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14630           // FIXME: need symbolic constants for these magic numbers.
14631           // See X86ATTInstPrinter.cpp:printSSECC().
14632           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14633           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14634                                               DAG.getConstant(x86cc, MVT::i8));
14635           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14636                                               OnesOrZeroesF);
14637           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14638                                       DAG.getConstant(1, MVT::i32));
14639           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14640           return OneBitOfTruth;
14641         }
14642       }
14643     }
14644   }
14645   return SDValue();
14646 }
14647
14648 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14649 /// so it can be folded inside ANDNP.
14650 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14651   EVT VT = N->getValueType(0);
14652
14653   // Match direct AllOnes for 128 and 256-bit vectors
14654   if (ISD::isBuildVectorAllOnes(N))
14655     return true;
14656
14657   // Look through a bit convert.
14658   if (N->getOpcode() == ISD::BITCAST)
14659     N = N->getOperand(0).getNode();
14660
14661   // Sometimes the operand may come from a insert_subvector building a 256-bit
14662   // allones vector
14663   if (VT.is256BitVector() &&
14664       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14665     SDValue V1 = N->getOperand(0);
14666     SDValue V2 = N->getOperand(1);
14667
14668     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14669         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14670         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14671         ISD::isBuildVectorAllOnes(V2.getNode()))
14672       return true;
14673   }
14674
14675   return false;
14676 }
14677
14678 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14679                                  TargetLowering::DAGCombinerInfo &DCI,
14680                                  const X86Subtarget *Subtarget) {
14681   if (DCI.isBeforeLegalizeOps())
14682     return SDValue();
14683
14684   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14685   if (R.getNode())
14686     return R;
14687
14688   EVT VT = N->getValueType(0);
14689
14690   // Create ANDN, BLSI, and BLSR instructions
14691   // BLSI is X & (-X)
14692   // BLSR is X & (X-1)
14693   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14694     SDValue N0 = N->getOperand(0);
14695     SDValue N1 = N->getOperand(1);
14696     DebugLoc DL = N->getDebugLoc();
14697
14698     // Check LHS for not
14699     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14700       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14701     // Check RHS for not
14702     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14703       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14704
14705     // Check LHS for neg
14706     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14707         isZero(N0.getOperand(0)))
14708       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14709
14710     // Check RHS for neg
14711     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14712         isZero(N1.getOperand(0)))
14713       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14714
14715     // Check LHS for X-1
14716     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14717         isAllOnes(N0.getOperand(1)))
14718       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14719
14720     // Check RHS for X-1
14721     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14722         isAllOnes(N1.getOperand(1)))
14723       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14724
14725     return SDValue();
14726   }
14727
14728   // Want to form ANDNP nodes:
14729   // 1) In the hopes of then easily combining them with OR and AND nodes
14730   //    to form PBLEND/PSIGN.
14731   // 2) To match ANDN packed intrinsics
14732   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14733     return SDValue();
14734
14735   SDValue N0 = N->getOperand(0);
14736   SDValue N1 = N->getOperand(1);
14737   DebugLoc DL = N->getDebugLoc();
14738
14739   // Check LHS for vnot
14740   if (N0.getOpcode() == ISD::XOR &&
14741       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14742       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14743     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14744
14745   // Check RHS for vnot
14746   if (N1.getOpcode() == ISD::XOR &&
14747       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14748       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14749     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14750
14751   return SDValue();
14752 }
14753
14754 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14755                                 TargetLowering::DAGCombinerInfo &DCI,
14756                                 const X86Subtarget *Subtarget) {
14757   if (DCI.isBeforeLegalizeOps())
14758     return SDValue();
14759
14760   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14761   if (R.getNode())
14762     return R;
14763
14764   EVT VT = N->getValueType(0);
14765
14766   SDValue N0 = N->getOperand(0);
14767   SDValue N1 = N->getOperand(1);
14768
14769   // look for psign/blend
14770   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14771     if (!Subtarget->hasSSSE3() ||
14772         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14773       return SDValue();
14774
14775     // Canonicalize pandn to RHS
14776     if (N0.getOpcode() == X86ISD::ANDNP)
14777       std::swap(N0, N1);
14778     // or (and (m, y), (pandn m, x))
14779     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14780       SDValue Mask = N1.getOperand(0);
14781       SDValue X    = N1.getOperand(1);
14782       SDValue Y;
14783       if (N0.getOperand(0) == Mask)
14784         Y = N0.getOperand(1);
14785       if (N0.getOperand(1) == Mask)
14786         Y = N0.getOperand(0);
14787
14788       // Check to see if the mask appeared in both the AND and ANDNP and
14789       if (!Y.getNode())
14790         return SDValue();
14791
14792       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14793       // Look through mask bitcast.
14794       if (Mask.getOpcode() == ISD::BITCAST)
14795         Mask = Mask.getOperand(0);
14796       if (X.getOpcode() == ISD::BITCAST)
14797         X = X.getOperand(0);
14798       if (Y.getOpcode() == ISD::BITCAST)
14799         Y = Y.getOperand(0);
14800
14801       EVT MaskVT = Mask.getValueType();
14802
14803       // Validate that the Mask operand is a vector sra node.
14804       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14805       // there is no psrai.b
14806       if (Mask.getOpcode() != X86ISD::VSRAI)
14807         return SDValue();
14808
14809       // Check that the SRA is all signbits.
14810       SDValue SraC = Mask.getOperand(1);
14811       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14812       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14813       if ((SraAmt + 1) != EltBits)
14814         return SDValue();
14815
14816       DebugLoc DL = N->getDebugLoc();
14817
14818       // Now we know we at least have a plendvb with the mask val.  See if
14819       // we can form a psignb/w/d.
14820       // psign = x.type == y.type == mask.type && y = sub(0, x);
14821       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14822           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14823           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14824         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14825                "Unsupported VT for PSIGN");
14826         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14827         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14828       }
14829       // PBLENDVB only available on SSE 4.1
14830       if (!Subtarget->hasSSE41())
14831         return SDValue();
14832
14833       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14834
14835       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14836       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14837       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14838       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14839       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14840     }
14841   }
14842
14843   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14844     return SDValue();
14845
14846   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14847   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14848     std::swap(N0, N1);
14849   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14850     return SDValue();
14851   if (!N0.hasOneUse() || !N1.hasOneUse())
14852     return SDValue();
14853
14854   SDValue ShAmt0 = N0.getOperand(1);
14855   if (ShAmt0.getValueType() != MVT::i8)
14856     return SDValue();
14857   SDValue ShAmt1 = N1.getOperand(1);
14858   if (ShAmt1.getValueType() != MVT::i8)
14859     return SDValue();
14860   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14861     ShAmt0 = ShAmt0.getOperand(0);
14862   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14863     ShAmt1 = ShAmt1.getOperand(0);
14864
14865   DebugLoc DL = N->getDebugLoc();
14866   unsigned Opc = X86ISD::SHLD;
14867   SDValue Op0 = N0.getOperand(0);
14868   SDValue Op1 = N1.getOperand(0);
14869   if (ShAmt0.getOpcode() == ISD::SUB) {
14870     Opc = X86ISD::SHRD;
14871     std::swap(Op0, Op1);
14872     std::swap(ShAmt0, ShAmt1);
14873   }
14874
14875   unsigned Bits = VT.getSizeInBits();
14876   if (ShAmt1.getOpcode() == ISD::SUB) {
14877     SDValue Sum = ShAmt1.getOperand(0);
14878     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14879       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14880       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14881         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14882       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14883         return DAG.getNode(Opc, DL, VT,
14884                            Op0, Op1,
14885                            DAG.getNode(ISD::TRUNCATE, DL,
14886                                        MVT::i8, ShAmt0));
14887     }
14888   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14889     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14890     if (ShAmt0C &&
14891         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14892       return DAG.getNode(Opc, DL, VT,
14893                          N0.getOperand(0), N1.getOperand(0),
14894                          DAG.getNode(ISD::TRUNCATE, DL,
14895                                        MVT::i8, ShAmt0));
14896   }
14897
14898   return SDValue();
14899 }
14900
14901 // Generate NEG and CMOV for integer abs.
14902 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14903   EVT VT = N->getValueType(0);
14904
14905   // Since X86 does not have CMOV for 8-bit integer, we don't convert
14906   // 8-bit integer abs to NEG and CMOV.
14907   if (VT.isInteger() && VT.getSizeInBits() == 8)
14908     return SDValue();
14909
14910   SDValue N0 = N->getOperand(0);
14911   SDValue N1 = N->getOperand(1);
14912   DebugLoc DL = N->getDebugLoc();
14913
14914   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14915   // and change it to SUB and CMOV.
14916   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14917       N0.getOpcode() == ISD::ADD &&
14918       N0.getOperand(1) == N1 &&
14919       N1.getOpcode() == ISD::SRA &&
14920       N1.getOperand(0) == N0.getOperand(0))
14921     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14922       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14923         // Generate SUB & CMOV.
14924         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14925                                   DAG.getConstant(0, VT), N0.getOperand(0));
14926
14927         SDValue Ops[] = { N0.getOperand(0), Neg,
14928                           DAG.getConstant(X86::COND_GE, MVT::i8),
14929                           SDValue(Neg.getNode(), 1) };
14930         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14931                            Ops, array_lengthof(Ops));
14932       }
14933   return SDValue();
14934 }
14935
14936 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14937 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14938                                  TargetLowering::DAGCombinerInfo &DCI,
14939                                  const X86Subtarget *Subtarget) {
14940   if (DCI.isBeforeLegalizeOps())
14941     return SDValue();
14942
14943   if (Subtarget->hasCMov()) {
14944     SDValue RV = performIntegerAbsCombine(N, DAG);
14945     if (RV.getNode())
14946       return RV;
14947   }
14948
14949   // Try forming BMI if it is available.
14950   if (!Subtarget->hasBMI())
14951     return SDValue();
14952
14953   EVT VT = N->getValueType(0);
14954
14955   if (VT != MVT::i32 && VT != MVT::i64)
14956     return SDValue();
14957
14958   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14959
14960   // Create BLSMSK instructions by finding X ^ (X-1)
14961   SDValue N0 = N->getOperand(0);
14962   SDValue N1 = N->getOperand(1);
14963   DebugLoc DL = N->getDebugLoc();
14964
14965   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14966       isAllOnes(N0.getOperand(1)))
14967     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14968
14969   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14970       isAllOnes(N1.getOperand(1)))
14971     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14972
14973   return SDValue();
14974 }
14975
14976 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14977 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14978                                   TargetLowering::DAGCombinerInfo &DCI,
14979                                   const X86Subtarget *Subtarget) {
14980   LoadSDNode *Ld = cast<LoadSDNode>(N);
14981   EVT RegVT = Ld->getValueType(0);
14982   EVT MemVT = Ld->getMemoryVT();
14983   DebugLoc dl = Ld->getDebugLoc();
14984   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14985
14986   ISD::LoadExtType Ext = Ld->getExtensionType();
14987
14988   // If this is a vector EXT Load then attempt to optimize it using a
14989   // shuffle. We need SSE4 for the shuffles.
14990   // TODO: It is possible to support ZExt by zeroing the undef values
14991   // during the shuffle phase or after the shuffle.
14992   if (RegVT.isVector() && RegVT.isInteger() &&
14993       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14994     assert(MemVT != RegVT && "Cannot extend to the same type");
14995     assert(MemVT.isVector() && "Must load a vector from memory");
14996
14997     unsigned NumElems = RegVT.getVectorNumElements();
14998     unsigned RegSz = RegVT.getSizeInBits();
14999     unsigned MemSz = MemVT.getSizeInBits();
15000     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15001
15002     // All sizes must be a power of two.
15003     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15004       return SDValue();
15005
15006     // Attempt to load the original value using scalar loads.
15007     // Find the largest scalar type that divides the total loaded size.
15008     MVT SclrLoadTy = MVT::i8;
15009     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15010          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15011       MVT Tp = (MVT::SimpleValueType)tp;
15012       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15013         SclrLoadTy = Tp;
15014       }
15015     }
15016
15017     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15018     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15019         (64 <= MemSz))
15020       SclrLoadTy = MVT::f64;
15021
15022     // Calculate the number of scalar loads that we need to perform
15023     // in order to load our vector from memory.
15024     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15025
15026     // Represent our vector as a sequence of elements which are the
15027     // largest scalar that we can load.
15028     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15029       RegSz/SclrLoadTy.getSizeInBits());
15030
15031     // Represent the data using the same element type that is stored in
15032     // memory. In practice, we ''widen'' MemVT.
15033     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15034                                   RegSz/MemVT.getScalarType().getSizeInBits());
15035
15036     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15037       "Invalid vector type");
15038
15039     // We can't shuffle using an illegal type.
15040     if (!TLI.isTypeLegal(WideVecVT))
15041       return SDValue();
15042
15043     SmallVector<SDValue, 8> Chains;
15044     SDValue Ptr = Ld->getBasePtr();
15045     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15046                                         TLI.getPointerTy());
15047     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15048
15049     for (unsigned i = 0; i < NumLoads; ++i) {
15050       // Perform a single load.
15051       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15052                                        Ptr, Ld->getPointerInfo(),
15053                                        Ld->isVolatile(), Ld->isNonTemporal(),
15054                                        Ld->isInvariant(), Ld->getAlignment());
15055       Chains.push_back(ScalarLoad.getValue(1));
15056       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15057       // another round of DAGCombining.
15058       if (i == 0)
15059         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15060       else
15061         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15062                           ScalarLoad, DAG.getIntPtrConstant(i));
15063
15064       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15065     }
15066
15067     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15068                                Chains.size());
15069
15070     // Bitcast the loaded value to a vector of the original element type, in
15071     // the size of the target vector type.
15072     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15073     unsigned SizeRatio = RegSz/MemSz;
15074
15075     // Redistribute the loaded elements into the different locations.
15076     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15077     for (unsigned i = 0; i != NumElems; ++i)
15078       ShuffleVec[i*SizeRatio] = i;
15079
15080     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15081                                          DAG.getUNDEF(WideVecVT),
15082                                          &ShuffleVec[0]);
15083
15084     // Bitcast to the requested type.
15085     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15086     // Replace the original load with the new sequence
15087     // and return the new chain.
15088     return DCI.CombineTo(N, Shuff, TF, true);
15089   }
15090
15091   return SDValue();
15092 }
15093
15094 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15095 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15096                                    const X86Subtarget *Subtarget) {
15097   StoreSDNode *St = cast<StoreSDNode>(N);
15098   EVT VT = St->getValue().getValueType();
15099   EVT StVT = St->getMemoryVT();
15100   DebugLoc dl = St->getDebugLoc();
15101   SDValue StoredVal = St->getOperand(1);
15102   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15103
15104   // If we are saving a concatenation of two XMM registers, perform two stores.
15105   // On Sandy Bridge, 256-bit memory operations are executed by two
15106   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15107   // memory  operation.
15108   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15109       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15110       StoredVal.getNumOperands() == 2) {
15111     SDValue Value0 = StoredVal.getOperand(0);
15112     SDValue Value1 = StoredVal.getOperand(1);
15113
15114     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15115     SDValue Ptr0 = St->getBasePtr();
15116     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15117
15118     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15119                                 St->getPointerInfo(), St->isVolatile(),
15120                                 St->isNonTemporal(), St->getAlignment());
15121     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15122                                 St->getPointerInfo(), St->isVolatile(),
15123                                 St->isNonTemporal(), St->getAlignment());
15124     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15125   }
15126
15127   // Optimize trunc store (of multiple scalars) to shuffle and store.
15128   // First, pack all of the elements in one place. Next, store to memory
15129   // in fewer chunks.
15130   if (St->isTruncatingStore() && VT.isVector()) {
15131     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15132     unsigned NumElems = VT.getVectorNumElements();
15133     assert(StVT != VT && "Cannot truncate to the same type");
15134     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15135     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15136
15137     // From, To sizes and ElemCount must be pow of two
15138     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15139     // We are going to use the original vector elt for storing.
15140     // Accumulated smaller vector elements must be a multiple of the store size.
15141     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15142
15143     unsigned SizeRatio  = FromSz / ToSz;
15144
15145     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15146
15147     // Create a type on which we perform the shuffle
15148     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15149             StVT.getScalarType(), NumElems*SizeRatio);
15150
15151     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15152
15153     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15154     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15155     for (unsigned i = 0; i != NumElems; ++i)
15156       ShuffleVec[i] = i * SizeRatio;
15157
15158     // Can't shuffle using an illegal type.
15159     if (!TLI.isTypeLegal(WideVecVT))
15160       return SDValue();
15161
15162     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15163                                          DAG.getUNDEF(WideVecVT),
15164                                          &ShuffleVec[0]);
15165     // At this point all of the data is stored at the bottom of the
15166     // register. We now need to save it to mem.
15167
15168     // Find the largest store unit
15169     MVT StoreType = MVT::i8;
15170     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15171          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15172       MVT Tp = (MVT::SimpleValueType)tp;
15173       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15174         StoreType = Tp;
15175     }
15176
15177     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15178     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15179         (64 <= NumElems * ToSz))
15180       StoreType = MVT::f64;
15181
15182     // Bitcast the original vector into a vector of store-size units
15183     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15184             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15185     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15186     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15187     SmallVector<SDValue, 8> Chains;
15188     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15189                                         TLI.getPointerTy());
15190     SDValue Ptr = St->getBasePtr();
15191
15192     // Perform one or more big stores into memory.
15193     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15194       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15195                                    StoreType, ShuffWide,
15196                                    DAG.getIntPtrConstant(i));
15197       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15198                                 St->getPointerInfo(), St->isVolatile(),
15199                                 St->isNonTemporal(), St->getAlignment());
15200       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15201       Chains.push_back(Ch);
15202     }
15203
15204     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15205                                Chains.size());
15206   }
15207
15208
15209   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15210   // the FP state in cases where an emms may be missing.
15211   // A preferable solution to the general problem is to figure out the right
15212   // places to insert EMMS.  This qualifies as a quick hack.
15213
15214   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15215   if (VT.getSizeInBits() != 64)
15216     return SDValue();
15217
15218   const Function *F = DAG.getMachineFunction().getFunction();
15219   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
15220   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15221                      && Subtarget->hasSSE2();
15222   if ((VT.isVector() ||
15223        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15224       isa<LoadSDNode>(St->getValue()) &&
15225       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15226       St->getChain().hasOneUse() && !St->isVolatile()) {
15227     SDNode* LdVal = St->getValue().getNode();
15228     LoadSDNode *Ld = 0;
15229     int TokenFactorIndex = -1;
15230     SmallVector<SDValue, 8> Ops;
15231     SDNode* ChainVal = St->getChain().getNode();
15232     // Must be a store of a load.  We currently handle two cases:  the load
15233     // is a direct child, and it's under an intervening TokenFactor.  It is
15234     // possible to dig deeper under nested TokenFactors.
15235     if (ChainVal == LdVal)
15236       Ld = cast<LoadSDNode>(St->getChain());
15237     else if (St->getValue().hasOneUse() &&
15238              ChainVal->getOpcode() == ISD::TokenFactor) {
15239       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15240         if (ChainVal->getOperand(i).getNode() == LdVal) {
15241           TokenFactorIndex = i;
15242           Ld = cast<LoadSDNode>(St->getValue());
15243         } else
15244           Ops.push_back(ChainVal->getOperand(i));
15245       }
15246     }
15247
15248     if (!Ld || !ISD::isNormalLoad(Ld))
15249       return SDValue();
15250
15251     // If this is not the MMX case, i.e. we are just turning i64 load/store
15252     // into f64 load/store, avoid the transformation if there are multiple
15253     // uses of the loaded value.
15254     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15255       return SDValue();
15256
15257     DebugLoc LdDL = Ld->getDebugLoc();
15258     DebugLoc StDL = N->getDebugLoc();
15259     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15260     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15261     // pair instead.
15262     if (Subtarget->is64Bit() || F64IsLegal) {
15263       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15264       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15265                                   Ld->getPointerInfo(), Ld->isVolatile(),
15266                                   Ld->isNonTemporal(), Ld->isInvariant(),
15267                                   Ld->getAlignment());
15268       SDValue NewChain = NewLd.getValue(1);
15269       if (TokenFactorIndex != -1) {
15270         Ops.push_back(NewChain);
15271         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15272                                Ops.size());
15273       }
15274       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15275                           St->getPointerInfo(),
15276                           St->isVolatile(), St->isNonTemporal(),
15277                           St->getAlignment());
15278     }
15279
15280     // Otherwise, lower to two pairs of 32-bit loads / stores.
15281     SDValue LoAddr = Ld->getBasePtr();
15282     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15283                                  DAG.getConstant(4, MVT::i32));
15284
15285     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15286                                Ld->getPointerInfo(),
15287                                Ld->isVolatile(), Ld->isNonTemporal(),
15288                                Ld->isInvariant(), Ld->getAlignment());
15289     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15290                                Ld->getPointerInfo().getWithOffset(4),
15291                                Ld->isVolatile(), Ld->isNonTemporal(),
15292                                Ld->isInvariant(),
15293                                MinAlign(Ld->getAlignment(), 4));
15294
15295     SDValue NewChain = LoLd.getValue(1);
15296     if (TokenFactorIndex != -1) {
15297       Ops.push_back(LoLd);
15298       Ops.push_back(HiLd);
15299       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15300                              Ops.size());
15301     }
15302
15303     LoAddr = St->getBasePtr();
15304     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15305                          DAG.getConstant(4, MVT::i32));
15306
15307     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15308                                 St->getPointerInfo(),
15309                                 St->isVolatile(), St->isNonTemporal(),
15310                                 St->getAlignment());
15311     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15312                                 St->getPointerInfo().getWithOffset(4),
15313                                 St->isVolatile(),
15314                                 St->isNonTemporal(),
15315                                 MinAlign(St->getAlignment(), 4));
15316     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15317   }
15318   return SDValue();
15319 }
15320
15321 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15322 /// and return the operands for the horizontal operation in LHS and RHS.  A
15323 /// horizontal operation performs the binary operation on successive elements
15324 /// of its first operand, then on successive elements of its second operand,
15325 /// returning the resulting values in a vector.  For example, if
15326 ///   A = < float a0, float a1, float a2, float a3 >
15327 /// and
15328 ///   B = < float b0, float b1, float b2, float b3 >
15329 /// then the result of doing a horizontal operation on A and B is
15330 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15331 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15332 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15333 /// set to A, RHS to B, and the routine returns 'true'.
15334 /// Note that the binary operation should have the property that if one of the
15335 /// operands is UNDEF then the result is UNDEF.
15336 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15337   // Look for the following pattern: if
15338   //   A = < float a0, float a1, float a2, float a3 >
15339   //   B = < float b0, float b1, float b2, float b3 >
15340   // and
15341   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15342   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15343   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15344   // which is A horizontal-op B.
15345
15346   // At least one of the operands should be a vector shuffle.
15347   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15348       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15349     return false;
15350
15351   EVT VT = LHS.getValueType();
15352
15353   assert((VT.is128BitVector() || VT.is256BitVector()) &&
15354          "Unsupported vector type for horizontal add/sub");
15355
15356   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15357   // operate independently on 128-bit lanes.
15358   unsigned NumElts = VT.getVectorNumElements();
15359   unsigned NumLanes = VT.getSizeInBits()/128;
15360   unsigned NumLaneElts = NumElts / NumLanes;
15361   assert((NumLaneElts % 2 == 0) &&
15362          "Vector type should have an even number of elements in each lane");
15363   unsigned HalfLaneElts = NumLaneElts/2;
15364
15365   // View LHS in the form
15366   //   LHS = VECTOR_SHUFFLE A, B, LMask
15367   // If LHS is not a shuffle then pretend it is the shuffle
15368   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15369   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15370   // type VT.
15371   SDValue A, B;
15372   SmallVector<int, 16> LMask(NumElts);
15373   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15374     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15375       A = LHS.getOperand(0);
15376     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15377       B = LHS.getOperand(1);
15378     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15379     std::copy(Mask.begin(), Mask.end(), LMask.begin());
15380   } else {
15381     if (LHS.getOpcode() != ISD::UNDEF)
15382       A = LHS;
15383     for (unsigned i = 0; i != NumElts; ++i)
15384       LMask[i] = i;
15385   }
15386
15387   // Likewise, view RHS in the form
15388   //   RHS = VECTOR_SHUFFLE C, D, RMask
15389   SDValue C, D;
15390   SmallVector<int, 16> RMask(NumElts);
15391   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15392     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15393       C = RHS.getOperand(0);
15394     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15395       D = RHS.getOperand(1);
15396     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15397     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15398   } else {
15399     if (RHS.getOpcode() != ISD::UNDEF)
15400       C = RHS;
15401     for (unsigned i = 0; i != NumElts; ++i)
15402       RMask[i] = i;
15403   }
15404
15405   // Check that the shuffles are both shuffling the same vectors.
15406   if (!(A == C && B == D) && !(A == D && B == C))
15407     return false;
15408
15409   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15410   if (!A.getNode() && !B.getNode())
15411     return false;
15412
15413   // If A and B occur in reverse order in RHS, then "swap" them (which means
15414   // rewriting the mask).
15415   if (A != C)
15416     CommuteVectorShuffleMask(RMask, NumElts);
15417
15418   // At this point LHS and RHS are equivalent to
15419   //   LHS = VECTOR_SHUFFLE A, B, LMask
15420   //   RHS = VECTOR_SHUFFLE A, B, RMask
15421   // Check that the masks correspond to performing a horizontal operation.
15422   for (unsigned i = 0; i != NumElts; ++i) {
15423     int LIdx = LMask[i], RIdx = RMask[i];
15424
15425     // Ignore any UNDEF components.
15426     if (LIdx < 0 || RIdx < 0 ||
15427         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15428         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15429       continue;
15430
15431     // Check that successive elements are being operated on.  If not, this is
15432     // not a horizontal operation.
15433     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15434     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15435     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15436     if (!(LIdx == Index && RIdx == Index + 1) &&
15437         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15438       return false;
15439   }
15440
15441   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15442   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15443   return true;
15444 }
15445
15446 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15447 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15448                                   const X86Subtarget *Subtarget) {
15449   EVT VT = N->getValueType(0);
15450   SDValue LHS = N->getOperand(0);
15451   SDValue RHS = N->getOperand(1);
15452
15453   // Try to synthesize horizontal adds from adds of shuffles.
15454   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15455        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15456       isHorizontalBinOp(LHS, RHS, true))
15457     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15458   return SDValue();
15459 }
15460
15461 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15462 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15463                                   const X86Subtarget *Subtarget) {
15464   EVT VT = N->getValueType(0);
15465   SDValue LHS = N->getOperand(0);
15466   SDValue RHS = N->getOperand(1);
15467
15468   // Try to synthesize horizontal subs from subs of shuffles.
15469   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15470        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15471       isHorizontalBinOp(LHS, RHS, false))
15472     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15473   return SDValue();
15474 }
15475
15476 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15477 /// X86ISD::FXOR nodes.
15478 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15479   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15480   // F[X]OR(0.0, x) -> x
15481   // F[X]OR(x, 0.0) -> x
15482   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15483     if (C->getValueAPF().isPosZero())
15484       return N->getOperand(1);
15485   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15486     if (C->getValueAPF().isPosZero())
15487       return N->getOperand(0);
15488   return SDValue();
15489 }
15490
15491 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15492 /// X86ISD::FMAX nodes.
15493 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15494   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15495
15496   // Only perform optimizations if UnsafeMath is used.
15497   if (!DAG.getTarget().Options.UnsafeFPMath)
15498     return SDValue();
15499
15500   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15501   // into FMINC and FMAXC, which are Commutative operations.
15502   unsigned NewOp = 0;
15503   switch (N->getOpcode()) {
15504     default: llvm_unreachable("unknown opcode");
15505     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
15506     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
15507   }
15508
15509   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15510                      N->getOperand(0), N->getOperand(1));
15511 }
15512
15513
15514 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15515 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15516   // FAND(0.0, x) -> 0.0
15517   // FAND(x, 0.0) -> 0.0
15518   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15519     if (C->getValueAPF().isPosZero())
15520       return N->getOperand(0);
15521   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15522     if (C->getValueAPF().isPosZero())
15523       return N->getOperand(1);
15524   return SDValue();
15525 }
15526
15527 static SDValue PerformBTCombine(SDNode *N,
15528                                 SelectionDAG &DAG,
15529                                 TargetLowering::DAGCombinerInfo &DCI) {
15530   // BT ignores high bits in the bit index operand.
15531   SDValue Op1 = N->getOperand(1);
15532   if (Op1.hasOneUse()) {
15533     unsigned BitWidth = Op1.getValueSizeInBits();
15534     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15535     APInt KnownZero, KnownOne;
15536     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15537                                           !DCI.isBeforeLegalizeOps());
15538     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15539     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15540         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15541       DCI.CommitTargetLoweringOpt(TLO);
15542   }
15543   return SDValue();
15544 }
15545
15546 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15547   SDValue Op = N->getOperand(0);
15548   if (Op.getOpcode() == ISD::BITCAST)
15549     Op = Op.getOperand(0);
15550   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15551   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15552       VT.getVectorElementType().getSizeInBits() ==
15553       OpVT.getVectorElementType().getSizeInBits()) {
15554     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15555   }
15556   return SDValue();
15557 }
15558
15559 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15560                                   TargetLowering::DAGCombinerInfo &DCI,
15561                                   const X86Subtarget *Subtarget) {
15562   if (!DCI.isBeforeLegalizeOps())
15563     return SDValue();
15564
15565   if (!Subtarget->hasAVX())
15566     return SDValue();
15567
15568   EVT VT = N->getValueType(0);
15569   SDValue Op = N->getOperand(0);
15570   EVT OpVT = Op.getValueType();
15571   DebugLoc dl = N->getDebugLoc();
15572
15573   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15574       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15575
15576     if (Subtarget->hasAVX2())
15577       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15578
15579     // Optimize vectors in AVX mode
15580     // Sign extend  v8i16 to v8i32 and
15581     //              v4i32 to v4i64
15582     //
15583     // Divide input vector into two parts
15584     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15585     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15586     // concat the vectors to original VT
15587
15588     unsigned NumElems = OpVT.getVectorNumElements();
15589     SDValue Undef = DAG.getUNDEF(OpVT);
15590
15591     SmallVector<int,8> ShufMask1(NumElems, -1);
15592     for (unsigned i = 0; i != NumElems/2; ++i)
15593       ShufMask1[i] = i;
15594
15595     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15596
15597     SmallVector<int,8> ShufMask2(NumElems, -1);
15598     for (unsigned i = 0; i != NumElems/2; ++i)
15599       ShufMask2[i] = i + NumElems/2;
15600
15601     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15602
15603     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15604                                   VT.getVectorNumElements()/2);
15605
15606     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15607     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15608
15609     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15610   }
15611   return SDValue();
15612 }
15613
15614 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15615                                  const X86Subtarget* Subtarget) {
15616   DebugLoc dl = N->getDebugLoc();
15617   EVT VT = N->getValueType(0);
15618
15619   // Let legalize expand this if it isn't a legal type yet.
15620   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15621     return SDValue();
15622
15623   EVT ScalarVT = VT.getScalarType();
15624   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15625       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15626     return SDValue();
15627
15628   SDValue A = N->getOperand(0);
15629   SDValue B = N->getOperand(1);
15630   SDValue C = N->getOperand(2);
15631
15632   bool NegA = (A.getOpcode() == ISD::FNEG);
15633   bool NegB = (B.getOpcode() == ISD::FNEG);
15634   bool NegC = (C.getOpcode() == ISD::FNEG);
15635
15636   // Negative multiplication when NegA xor NegB
15637   bool NegMul = (NegA != NegB);
15638   if (NegA)
15639     A = A.getOperand(0);
15640   if (NegB)
15641     B = B.getOperand(0);
15642   if (NegC)
15643     C = C.getOperand(0);
15644
15645   unsigned Opcode;
15646   if (!NegMul)
15647     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15648   else
15649     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15650
15651   return DAG.getNode(Opcode, dl, VT, A, B, C);
15652 }
15653
15654 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15655                                   TargetLowering::DAGCombinerInfo &DCI,
15656                                   const X86Subtarget *Subtarget) {
15657   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15658   //           (and (i32 x86isd::setcc_carry), 1)
15659   // This eliminates the zext. This transformation is necessary because
15660   // ISD::SETCC is always legalized to i8.
15661   DebugLoc dl = N->getDebugLoc();
15662   SDValue N0 = N->getOperand(0);
15663   EVT VT = N->getValueType(0);
15664   EVT OpVT = N0.getValueType();
15665
15666   if (N0.getOpcode() == ISD::AND &&
15667       N0.hasOneUse() &&
15668       N0.getOperand(0).hasOneUse()) {
15669     SDValue N00 = N0.getOperand(0);
15670     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15671       return SDValue();
15672     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15673     if (!C || C->getZExtValue() != 1)
15674       return SDValue();
15675     return DAG.getNode(ISD::AND, dl, VT,
15676                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15677                                    N00.getOperand(0), N00.getOperand(1)),
15678                        DAG.getConstant(1, VT));
15679   }
15680
15681   // Optimize vectors in AVX mode:
15682   //
15683   //   v8i16 -> v8i32
15684   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15685   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15686   //   Concat upper and lower parts.
15687   //
15688   //   v4i32 -> v4i64
15689   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15690   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15691   //   Concat upper and lower parts.
15692   //
15693   if (!DCI.isBeforeLegalizeOps())
15694     return SDValue();
15695
15696   if (!Subtarget->hasAVX())
15697     return SDValue();
15698
15699   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15700       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15701
15702     if (Subtarget->hasAVX2())
15703       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15704
15705     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15706     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15707     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15708
15709     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15710                                VT.getVectorNumElements()/2);
15711
15712     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15713     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15714
15715     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15716   }
15717
15718   return SDValue();
15719 }
15720
15721 // Optimize x == -y --> x+y == 0
15722 //          x != -y --> x+y != 0
15723 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15724   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15725   SDValue LHS = N->getOperand(0);
15726   SDValue RHS = N->getOperand(1);
15727
15728   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15729     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15730       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15731         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15732                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15733         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15734                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15735       }
15736   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15737     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15738       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15739         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15740                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15741         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15742                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15743       }
15744   return SDValue();
15745 }
15746
15747 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15748 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15749                                    TargetLowering::DAGCombinerInfo &DCI,
15750                                    const X86Subtarget *Subtarget) {
15751   DebugLoc DL = N->getDebugLoc();
15752   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15753   SDValue EFLAGS = N->getOperand(1);
15754
15755   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15756   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15757   // cases.
15758   if (CC == X86::COND_B)
15759     return DAG.getNode(ISD::AND, DL, MVT::i8,
15760                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15761                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
15762                        DAG.getConstant(1, MVT::i8));
15763
15764   SDValue Flags;
15765
15766   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15767   if (Flags.getNode()) {
15768     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15769     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15770   }
15771
15772   Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15773   if (Flags.getNode()) {
15774     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15775     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15776   }
15777
15778   return SDValue();
15779 }
15780
15781 // Optimize branch condition evaluation.
15782 //
15783 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15784                                     TargetLowering::DAGCombinerInfo &DCI,
15785                                     const X86Subtarget *Subtarget) {
15786   DebugLoc DL = N->getDebugLoc();
15787   SDValue Chain = N->getOperand(0);
15788   SDValue Dest = N->getOperand(1);
15789   SDValue EFLAGS = N->getOperand(3);
15790   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15791
15792   SDValue Flags;
15793
15794   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15795   if (Flags.getNode()) {
15796     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15797     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15798                        Flags);
15799   }
15800
15801   Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15802   if (Flags.getNode()) {
15803     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15804     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15805                        Flags);
15806   }
15807
15808   return SDValue();
15809 }
15810
15811 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15812   SDValue Op0 = N->getOperand(0);
15813   EVT InVT = Op0->getValueType(0);
15814
15815   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15816   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15817     DebugLoc dl = N->getDebugLoc();
15818     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15819     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15820     // Notice that we use SINT_TO_FP because we know that the high bits
15821     // are zero and SINT_TO_FP is better supported by the hardware.
15822     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15823   }
15824
15825   return SDValue();
15826 }
15827
15828 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15829                                         const X86TargetLowering *XTLI) {
15830   SDValue Op0 = N->getOperand(0);
15831   EVT InVT = Op0->getValueType(0);
15832
15833   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15834   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15835     DebugLoc dl = N->getDebugLoc();
15836     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15837     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15838     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15839   }
15840
15841   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15842   // a 32-bit target where SSE doesn't support i64->FP operations.
15843   if (Op0.getOpcode() == ISD::LOAD) {
15844     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15845     EVT VT = Ld->getValueType(0);
15846     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15847         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15848         !XTLI->getSubtarget()->is64Bit() &&
15849         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15850       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15851                                           Ld->getChain(), Op0, DAG);
15852       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15853       return FILDChain;
15854     }
15855   }
15856   return SDValue();
15857 }
15858
15859 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15860   EVT VT = N->getValueType(0);
15861
15862   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15863   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15864     DebugLoc dl = N->getDebugLoc();
15865     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15866     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15867     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15868   }
15869
15870   return SDValue();
15871 }
15872
15873 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15874 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15875                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15876   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15877   // the result is either zero or one (depending on the input carry bit).
15878   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15879   if (X86::isZeroNode(N->getOperand(0)) &&
15880       X86::isZeroNode(N->getOperand(1)) &&
15881       // We don't have a good way to replace an EFLAGS use, so only do this when
15882       // dead right now.
15883       SDValue(N, 1).use_empty()) {
15884     DebugLoc DL = N->getDebugLoc();
15885     EVT VT = N->getValueType(0);
15886     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15887     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15888                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15889                                            DAG.getConstant(X86::COND_B,MVT::i8),
15890                                            N->getOperand(2)),
15891                                DAG.getConstant(1, VT));
15892     return DCI.CombineTo(N, Res1, CarryOut);
15893   }
15894
15895   return SDValue();
15896 }
15897
15898 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15899 //      (add Y, (setne X, 0)) -> sbb -1, Y
15900 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15901 //      (sub (setne X, 0), Y) -> adc -1, Y
15902 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15903   DebugLoc DL = N->getDebugLoc();
15904
15905   // Look through ZExts.
15906   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15907   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15908     return SDValue();
15909
15910   SDValue SetCC = Ext.getOperand(0);
15911   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15912     return SDValue();
15913
15914   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15915   if (CC != X86::COND_E && CC != X86::COND_NE)
15916     return SDValue();
15917
15918   SDValue Cmp = SetCC.getOperand(1);
15919   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15920       !X86::isZeroNode(Cmp.getOperand(1)) ||
15921       !Cmp.getOperand(0).getValueType().isInteger())
15922     return SDValue();
15923
15924   SDValue CmpOp0 = Cmp.getOperand(0);
15925   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15926                                DAG.getConstant(1, CmpOp0.getValueType()));
15927
15928   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15929   if (CC == X86::COND_NE)
15930     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15931                        DL, OtherVal.getValueType(), OtherVal,
15932                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15933   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15934                      DL, OtherVal.getValueType(), OtherVal,
15935                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15936 }
15937
15938 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15939 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15940                                  const X86Subtarget *Subtarget) {
15941   EVT VT = N->getValueType(0);
15942   SDValue Op0 = N->getOperand(0);
15943   SDValue Op1 = N->getOperand(1);
15944
15945   // Try to synthesize horizontal adds from adds of shuffles.
15946   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15947        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15948       isHorizontalBinOp(Op0, Op1, true))
15949     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15950
15951   return OptimizeConditionalInDecrement(N, DAG);
15952 }
15953
15954 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15955                                  const X86Subtarget *Subtarget) {
15956   SDValue Op0 = N->getOperand(0);
15957   SDValue Op1 = N->getOperand(1);
15958
15959   // X86 can't encode an immediate LHS of a sub. See if we can push the
15960   // negation into a preceding instruction.
15961   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15962     // If the RHS of the sub is a XOR with one use and a constant, invert the
15963     // immediate. Then add one to the LHS of the sub so we can turn
15964     // X-Y -> X+~Y+1, saving one register.
15965     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15966         isa<ConstantSDNode>(Op1.getOperand(1))) {
15967       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15968       EVT VT = Op0.getValueType();
15969       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15970                                    Op1.getOperand(0),
15971                                    DAG.getConstant(~XorC, VT));
15972       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15973                          DAG.getConstant(C->getAPIntValue()+1, VT));
15974     }
15975   }
15976
15977   // Try to synthesize horizontal adds from adds of shuffles.
15978   EVT VT = N->getValueType(0);
15979   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15980        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15981       isHorizontalBinOp(Op0, Op1, true))
15982     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15983
15984   return OptimizeConditionalInDecrement(N, DAG);
15985 }
15986
15987 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15988                                              DAGCombinerInfo &DCI) const {
15989   SelectionDAG &DAG = DCI.DAG;
15990   switch (N->getOpcode()) {
15991   default: break;
15992   case ISD::EXTRACT_VECTOR_ELT:
15993     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15994   case ISD::VSELECT:
15995   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15996   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
15997   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
15998   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
15999   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16000   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16001   case ISD::SHL:
16002   case ISD::SRA:
16003   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16004   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16005   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16006   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16007   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16008   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16009   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16010   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16011   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
16012   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16013   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16014   case X86ISD::FXOR:
16015   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16016   case X86ISD::FMIN:
16017   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16018   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16019   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16020   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16021   case ISD::ANY_EXTEND:
16022   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16023   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16024   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
16025   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16026   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16027   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16028   case X86ISD::SHUFP:       // Handle all target specific shuffles
16029   case X86ISD::PALIGN:
16030   case X86ISD::UNPCKH:
16031   case X86ISD::UNPCKL:
16032   case X86ISD::MOVHLPS:
16033   case X86ISD::MOVLHPS:
16034   case X86ISD::PSHUFD:
16035   case X86ISD::PSHUFHW:
16036   case X86ISD::PSHUFLW:
16037   case X86ISD::MOVSS:
16038   case X86ISD::MOVSD:
16039   case X86ISD::VPERMILP:
16040   case X86ISD::VPERM2X128:
16041   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16042   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16043   }
16044
16045   return SDValue();
16046 }
16047
16048 /// isTypeDesirableForOp - Return true if the target has native support for
16049 /// the specified value type and it is 'desirable' to use the type for the
16050 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16051 /// instruction encodings are longer and some i16 instructions are slow.
16052 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16053   if (!isTypeLegal(VT))
16054     return false;
16055   if (VT != MVT::i16)
16056     return true;
16057
16058   switch (Opc) {
16059   default:
16060     return true;
16061   case ISD::LOAD:
16062   case ISD::SIGN_EXTEND:
16063   case ISD::ZERO_EXTEND:
16064   case ISD::ANY_EXTEND:
16065   case ISD::SHL:
16066   case ISD::SRL:
16067   case ISD::SUB:
16068   case ISD::ADD:
16069   case ISD::MUL:
16070   case ISD::AND:
16071   case ISD::OR:
16072   case ISD::XOR:
16073     return false;
16074   }
16075 }
16076
16077 /// IsDesirableToPromoteOp - This method query the target whether it is
16078 /// beneficial for dag combiner to promote the specified node. If true, it
16079 /// should return the desired promotion type by reference.
16080 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16081   EVT VT = Op.getValueType();
16082   if (VT != MVT::i16)
16083     return false;
16084
16085   bool Promote = false;
16086   bool Commute = false;
16087   switch (Op.getOpcode()) {
16088   default: break;
16089   case ISD::LOAD: {
16090     LoadSDNode *LD = cast<LoadSDNode>(Op);
16091     // If the non-extending load has a single use and it's not live out, then it
16092     // might be folded.
16093     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16094                                                      Op.hasOneUse()*/) {
16095       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16096              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16097         // The only case where we'd want to promote LOAD (rather then it being
16098         // promoted as an operand is when it's only use is liveout.
16099         if (UI->getOpcode() != ISD::CopyToReg)
16100           return false;
16101       }
16102     }
16103     Promote = true;
16104     break;
16105   }
16106   case ISD::SIGN_EXTEND:
16107   case ISD::ZERO_EXTEND:
16108   case ISD::ANY_EXTEND:
16109     Promote = true;
16110     break;
16111   case ISD::SHL:
16112   case ISD::SRL: {
16113     SDValue N0 = Op.getOperand(0);
16114     // Look out for (store (shl (load), x)).
16115     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16116       return false;
16117     Promote = true;
16118     break;
16119   }
16120   case ISD::ADD:
16121   case ISD::MUL:
16122   case ISD::AND:
16123   case ISD::OR:
16124   case ISD::XOR:
16125     Commute = true;
16126     // fallthrough
16127   case ISD::SUB: {
16128     SDValue N0 = Op.getOperand(0);
16129     SDValue N1 = Op.getOperand(1);
16130     if (!Commute && MayFoldLoad(N1))
16131       return false;
16132     // Avoid disabling potential load folding opportunities.
16133     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16134       return false;
16135     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16136       return false;
16137     Promote = true;
16138   }
16139   }
16140
16141   PVT = MVT::i32;
16142   return Promote;
16143 }
16144
16145 //===----------------------------------------------------------------------===//
16146 //                           X86 Inline Assembly Support
16147 //===----------------------------------------------------------------------===//
16148
16149 namespace {
16150   // Helper to match a string separated by whitespace.
16151   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16152     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16153
16154     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16155       StringRef piece(*args[i]);
16156       if (!s.startswith(piece)) // Check if the piece matches.
16157         return false;
16158
16159       s = s.substr(piece.size());
16160       StringRef::size_type pos = s.find_first_not_of(" \t");
16161       if (pos == 0) // We matched a prefix.
16162         return false;
16163
16164       s = s.substr(pos);
16165     }
16166
16167     return s.empty();
16168   }
16169   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16170 }
16171
16172 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16173   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16174
16175   std::string AsmStr = IA->getAsmString();
16176
16177   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16178   if (!Ty || Ty->getBitWidth() % 16 != 0)
16179     return false;
16180
16181   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16182   SmallVector<StringRef, 4> AsmPieces;
16183   SplitString(AsmStr, AsmPieces, ";\n");
16184
16185   switch (AsmPieces.size()) {
16186   default: return false;
16187   case 1:
16188     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16189     // we will turn this bswap into something that will be lowered to logical
16190     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16191     // lower so don't worry about this.
16192     // bswap $0
16193     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16194         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16195         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16196         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16197         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16198         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16199       // No need to check constraints, nothing other than the equivalent of
16200       // "=r,0" would be valid here.
16201       return IntrinsicLowering::LowerToByteSwap(CI);
16202     }
16203
16204     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16205     if (CI->getType()->isIntegerTy(16) &&
16206         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16207         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16208          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16209       AsmPieces.clear();
16210       const std::string &ConstraintsStr = IA->getConstraintString();
16211       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16212       std::sort(AsmPieces.begin(), AsmPieces.end());
16213       if (AsmPieces.size() == 4 &&
16214           AsmPieces[0] == "~{cc}" &&
16215           AsmPieces[1] == "~{dirflag}" &&
16216           AsmPieces[2] == "~{flags}" &&
16217           AsmPieces[3] == "~{fpsr}")
16218       return IntrinsicLowering::LowerToByteSwap(CI);
16219     }
16220     break;
16221   case 3:
16222     if (CI->getType()->isIntegerTy(32) &&
16223         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16224         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16225         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16226         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16227       AsmPieces.clear();
16228       const std::string &ConstraintsStr = IA->getConstraintString();
16229       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16230       std::sort(AsmPieces.begin(), AsmPieces.end());
16231       if (AsmPieces.size() == 4 &&
16232           AsmPieces[0] == "~{cc}" &&
16233           AsmPieces[1] == "~{dirflag}" &&
16234           AsmPieces[2] == "~{flags}" &&
16235           AsmPieces[3] == "~{fpsr}")
16236         return IntrinsicLowering::LowerToByteSwap(CI);
16237     }
16238
16239     if (CI->getType()->isIntegerTy(64)) {
16240       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16241       if (Constraints.size() >= 2 &&
16242           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16243           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16244         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16245         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16246             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16247             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16248           return IntrinsicLowering::LowerToByteSwap(CI);
16249       }
16250     }
16251     break;
16252   }
16253   return false;
16254 }
16255
16256
16257
16258 /// getConstraintType - Given a constraint letter, return the type of
16259 /// constraint it is for this target.
16260 X86TargetLowering::ConstraintType
16261 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16262   if (Constraint.size() == 1) {
16263     switch (Constraint[0]) {
16264     case 'R':
16265     case 'q':
16266     case 'Q':
16267     case 'f':
16268     case 't':
16269     case 'u':
16270     case 'y':
16271     case 'x':
16272     case 'Y':
16273     case 'l':
16274       return C_RegisterClass;
16275     case 'a':
16276     case 'b':
16277     case 'c':
16278     case 'd':
16279     case 'S':
16280     case 'D':
16281     case 'A':
16282       return C_Register;
16283     case 'I':
16284     case 'J':
16285     case 'K':
16286     case 'L':
16287     case 'M':
16288     case 'N':
16289     case 'G':
16290     case 'C':
16291     case 'e':
16292     case 'Z':
16293       return C_Other;
16294     default:
16295       break;
16296     }
16297   }
16298   return TargetLowering::getConstraintType(Constraint);
16299 }
16300
16301 /// Examine constraint type and operand type and determine a weight value.
16302 /// This object must already have been set up with the operand type
16303 /// and the current alternative constraint selected.
16304 TargetLowering::ConstraintWeight
16305   X86TargetLowering::getSingleConstraintMatchWeight(
16306     AsmOperandInfo &info, const char *constraint) const {
16307   ConstraintWeight weight = CW_Invalid;
16308   Value *CallOperandVal = info.CallOperandVal;
16309     // If we don't have a value, we can't do a match,
16310     // but allow it at the lowest weight.
16311   if (CallOperandVal == NULL)
16312     return CW_Default;
16313   Type *type = CallOperandVal->getType();
16314   // Look at the constraint type.
16315   switch (*constraint) {
16316   default:
16317     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16318   case 'R':
16319   case 'q':
16320   case 'Q':
16321   case 'a':
16322   case 'b':
16323   case 'c':
16324   case 'd':
16325   case 'S':
16326   case 'D':
16327   case 'A':
16328     if (CallOperandVal->getType()->isIntegerTy())
16329       weight = CW_SpecificReg;
16330     break;
16331   case 'f':
16332   case 't':
16333   case 'u':
16334       if (type->isFloatingPointTy())
16335         weight = CW_SpecificReg;
16336       break;
16337   case 'y':
16338       if (type->isX86_MMXTy() && Subtarget->hasMMX())
16339         weight = CW_SpecificReg;
16340       break;
16341   case 'x':
16342   case 'Y':
16343     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16344         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16345       weight = CW_Register;
16346     break;
16347   case 'I':
16348     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16349       if (C->getZExtValue() <= 31)
16350         weight = CW_Constant;
16351     }
16352     break;
16353   case 'J':
16354     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16355       if (C->getZExtValue() <= 63)
16356         weight = CW_Constant;
16357     }
16358     break;
16359   case 'K':
16360     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16361       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16362         weight = CW_Constant;
16363     }
16364     break;
16365   case 'L':
16366     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16367       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16368         weight = CW_Constant;
16369     }
16370     break;
16371   case 'M':
16372     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16373       if (C->getZExtValue() <= 3)
16374         weight = CW_Constant;
16375     }
16376     break;
16377   case 'N':
16378     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16379       if (C->getZExtValue() <= 0xff)
16380         weight = CW_Constant;
16381     }
16382     break;
16383   case 'G':
16384   case 'C':
16385     if (dyn_cast<ConstantFP>(CallOperandVal)) {
16386       weight = CW_Constant;
16387     }
16388     break;
16389   case 'e':
16390     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16391       if ((C->getSExtValue() >= -0x80000000LL) &&
16392           (C->getSExtValue() <= 0x7fffffffLL))
16393         weight = CW_Constant;
16394     }
16395     break;
16396   case 'Z':
16397     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16398       if (C->getZExtValue() <= 0xffffffff)
16399         weight = CW_Constant;
16400     }
16401     break;
16402   }
16403   return weight;
16404 }
16405
16406 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16407 /// with another that has more specific requirements based on the type of the
16408 /// corresponding operand.
16409 const char *X86TargetLowering::
16410 LowerXConstraint(EVT ConstraintVT) const {
16411   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16412   // 'f' like normal targets.
16413   if (ConstraintVT.isFloatingPoint()) {
16414     if (Subtarget->hasSSE2())
16415       return "Y";
16416     if (Subtarget->hasSSE1())
16417       return "x";
16418   }
16419
16420   return TargetLowering::LowerXConstraint(ConstraintVT);
16421 }
16422
16423 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16424 /// vector.  If it is invalid, don't add anything to Ops.
16425 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16426                                                      std::string &Constraint,
16427                                                      std::vector<SDValue>&Ops,
16428                                                      SelectionDAG &DAG) const {
16429   SDValue Result(0, 0);
16430
16431   // Only support length 1 constraints for now.
16432   if (Constraint.length() > 1) return;
16433
16434   char ConstraintLetter = Constraint[0];
16435   switch (ConstraintLetter) {
16436   default: break;
16437   case 'I':
16438     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16439       if (C->getZExtValue() <= 31) {
16440         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16441         break;
16442       }
16443     }
16444     return;
16445   case 'J':
16446     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16447       if (C->getZExtValue() <= 63) {
16448         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16449         break;
16450       }
16451     }
16452     return;
16453   case 'K':
16454     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16455       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16456         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16457         break;
16458       }
16459     }
16460     return;
16461   case 'N':
16462     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16463       if (C->getZExtValue() <= 255) {
16464         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16465         break;
16466       }
16467     }
16468     return;
16469   case 'e': {
16470     // 32-bit signed value
16471     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16472       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16473                                            C->getSExtValue())) {
16474         // Widen to 64 bits here to get it sign extended.
16475         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16476         break;
16477       }
16478     // FIXME gcc accepts some relocatable values here too, but only in certain
16479     // memory models; it's complicated.
16480     }
16481     return;
16482   }
16483   case 'Z': {
16484     // 32-bit unsigned value
16485     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16486       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16487                                            C->getZExtValue())) {
16488         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16489         break;
16490       }
16491     }
16492     // FIXME gcc accepts some relocatable values here too, but only in certain
16493     // memory models; it's complicated.
16494     return;
16495   }
16496   case 'i': {
16497     // Literal immediates are always ok.
16498     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16499       // Widen to 64 bits here to get it sign extended.
16500       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16501       break;
16502     }
16503
16504     // In any sort of PIC mode addresses need to be computed at runtime by
16505     // adding in a register or some sort of table lookup.  These can't
16506     // be used as immediates.
16507     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16508       return;
16509
16510     // If we are in non-pic codegen mode, we allow the address of a global (with
16511     // an optional displacement) to be used with 'i'.
16512     GlobalAddressSDNode *GA = 0;
16513     int64_t Offset = 0;
16514
16515     // Match either (GA), (GA+C), (GA+C1+C2), etc.
16516     while (1) {
16517       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16518         Offset += GA->getOffset();
16519         break;
16520       } else if (Op.getOpcode() == ISD::ADD) {
16521         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16522           Offset += C->getZExtValue();
16523           Op = Op.getOperand(0);
16524           continue;
16525         }
16526       } else if (Op.getOpcode() == ISD::SUB) {
16527         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16528           Offset += -C->getZExtValue();
16529           Op = Op.getOperand(0);
16530           continue;
16531         }
16532       }
16533
16534       // Otherwise, this isn't something we can handle, reject it.
16535       return;
16536     }
16537
16538     const GlobalValue *GV = GA->getGlobal();
16539     // If we require an extra load to get this address, as in PIC mode, we
16540     // can't accept it.
16541     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16542                                                         getTargetMachine())))
16543       return;
16544
16545     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16546                                         GA->getValueType(0), Offset);
16547     break;
16548   }
16549   }
16550
16551   if (Result.getNode()) {
16552     Ops.push_back(Result);
16553     return;
16554   }
16555   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16556 }
16557
16558 std::pair<unsigned, const TargetRegisterClass*>
16559 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16560                                                 EVT VT) const {
16561   // First, see if this is a constraint that directly corresponds to an LLVM
16562   // register class.
16563   if (Constraint.size() == 1) {
16564     // GCC Constraint Letters
16565     switch (Constraint[0]) {
16566     default: break;
16567       // TODO: Slight differences here in allocation order and leaving
16568       // RIP in the class. Do they matter any more here than they do
16569       // in the normal allocation?
16570     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16571       if (Subtarget->is64Bit()) {
16572         if (VT == MVT::i32 || VT == MVT::f32)
16573           return std::make_pair(0U, &X86::GR32RegClass);
16574         if (VT == MVT::i16)
16575           return std::make_pair(0U, &X86::GR16RegClass);
16576         if (VT == MVT::i8 || VT == MVT::i1)
16577           return std::make_pair(0U, &X86::GR8RegClass);
16578         if (VT == MVT::i64 || VT == MVT::f64)
16579           return std::make_pair(0U, &X86::GR64RegClass);
16580         break;
16581       }
16582       // 32-bit fallthrough
16583     case 'Q':   // Q_REGS
16584       if (VT == MVT::i32 || VT == MVT::f32)
16585         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16586       if (VT == MVT::i16)
16587         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16588       if (VT == MVT::i8 || VT == MVT::i1)
16589         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16590       if (VT == MVT::i64)
16591         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16592       break;
16593     case 'r':   // GENERAL_REGS
16594     case 'l':   // INDEX_REGS
16595       if (VT == MVT::i8 || VT == MVT::i1)
16596         return std::make_pair(0U, &X86::GR8RegClass);
16597       if (VT == MVT::i16)
16598         return std::make_pair(0U, &X86::GR16RegClass);
16599       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16600         return std::make_pair(0U, &X86::GR32RegClass);
16601       return std::make_pair(0U, &X86::GR64RegClass);
16602     case 'R':   // LEGACY_REGS
16603       if (VT == MVT::i8 || VT == MVT::i1)
16604         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16605       if (VT == MVT::i16)
16606         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16607       if (VT == MVT::i32 || !Subtarget->is64Bit())
16608         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16609       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16610     case 'f':  // FP Stack registers.
16611       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16612       // value to the correct fpstack register class.
16613       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16614         return std::make_pair(0U, &X86::RFP32RegClass);
16615       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16616         return std::make_pair(0U, &X86::RFP64RegClass);
16617       return std::make_pair(0U, &X86::RFP80RegClass);
16618     case 'y':   // MMX_REGS if MMX allowed.
16619       if (!Subtarget->hasMMX()) break;
16620       return std::make_pair(0U, &X86::VR64RegClass);
16621     case 'Y':   // SSE_REGS if SSE2 allowed
16622       if (!Subtarget->hasSSE2()) break;
16623       // FALL THROUGH.
16624     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16625       if (!Subtarget->hasSSE1()) break;
16626
16627       switch (VT.getSimpleVT().SimpleTy) {
16628       default: break;
16629       // Scalar SSE types.
16630       case MVT::f32:
16631       case MVT::i32:
16632         return std::make_pair(0U, &X86::FR32RegClass);
16633       case MVT::f64:
16634       case MVT::i64:
16635         return std::make_pair(0U, &X86::FR64RegClass);
16636       // Vector types.
16637       case MVT::v16i8:
16638       case MVT::v8i16:
16639       case MVT::v4i32:
16640       case MVT::v2i64:
16641       case MVT::v4f32:
16642       case MVT::v2f64:
16643         return std::make_pair(0U, &X86::VR128RegClass);
16644       // AVX types.
16645       case MVT::v32i8:
16646       case MVT::v16i16:
16647       case MVT::v8i32:
16648       case MVT::v4i64:
16649       case MVT::v8f32:
16650       case MVT::v4f64:
16651         return std::make_pair(0U, &X86::VR256RegClass);
16652       }
16653       break;
16654     }
16655   }
16656
16657   // Use the default implementation in TargetLowering to convert the register
16658   // constraint into a member of a register class.
16659   std::pair<unsigned, const TargetRegisterClass*> Res;
16660   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16661
16662   // Not found as a standard register?
16663   if (Res.second == 0) {
16664     // Map st(0) -> st(7) -> ST0
16665     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16666         tolower(Constraint[1]) == 's' &&
16667         tolower(Constraint[2]) == 't' &&
16668         Constraint[3] == '(' &&
16669         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16670         Constraint[5] == ')' &&
16671         Constraint[6] == '}') {
16672
16673       Res.first = X86::ST0+Constraint[4]-'0';
16674       Res.second = &X86::RFP80RegClass;
16675       return Res;
16676     }
16677
16678     // GCC allows "st(0)" to be called just plain "st".
16679     if (StringRef("{st}").equals_lower(Constraint)) {
16680       Res.first = X86::ST0;
16681       Res.second = &X86::RFP80RegClass;
16682       return Res;
16683     }
16684
16685     // flags -> EFLAGS
16686     if (StringRef("{flags}").equals_lower(Constraint)) {
16687       Res.first = X86::EFLAGS;
16688       Res.second = &X86::CCRRegClass;
16689       return Res;
16690     }
16691
16692     // 'A' means EAX + EDX.
16693     if (Constraint == "A") {
16694       Res.first = X86::EAX;
16695       Res.second = &X86::GR32_ADRegClass;
16696       return Res;
16697     }
16698     return Res;
16699   }
16700
16701   // Otherwise, check to see if this is a register class of the wrong value
16702   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16703   // turn into {ax},{dx}.
16704   if (Res.second->hasType(VT))
16705     return Res;   // Correct type already, nothing to do.
16706
16707   // All of the single-register GCC register classes map their values onto
16708   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16709   // really want an 8-bit or 32-bit register, map to the appropriate register
16710   // class and return the appropriate register.
16711   if (Res.second == &X86::GR16RegClass) {
16712     if (VT == MVT::i8) {
16713       unsigned DestReg = 0;
16714       switch (Res.first) {
16715       default: break;
16716       case X86::AX: DestReg = X86::AL; break;
16717       case X86::DX: DestReg = X86::DL; break;
16718       case X86::CX: DestReg = X86::CL; break;
16719       case X86::BX: DestReg = X86::BL; break;
16720       }
16721       if (DestReg) {
16722         Res.first = DestReg;
16723         Res.second = &X86::GR8RegClass;
16724       }
16725     } else if (VT == MVT::i32) {
16726       unsigned DestReg = 0;
16727       switch (Res.first) {
16728       default: break;
16729       case X86::AX: DestReg = X86::EAX; break;
16730       case X86::DX: DestReg = X86::EDX; break;
16731       case X86::CX: DestReg = X86::ECX; break;
16732       case X86::BX: DestReg = X86::EBX; break;
16733       case X86::SI: DestReg = X86::ESI; break;
16734       case X86::DI: DestReg = X86::EDI; break;
16735       case X86::BP: DestReg = X86::EBP; break;
16736       case X86::SP: DestReg = X86::ESP; break;
16737       }
16738       if (DestReg) {
16739         Res.first = DestReg;
16740         Res.second = &X86::GR32RegClass;
16741       }
16742     } else if (VT == MVT::i64) {
16743       unsigned DestReg = 0;
16744       switch (Res.first) {
16745       default: break;
16746       case X86::AX: DestReg = X86::RAX; break;
16747       case X86::DX: DestReg = X86::RDX; break;
16748       case X86::CX: DestReg = X86::RCX; break;
16749       case X86::BX: DestReg = X86::RBX; break;
16750       case X86::SI: DestReg = X86::RSI; break;
16751       case X86::DI: DestReg = X86::RDI; break;
16752       case X86::BP: DestReg = X86::RBP; break;
16753       case X86::SP: DestReg = X86::RSP; break;
16754       }
16755       if (DestReg) {
16756         Res.first = DestReg;
16757         Res.second = &X86::GR64RegClass;
16758       }
16759     }
16760   } else if (Res.second == &X86::FR32RegClass ||
16761              Res.second == &X86::FR64RegClass ||
16762              Res.second == &X86::VR128RegClass) {
16763     // Handle references to XMM physical registers that got mapped into the
16764     // wrong class.  This can happen with constraints like {xmm0} where the
16765     // target independent register mapper will just pick the first match it can
16766     // find, ignoring the required type.
16767
16768     if (VT == MVT::f32 || VT == MVT::i32)
16769       Res.second = &X86::FR32RegClass;
16770     else if (VT == MVT::f64 || VT == MVT::i64)
16771       Res.second = &X86::FR64RegClass;
16772     else if (X86::VR128RegClass.hasType(VT))
16773       Res.second = &X86::VR128RegClass;
16774     else if (X86::VR256RegClass.hasType(VT))
16775       Res.second = &X86::VR256RegClass;
16776   }
16777
16778   return Res;
16779 }