X86: Shave off one shuffle from the pcmpeqq sequence for SSE2 by making use of and...
[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 "Utils/X86ShuffleDecode.h"
18 #include "X86.h"
19 #include "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/Constants.h"
35 #include "llvm/DerivedTypes.h"
36 #include "llvm/Function.h"
37 #include "llvm/GlobalAlias.h"
38 #include "llvm/GlobalVariable.h"
39 #include "llvm/Instructions.h"
40 #include "llvm/Intrinsics.h"
41 #include "llvm/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.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.getIntPtrConstant(NormalizedIdxVal);
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.getIntPtrConstant(NormalizedIdxVal);
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
162   RegInfo = TM.getRegisterInfo();
163   TD = getDataLayout();
164
165   // Set up the TargetLowering object.
166   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
167
168   // X86 is weird, it always uses i8 for shift amounts and setcc results.
169   setBooleanContents(ZeroOrOneBooleanContent);
170   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
172
173   // For 64-bit since we have so many registers use the ILP scheduler, for
174   // 32-bit code use the register pressure specific scheduling.
175   // For Atom, always use ILP scheduling.
176   if (Subtarget->isAtom())
177     setSchedulingPreference(Sched::ILP);
178   else if (Subtarget->is64Bit())
179     setSchedulingPreference(Sched::ILP);
180   else
181     setSchedulingPreference(Sched::RegPressure);
182   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
183
184   // Bypass i32 with i8 on Atom when compiling with O2
185   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
186     addBypassSlowDiv(32, 8);
187
188   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
189     // Setup Windows compiler runtime calls.
190     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
191     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
192     setLibcallName(RTLIB::SREM_I64, "_allrem");
193     setLibcallName(RTLIB::UREM_I64, "_aullrem");
194     setLibcallName(RTLIB::MUL_I64, "_allmul");
195     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
196     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
197     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
198     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
199     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
200
201     // The _ftol2 runtime function has an unusual calling conv, which
202     // is modeled by a special pseudo-instruction.
203     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
204     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
205     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
206     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
207   }
208
209   if (Subtarget->isTargetDarwin()) {
210     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
211     setUseUnderscoreSetJmp(false);
212     setUseUnderscoreLongJmp(false);
213   } else if (Subtarget->isTargetMingw()) {
214     // MS runtime is weird: it exports _setjmp, but longjmp!
215     setUseUnderscoreSetJmp(true);
216     setUseUnderscoreLongJmp(false);
217   } else {
218     setUseUnderscoreSetJmp(true);
219     setUseUnderscoreLongJmp(true);
220   }
221
222   // Set up the register classes.
223   addRegisterClass(MVT::i8, &X86::GR8RegClass);
224   addRegisterClass(MVT::i16, &X86::GR16RegClass);
225   addRegisterClass(MVT::i32, &X86::GR32RegClass);
226   if (Subtarget->is64Bit())
227     addRegisterClass(MVT::i64, &X86::GR64RegClass);
228
229   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
230
231   // We don't accept any truncstore of integer registers.
232   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
233   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
234   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
235   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
236   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
237   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
238
239   // SETOEQ and SETUNE require checking two conditions.
240   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
241   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
242   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
243   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
244   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
245   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
246
247   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
248   // operation.
249   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
250   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
251   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
252
253   if (Subtarget->is64Bit()) {
254     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
255     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
256   } else if (!TM.Options.UseSoftFloat) {
257     // We have an algorithm for SSE2->double, and we turn this into a
258     // 64-bit FILD followed by conditional FADD for other targets.
259     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
260     // We have an algorithm for SSE2, and we turn this into a 64-bit
261     // FILD for other targets.
262     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
263   }
264
265   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
266   // this operation.
267   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
268   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
269
270   if (!TM.Options.UseSoftFloat) {
271     // SSE has no i16 to fp conversion, only i32
272     if (X86ScalarSSEf32) {
273       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
274       // f32 and f64 cases are Legal, f80 case is not
275       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
276     } else {
277       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
278       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
279     }
280   } else {
281     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
282     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
283   }
284
285   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
286   // are Legal, f80 is custom lowered.
287   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
288   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
289
290   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
291   // this operation.
292   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
293   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
294
295   if (X86ScalarSSEf32) {
296     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
297     // f32 and f64 cases are Legal, f80 case is not
298     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
299   } else {
300     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
301     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
302   }
303
304   // Handle FP_TO_UINT by promoting the destination to a larger signed
305   // conversion.
306   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
307   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
308   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
309
310   if (Subtarget->is64Bit()) {
311     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
312     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
313   } else if (!TM.Options.UseSoftFloat) {
314     // Since AVX is a superset of SSE3, only check for SSE here.
315     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
316       // Expand FP_TO_UINT into a select.
317       // FIXME: We would like to use a Custom expander here eventually to do
318       // the optimal thing for SSE vs. the default expansion in the legalizer.
319       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
320     else
321       // With SSE3 we can use fisttpll to convert to a signed i64; without
322       // SSE, we're stuck with a fistpll.
323       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
324   }
325
326   if (isTargetFTOL()) {
327     // Use the _ftol2 runtime function, which has a pseudo-instruction
328     // to handle its weird calling convention.
329     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
330   }
331
332   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
333   if (!X86ScalarSSEf64) {
334     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
335     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
336     if (Subtarget->is64Bit()) {
337       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
338       // Without SSE, i64->f64 goes through memory.
339       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
340     }
341   }
342
343   // Scalar integer divide and remainder are lowered to use operations that
344   // produce two results, to match the available instructions. This exposes
345   // the two-result form to trivial CSE, which is able to combine x/y and x%y
346   // into a single instruction.
347   //
348   // Scalar integer multiply-high is also lowered to use two-result
349   // operations, to match the available instructions. However, plain multiply
350   // (low) operations are left as Legal, as there are single-result
351   // instructions for this in x86. Using the two-result multiply instructions
352   // when both high and low results are needed must be arranged by dagcombine.
353   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
354     MVT VT = IntVTs[i];
355     setOperationAction(ISD::MULHS, VT, Expand);
356     setOperationAction(ISD::MULHU, VT, Expand);
357     setOperationAction(ISD::SDIV, VT, Expand);
358     setOperationAction(ISD::UDIV, VT, Expand);
359     setOperationAction(ISD::SREM, VT, Expand);
360     setOperationAction(ISD::UREM, VT, Expand);
361
362     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
363     setOperationAction(ISD::ADDC, VT, Custom);
364     setOperationAction(ISD::ADDE, VT, Custom);
365     setOperationAction(ISD::SUBC, VT, Custom);
366     setOperationAction(ISD::SUBE, VT, Custom);
367   }
368
369   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
370   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
371   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
372   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
373   if (Subtarget->is64Bit())
374     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
375   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
376   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
377   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
378   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
379   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
380   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
381   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
382   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
383
384   // Promote the i8 variants and force them on up to i32 which has a shorter
385   // encoding.
386   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
387   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
388   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
389   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
390   if (Subtarget->hasBMI()) {
391     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
392     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
393     if (Subtarget->is64Bit())
394       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
395   } else {
396     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
397     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
398     if (Subtarget->is64Bit())
399       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
400   }
401
402   if (Subtarget->hasLZCNT()) {
403     // When promoting the i8 variants, force them to i32 for a shorter
404     // encoding.
405     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
406     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
407     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
408     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
409     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
410     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
411     if (Subtarget->is64Bit())
412       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
413   } else {
414     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
415     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
416     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
417     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
418     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
419     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
420     if (Subtarget->is64Bit()) {
421       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
422       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
423     }
424   }
425
426   if (Subtarget->hasPOPCNT()) {
427     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
428   } else {
429     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
430     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
431     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
432     if (Subtarget->is64Bit())
433       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
434   }
435
436   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
437   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
438
439   // These should be promoted to a larger select which is supported.
440   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
441   // X86 wants to expand cmov itself.
442   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
443   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
446   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
447   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
448   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
449   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
452   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
453   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
454   if (Subtarget->is64Bit()) {
455     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
456     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
457   }
458   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
459   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
460   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
461   // support continuation, user-level threading, and etc.. As a result, no
462   // other SjLj exception interfaces are implemented and please don't build
463   // your own exception handling based on them.
464   // LLVM/Clang supports zero-cost DWARF exception handling.
465   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
466   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
467
468   // Darwin ABI issue.
469   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
470   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
471   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
472   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
473   if (Subtarget->is64Bit())
474     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
475   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
476   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
477   if (Subtarget->is64Bit()) {
478     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
479     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
480     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
481     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
482     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
483   }
484   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
485   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
486   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
487   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
488   if (Subtarget->is64Bit()) {
489     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
490     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
491     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasSSE1())
495     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
496
497   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
498   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
499
500   // On X86 and X86-64, atomic operations are lowered to locked instructions.
501   // Locked instructions, in turn, have implicit fence semantics (all memory
502   // operations are flushed before issuing the locked instruction, and they
503   // are not buffered), so we can fold away the common pattern of
504   // fence-atomic-fence.
505   setShouldFoldAtomicFences(true);
506
507   // Expand certain atomics
508   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
509     MVT VT = IntVTs[i];
510     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
512     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
513   }
514
515   if (!Subtarget->is64Bit()) {
516     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
517     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
518     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
519     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
520     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
521     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
522     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
523     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
524     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
525     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
526     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
527     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
528   }
529
530   if (Subtarget->hasCmpxchg16b()) {
531     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
532   }
533
534   // FIXME - use subtarget debug flags
535   if (!Subtarget->isTargetDarwin() &&
536       !Subtarget->isTargetELF() &&
537       !Subtarget->isTargetCygMing()) {
538     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
539   }
540
541   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
542   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
543   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
544   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
545   if (Subtarget->is64Bit()) {
546     setExceptionPointerRegister(X86::RAX);
547     setExceptionSelectorRegister(X86::RDX);
548   } else {
549     setExceptionPointerRegister(X86::EAX);
550     setExceptionSelectorRegister(X86::EDX);
551   }
552   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
553   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
554
555   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
556   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
557
558   setOperationAction(ISD::TRAP, MVT::Other, Legal);
559   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
560
561   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
563   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
564   if (Subtarget->is64Bit()) {
565     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
566     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
567   } else {
568     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
569     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
570   }
571
572   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
573   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
574
575   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577                        MVT::i64 : MVT::i32, Custom);
578   else if (TM.Options.EnableSegmentedStacks)
579     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580                        MVT::i64 : MVT::i32, Custom);
581   else
582     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583                        MVT::i64 : MVT::i32, Expand);
584
585   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586     // f32 and f64 use SSE.
587     // Set up the FP register classes.
588     addRegisterClass(MVT::f32, &X86::FR32RegClass);
589     addRegisterClass(MVT::f64, &X86::FR64RegClass);
590
591     // Use ANDPD to simulate FABS.
592     setOperationAction(ISD::FABS , MVT::f64, Custom);
593     setOperationAction(ISD::FABS , MVT::f32, Custom);
594
595     // Use XORP to simulate FNEG.
596     setOperationAction(ISD::FNEG , MVT::f64, Custom);
597     setOperationAction(ISD::FNEG , MVT::f32, Custom);
598
599     // Use ANDPD and ORPD to simulate FCOPYSIGN.
600     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
602
603     // Lower this to FGETSIGNx86 plus an AND.
604     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
606
607     // We don't support sin/cos/fmod
608     setOperationAction(ISD::FSIN , MVT::f64, Expand);
609     setOperationAction(ISD::FCOS , MVT::f64, Expand);
610     setOperationAction(ISD::FSIN , MVT::f32, Expand);
611     setOperationAction(ISD::FCOS , MVT::f32, Expand);
612
613     // Expand FP immediates into loads from the stack, except for the special
614     // cases we handle.
615     addLegalFPImmediate(APFloat(+0.0)); // xorpd
616     addLegalFPImmediate(APFloat(+0.0f)); // xorps
617   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
618     // Use SSE for f32, x87 for f64.
619     // Set up the FP register classes.
620     addRegisterClass(MVT::f32, &X86::FR32RegClass);
621     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
622
623     // Use ANDPS to simulate FABS.
624     setOperationAction(ISD::FABS , MVT::f32, Custom);
625
626     // Use XORP to simulate FNEG.
627     setOperationAction(ISD::FNEG , MVT::f32, Custom);
628
629     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
630
631     // Use ANDPS and ORPS to simulate FCOPYSIGN.
632     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
634
635     // We don't support sin/cos/fmod
636     setOperationAction(ISD::FSIN , MVT::f32, Expand);
637     setOperationAction(ISD::FCOS , MVT::f32, Expand);
638
639     // Special cases we handle for FP constants.
640     addLegalFPImmediate(APFloat(+0.0f)); // xorps
641     addLegalFPImmediate(APFloat(+0.0)); // FLD0
642     addLegalFPImmediate(APFloat(+1.0)); // FLD1
643     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
644     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
645
646     if (!TM.Options.UnsafeFPMath) {
647       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
648       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
649     }
650   } else if (!TM.Options.UseSoftFloat) {
651     // f32 and f64 in x87.
652     // Set up the FP register classes.
653     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
654     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
655
656     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
657     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
658     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
660
661     if (!TM.Options.UnsafeFPMath) {
662       setOperationAction(ISD::FSIN           , MVT::f32  , Expand);
663       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
664       setOperationAction(ISD::FCOS           , MVT::f32  , Expand);
665       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
666     }
667     addLegalFPImmediate(APFloat(+0.0)); // FLD0
668     addLegalFPImmediate(APFloat(+1.0)); // FLD1
669     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
672     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
673     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
674     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
675   }
676
677   // We don't support FMA.
678   setOperationAction(ISD::FMA, MVT::f64, Expand);
679   setOperationAction(ISD::FMA, MVT::f32, Expand);
680
681   // Long double always uses X87.
682   if (!TM.Options.UseSoftFloat) {
683     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
684     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
685     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
686     {
687       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
688       addLegalFPImmediate(TmpFlt);  // FLD0
689       TmpFlt.changeSign();
690       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
691
692       bool ignored;
693       APFloat TmpFlt2(+1.0);
694       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
695                       &ignored);
696       addLegalFPImmediate(TmpFlt2);  // FLD1
697       TmpFlt2.changeSign();
698       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
699     }
700
701     if (!TM.Options.UnsafeFPMath) {
702       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
703       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
704     }
705
706     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
707     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
708     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
709     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
710     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
711     setOperationAction(ISD::FMA, MVT::f80, Expand);
712   }
713
714   // Always use a library call for pow.
715   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
716   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
717   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
718
719   setOperationAction(ISD::FLOG, MVT::f80, Expand);
720   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722   setOperationAction(ISD::FEXP, MVT::f80, Expand);
723   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
724
725   // First set operation action for all vector types to either promote
726   // (for widening) or expand (for scalarization). Then we will selectively
727   // turn on ones that can be effectively codegen'd.
728   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
729            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
730     MVT VT = (MVT::SimpleValueType)i;
731     setOperationAction(ISD::ADD , VT, Expand);
732     setOperationAction(ISD::SUB , VT, Expand);
733     setOperationAction(ISD::FADD, VT, Expand);
734     setOperationAction(ISD::FNEG, VT, Expand);
735     setOperationAction(ISD::FSUB, VT, Expand);
736     setOperationAction(ISD::MUL , VT, Expand);
737     setOperationAction(ISD::FMUL, VT, Expand);
738     setOperationAction(ISD::SDIV, VT, Expand);
739     setOperationAction(ISD::UDIV, VT, Expand);
740     setOperationAction(ISD::FDIV, VT, Expand);
741     setOperationAction(ISD::SREM, VT, Expand);
742     setOperationAction(ISD::UREM, VT, Expand);
743     setOperationAction(ISD::LOAD, VT, Expand);
744     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
745     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
746     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
747     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
748     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
749     setOperationAction(ISD::FABS, VT, Expand);
750     setOperationAction(ISD::FSIN, VT, Expand);
751     setOperationAction(ISD::FCOS, VT, Expand);
752     setOperationAction(ISD::FREM, VT, Expand);
753     setOperationAction(ISD::FMA,  VT, Expand);
754     setOperationAction(ISD::FPOWI, VT, Expand);
755     setOperationAction(ISD::FSQRT, VT, Expand);
756     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
757     setOperationAction(ISD::FFLOOR, VT, Expand);
758     setOperationAction(ISD::FCEIL, VT, Expand);
759     setOperationAction(ISD::FTRUNC, VT, Expand);
760     setOperationAction(ISD::FRINT, VT, Expand);
761     setOperationAction(ISD::FNEARBYINT, VT, Expand);
762     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
763     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
764     setOperationAction(ISD::SDIVREM, VT, Expand);
765     setOperationAction(ISD::UDIVREM, VT, Expand);
766     setOperationAction(ISD::FPOW, VT, Expand);
767     setOperationAction(ISD::CTPOP, VT, Expand);
768     setOperationAction(ISD::CTTZ, VT, Expand);
769     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
770     setOperationAction(ISD::CTLZ, VT, Expand);
771     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
772     setOperationAction(ISD::SHL, VT, Expand);
773     setOperationAction(ISD::SRA, VT, Expand);
774     setOperationAction(ISD::SRL, VT, Expand);
775     setOperationAction(ISD::ROTL, VT, Expand);
776     setOperationAction(ISD::ROTR, VT, Expand);
777     setOperationAction(ISD::BSWAP, VT, Expand);
778     setOperationAction(ISD::SETCC, VT, Expand);
779     setOperationAction(ISD::FLOG, VT, Expand);
780     setOperationAction(ISD::FLOG2, VT, Expand);
781     setOperationAction(ISD::FLOG10, VT, Expand);
782     setOperationAction(ISD::FEXP, VT, Expand);
783     setOperationAction(ISD::FEXP2, VT, Expand);
784     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
785     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
786     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
787     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
788     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
789     setOperationAction(ISD::TRUNCATE, VT, Expand);
790     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
791     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
792     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
793     setOperationAction(ISD::VSELECT, VT, Expand);
794     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
795              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
796       setTruncStoreAction(VT,
797                           (MVT::SimpleValueType)InnerVT, Expand);
798     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
799     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
800     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
801   }
802
803   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
804   // with -msoft-float, disable use of MMX as well.
805   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
806     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
807     // No operations on x86mmx supported, everything uses intrinsics.
808   }
809
810   // MMX-sized vectors (other than x86mmx) are expected to be expanded
811   // into smaller operations.
812   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
813   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
814   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
815   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
816   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
817   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
818   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
819   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
820   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
821   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
822   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
823   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
824   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
825   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
826   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
827   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
828   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
829   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
830   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
831   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
832   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
833   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
834   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
835   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
836   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
837   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
838   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
839   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
840   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
841
842   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
843     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
844
845     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
846     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
847     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
848     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
849     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
850     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
851     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
852     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
853     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
854     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
855     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
856     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
857   }
858
859   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
860     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
861
862     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
863     // registers cannot be used even for integer operations.
864     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
865     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
866     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
867     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
868
869     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
870     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
871     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
872     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
873     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
874     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
875     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
876     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
877     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
878     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
879     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
880     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
881     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
882     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
883     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
884     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
885     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
886     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
887
888     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
889     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
890     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
891     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
892
893     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
894     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
895     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
896     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
897     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
898
899     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
900     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
901       MVT VT = (MVT::SimpleValueType)i;
902       // Do not attempt to custom lower non-power-of-2 vectors
903       if (!isPowerOf2_32(VT.getVectorNumElements()))
904         continue;
905       // Do not attempt to custom lower non-128-bit vectors
906       if (!VT.is128BitVector())
907         continue;
908       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
909       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
910       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
911     }
912
913     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
914     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
915     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
916     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
917     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
918     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
919
920     if (Subtarget->is64Bit()) {
921       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
922       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
923     }
924
925     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
926     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
927       MVT VT = (MVT::SimpleValueType)i;
928
929       // Do not attempt to promote non-128-bit vectors
930       if (!VT.is128BitVector())
931         continue;
932
933       setOperationAction(ISD::AND,    VT, Promote);
934       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
935       setOperationAction(ISD::OR,     VT, Promote);
936       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
937       setOperationAction(ISD::XOR,    VT, Promote);
938       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
939       setOperationAction(ISD::LOAD,   VT, Promote);
940       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
941       setOperationAction(ISD::SELECT, VT, Promote);
942       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
943     }
944
945     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
946
947     // Custom lower v2i64 and v2f64 selects.
948     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
949     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
950     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
951     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
952
953     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
954     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
955
956     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
957     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
958     // As there is no 64-bit GPR available, we need build a special custom
959     // sequence to convert from v2i32 to v2f32.
960     if (!Subtarget->is64Bit())
961       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
962
963     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
964     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
965
966     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
967   }
968
969   if (Subtarget->hasSSE41()) {
970     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
971     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
972     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
973     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
974     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
975     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
976     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
977     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
978     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
979     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
980
981     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
982     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
983     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
984     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
985     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
986     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
987     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
988     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
989     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
990     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
991
992     // FIXME: Do we need to handle scalar-to-vector here?
993     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
994
995     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
996     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
997     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
998     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
999     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1000
1001     // i8 and i16 vectors are custom , because the source register and source
1002     // source memory operand types are not the same width.  f32 vectors are
1003     // custom since the immediate controlling the insert encodes additional
1004     // information.
1005     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1006     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1007     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1008     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1009
1010     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1011     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1012     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1013     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1014
1015     // FIXME: these should be Legal but thats only for the case where
1016     // the index is constant.  For now custom expand to deal with that.
1017     if (Subtarget->is64Bit()) {
1018       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1019       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1020     }
1021   }
1022
1023   if (Subtarget->hasSSE2()) {
1024     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1025     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1026
1027     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1028     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1029
1030     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1031     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1032
1033     if (Subtarget->hasInt256()) {
1034       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1035       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1036
1037       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1038       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1039
1040       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1041     } else {
1042       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1043       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1044
1045       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1046       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1047
1048       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1049     }
1050   }
1051
1052   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1053     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1054     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1055     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1056     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1057     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1058     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1059
1060     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1061     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1062     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1063
1064     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1065     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1066     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1067     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1068     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1069     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1070     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1071     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1072     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1073     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1074     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1075     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1076
1077     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1078     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1079     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1080     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1081     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1082     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1083     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1084     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1085     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1086     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1087     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1088     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1089
1090     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1091
1092     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1093
1094     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1095     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1096     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1097
1098     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1099     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1100     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1101
1102     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1103
1104     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1105     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1106
1107     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1108     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1109
1110     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1111     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1112
1113     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1114     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1115     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1116     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1117
1118     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1119     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1120     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1121
1122     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1123     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1124     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1125     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1126
1127     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1128       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1129       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1130       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1131       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1132       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1133       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1134     }
1135
1136     if (Subtarget->hasInt256()) {
1137       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1138       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1139       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1140       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1141
1142       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1143       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1144       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1145       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1146
1147       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1148       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1149       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1150       // Don't lower v32i8 because there is no 128-bit byte mul
1151
1152       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1153
1154       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1155       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1156
1157       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1158       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1159
1160       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1161     } else {
1162       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1163       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1164       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1165       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1166
1167       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1168       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1169       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1170       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1171
1172       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1173       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1174       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1175       // Don't lower v32i8 because there is no 128-bit byte mul
1176
1177       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1178       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1179
1180       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1181       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1182
1183       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1184     }
1185
1186     // Custom lower several nodes for 256-bit types.
1187     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1188              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1189       MVT VT = (MVT::SimpleValueType)i;
1190
1191       // Extract subvector is special because the value type
1192       // (result) is 128-bit but the source is 256-bit wide.
1193       if (VT.is128BitVector())
1194         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1195
1196       // Do not attempt to custom lower other non-256-bit vectors
1197       if (!VT.is256BitVector())
1198         continue;
1199
1200       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1201       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1202       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1203       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1204       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1205       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1206       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1207     }
1208
1209     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1210     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1211       MVT VT = (MVT::SimpleValueType)i;
1212
1213       // Do not attempt to promote non-256-bit vectors
1214       if (!VT.is256BitVector())
1215         continue;
1216
1217       setOperationAction(ISD::AND,    VT, Promote);
1218       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1219       setOperationAction(ISD::OR,     VT, Promote);
1220       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1221       setOperationAction(ISD::XOR,    VT, Promote);
1222       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1223       setOperationAction(ISD::LOAD,   VT, Promote);
1224       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1225       setOperationAction(ISD::SELECT, VT, Promote);
1226       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1227     }
1228   }
1229
1230   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1231   // of this type with custom code.
1232   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1233            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1234     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1235                        Custom);
1236   }
1237
1238   // We want to custom lower some of our intrinsics.
1239   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1240   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1241
1242   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1243   // handle type legalization for these operations here.
1244   //
1245   // FIXME: We really should do custom legalization for addition and
1246   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1247   // than generic legalization for 64-bit multiplication-with-overflow, though.
1248   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1249     // Add/Sub/Mul with overflow operations are custom lowered.
1250     MVT VT = IntVTs[i];
1251     setOperationAction(ISD::SADDO, VT, Custom);
1252     setOperationAction(ISD::UADDO, VT, Custom);
1253     setOperationAction(ISD::SSUBO, VT, Custom);
1254     setOperationAction(ISD::USUBO, VT, Custom);
1255     setOperationAction(ISD::SMULO, VT, Custom);
1256     setOperationAction(ISD::UMULO, VT, Custom);
1257   }
1258
1259   // There are no 8-bit 3-address imul/mul instructions
1260   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1261   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1262
1263   if (!Subtarget->is64Bit()) {
1264     // These libcalls are not available in 32-bit.
1265     setLibcallName(RTLIB::SHL_I128, 0);
1266     setLibcallName(RTLIB::SRL_I128, 0);
1267     setLibcallName(RTLIB::SRA_I128, 0);
1268   }
1269
1270   // We have target-specific dag combine patterns for the following nodes:
1271   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1272   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1273   setTargetDAGCombine(ISD::VSELECT);
1274   setTargetDAGCombine(ISD::SELECT);
1275   setTargetDAGCombine(ISD::SHL);
1276   setTargetDAGCombine(ISD::SRA);
1277   setTargetDAGCombine(ISD::SRL);
1278   setTargetDAGCombine(ISD::OR);
1279   setTargetDAGCombine(ISD::AND);
1280   setTargetDAGCombine(ISD::ADD);
1281   setTargetDAGCombine(ISD::FADD);
1282   setTargetDAGCombine(ISD::FSUB);
1283   setTargetDAGCombine(ISD::FMA);
1284   setTargetDAGCombine(ISD::SUB);
1285   setTargetDAGCombine(ISD::LOAD);
1286   setTargetDAGCombine(ISD::STORE);
1287   setTargetDAGCombine(ISD::ZERO_EXTEND);
1288   setTargetDAGCombine(ISD::ANY_EXTEND);
1289   setTargetDAGCombine(ISD::SIGN_EXTEND);
1290   setTargetDAGCombine(ISD::TRUNCATE);
1291   setTargetDAGCombine(ISD::SINT_TO_FP);
1292   setTargetDAGCombine(ISD::SETCC);
1293   if (Subtarget->is64Bit())
1294     setTargetDAGCombine(ISD::MUL);
1295   setTargetDAGCombine(ISD::XOR);
1296
1297   computeRegisterProperties();
1298
1299   // On Darwin, -Os means optimize for size without hurting performance,
1300   // do not reduce the limit.
1301   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1302   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1303   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1304   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1305   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1306   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1307   setPrefLoopAlignment(4); // 2^4 bytes.
1308   benefitFromCodePlacementOpt = true;
1309
1310   // Predictable cmov don't hurt on atom because it's in-order.
1311   predictableSelectIsExpensive = !Subtarget->isAtom();
1312
1313   setPrefFunctionAlignment(4); // 2^4 bytes.
1314 }
1315
1316 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1317   if (!VT.isVector()) return MVT::i8;
1318   return VT.changeVectorElementTypeToInteger();
1319 }
1320
1321 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1322 /// the desired ByVal argument alignment.
1323 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1324   if (MaxAlign == 16)
1325     return;
1326   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1327     if (VTy->getBitWidth() == 128)
1328       MaxAlign = 16;
1329   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1330     unsigned EltAlign = 0;
1331     getMaxByValAlign(ATy->getElementType(), EltAlign);
1332     if (EltAlign > MaxAlign)
1333       MaxAlign = EltAlign;
1334   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1335     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1336       unsigned EltAlign = 0;
1337       getMaxByValAlign(STy->getElementType(i), EltAlign);
1338       if (EltAlign > MaxAlign)
1339         MaxAlign = EltAlign;
1340       if (MaxAlign == 16)
1341         break;
1342     }
1343   }
1344 }
1345
1346 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1347 /// function arguments in the caller parameter area. For X86, aggregates
1348 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1349 /// are at 4-byte boundaries.
1350 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1351   if (Subtarget->is64Bit()) {
1352     // Max of 8 and alignment of type.
1353     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1354     if (TyAlign > 8)
1355       return TyAlign;
1356     return 8;
1357   }
1358
1359   unsigned Align = 4;
1360   if (Subtarget->hasSSE1())
1361     getMaxByValAlign(Ty, Align);
1362   return Align;
1363 }
1364
1365 /// getOptimalMemOpType - Returns the target specific optimal type for load
1366 /// and store operations as a result of memset, memcpy, and memmove
1367 /// lowering. If DstAlign is zero that means it's safe to destination
1368 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1369 /// means there isn't a need to check it against alignment requirement,
1370 /// probably because the source does not need to be loaded. If 'IsMemset' is
1371 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1372 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1373 /// source is constant so it does not need to be loaded.
1374 /// It returns EVT::Other if the type should be determined using generic
1375 /// target-independent logic.
1376 EVT
1377 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1378                                        unsigned DstAlign, unsigned SrcAlign,
1379                                        bool IsMemset, bool ZeroMemset,
1380                                        bool MemcpyStrSrc,
1381                                        MachineFunction &MF) const {
1382   const Function *F = MF.getFunction();
1383   if ((!IsMemset || ZeroMemset) &&
1384       !F->getFnAttributes().hasAttribute(Attribute::NoImplicitFloat)) {
1385     if (Size >= 16 &&
1386         (Subtarget->isUnalignedMemAccessFast() ||
1387          ((DstAlign == 0 || DstAlign >= 16) &&
1388           (SrcAlign == 0 || SrcAlign >= 16)))) {
1389       if (Size >= 32) {
1390         if (Subtarget->hasInt256())
1391           return MVT::v8i32;
1392         if (Subtarget->hasFp256())
1393           return MVT::v8f32;
1394       }
1395       if (Subtarget->hasSSE2())
1396         return MVT::v4i32;
1397       if (Subtarget->hasSSE1())
1398         return MVT::v4f32;
1399     } else if (!MemcpyStrSrc && Size >= 8 &&
1400                !Subtarget->is64Bit() &&
1401                Subtarget->hasSSE2()) {
1402       // Do not use f64 to lower memcpy if source is string constant. It's
1403       // better to use i32 to avoid the loads.
1404       return MVT::f64;
1405     }
1406   }
1407   if (Subtarget->is64Bit() && Size >= 8)
1408     return MVT::i64;
1409   return MVT::i32;
1410 }
1411
1412 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1413   if (VT == MVT::f32)
1414     return X86ScalarSSEf32;
1415   else if (VT == MVT::f64)
1416     return X86ScalarSSEf64;
1417   return true;
1418 }
1419
1420 bool
1421 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1422   if (Fast)
1423     *Fast = Subtarget->isUnalignedMemAccessFast();
1424   return true;
1425 }
1426
1427 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1428 /// current function.  The returned value is a member of the
1429 /// MachineJumpTableInfo::JTEntryKind enum.
1430 unsigned X86TargetLowering::getJumpTableEncoding() const {
1431   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1432   // symbol.
1433   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1434       Subtarget->isPICStyleGOT())
1435     return MachineJumpTableInfo::EK_Custom32;
1436
1437   // Otherwise, use the normal jump table encoding heuristics.
1438   return TargetLowering::getJumpTableEncoding();
1439 }
1440
1441 const MCExpr *
1442 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1443                                              const MachineBasicBlock *MBB,
1444                                              unsigned uid,MCContext &Ctx) const{
1445   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1446          Subtarget->isPICStyleGOT());
1447   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1448   // entries.
1449   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1450                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1451 }
1452
1453 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1454 /// jumptable.
1455 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1456                                                     SelectionDAG &DAG) const {
1457   if (!Subtarget->is64Bit())
1458     // This doesn't have DebugLoc associated with it, but is not really the
1459     // same as a Register.
1460     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1461   return Table;
1462 }
1463
1464 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1465 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1466 /// MCExpr.
1467 const MCExpr *X86TargetLowering::
1468 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1469                              MCContext &Ctx) const {
1470   // X86-64 uses RIP relative addressing based on the jump table label.
1471   if (Subtarget->isPICStyleRIPRel())
1472     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1473
1474   // Otherwise, the reference is relative to the PIC base.
1475   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1476 }
1477
1478 // FIXME: Why this routine is here? Move to RegInfo!
1479 std::pair<const TargetRegisterClass*, uint8_t>
1480 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1481   const TargetRegisterClass *RRC = 0;
1482   uint8_t Cost = 1;
1483   switch (VT.SimpleTy) {
1484   default:
1485     return TargetLowering::findRepresentativeClass(VT);
1486   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1487     RRC = Subtarget->is64Bit() ?
1488       (const TargetRegisterClass*)&X86::GR64RegClass :
1489       (const TargetRegisterClass*)&X86::GR32RegClass;
1490     break;
1491   case MVT::x86mmx:
1492     RRC = &X86::VR64RegClass;
1493     break;
1494   case MVT::f32: case MVT::f64:
1495   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1496   case MVT::v4f32: case MVT::v2f64:
1497   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1498   case MVT::v4f64:
1499     RRC = &X86::VR128RegClass;
1500     break;
1501   }
1502   return std::make_pair(RRC, Cost);
1503 }
1504
1505 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1506                                                unsigned &Offset) const {
1507   if (!Subtarget->isTargetLinux())
1508     return false;
1509
1510   if (Subtarget->is64Bit()) {
1511     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1512     Offset = 0x28;
1513     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1514       AddressSpace = 256;
1515     else
1516       AddressSpace = 257;
1517   } else {
1518     // %gs:0x14 on i386
1519     Offset = 0x14;
1520     AddressSpace = 256;
1521   }
1522   return true;
1523 }
1524
1525 //===----------------------------------------------------------------------===//
1526 //               Return Value Calling Convention Implementation
1527 //===----------------------------------------------------------------------===//
1528
1529 #include "X86GenCallingConv.inc"
1530
1531 bool
1532 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1533                                   MachineFunction &MF, bool isVarArg,
1534                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1535                         LLVMContext &Context) const {
1536   SmallVector<CCValAssign, 16> RVLocs;
1537   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1538                  RVLocs, Context);
1539   return CCInfo.CheckReturn(Outs, RetCC_X86);
1540 }
1541
1542 SDValue
1543 X86TargetLowering::LowerReturn(SDValue Chain,
1544                                CallingConv::ID CallConv, bool isVarArg,
1545                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1546                                const SmallVectorImpl<SDValue> &OutVals,
1547                                DebugLoc dl, SelectionDAG &DAG) const {
1548   MachineFunction &MF = DAG.getMachineFunction();
1549   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1550
1551   SmallVector<CCValAssign, 16> RVLocs;
1552   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1553                  RVLocs, *DAG.getContext());
1554   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1555
1556   // Add the regs to the liveout set for the function.
1557   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1558   for (unsigned i = 0; i != RVLocs.size(); ++i)
1559     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1560       MRI.addLiveOut(RVLocs[i].getLocReg());
1561
1562   SDValue Flag;
1563
1564   SmallVector<SDValue, 6> RetOps;
1565   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1566   // Operand #1 = Bytes To Pop
1567   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1568                    MVT::i16));
1569
1570   // Copy the result values into the output registers.
1571   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1572     CCValAssign &VA = RVLocs[i];
1573     assert(VA.isRegLoc() && "Can only return in registers!");
1574     SDValue ValToCopy = OutVals[i];
1575     EVT ValVT = ValToCopy.getValueType();
1576
1577     // Promote values to the appropriate types
1578     if (VA.getLocInfo() == CCValAssign::SExt)
1579       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1580     else if (VA.getLocInfo() == CCValAssign::ZExt)
1581       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1582     else if (VA.getLocInfo() == CCValAssign::AExt)
1583       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1584     else if (VA.getLocInfo() == CCValAssign::BCvt)
1585       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1586
1587     // If this is x86-64, and we disabled SSE, we can't return FP values,
1588     // or SSE or MMX vectors.
1589     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1590          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1591           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1592       report_fatal_error("SSE register return with SSE disabled");
1593     }
1594     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1595     // llvm-gcc has never done it right and no one has noticed, so this
1596     // should be OK for now.
1597     if (ValVT == MVT::f64 &&
1598         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1599       report_fatal_error("SSE2 register return with SSE2 disabled");
1600
1601     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1602     // the RET instruction and handled by the FP Stackifier.
1603     if (VA.getLocReg() == X86::ST0 ||
1604         VA.getLocReg() == X86::ST1) {
1605       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1606       // change the value to the FP stack register class.
1607       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1608         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1609       RetOps.push_back(ValToCopy);
1610       // Don't emit a copytoreg.
1611       continue;
1612     }
1613
1614     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1615     // which is returned in RAX / RDX.
1616     if (Subtarget->is64Bit()) {
1617       if (ValVT == MVT::x86mmx) {
1618         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1619           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1620           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1621                                   ValToCopy);
1622           // If we don't have SSE2 available, convert to v4f32 so the generated
1623           // register is legal.
1624           if (!Subtarget->hasSSE2())
1625             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1626         }
1627       }
1628     }
1629
1630     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1631     Flag = Chain.getValue(1);
1632   }
1633
1634   // The x86-64 ABI for returning structs by value requires that we copy
1635   // the sret argument into %rax for the return. We saved the argument into
1636   // a virtual register in the entry block, so now we copy the value out
1637   // and into %rax.
1638   if (Subtarget->is64Bit() &&
1639       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1640     MachineFunction &MF = DAG.getMachineFunction();
1641     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1642     unsigned Reg = FuncInfo->getSRetReturnReg();
1643     assert(Reg &&
1644            "SRetReturnReg should have been set in LowerFormalArguments().");
1645     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1646
1647     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1648     Flag = Chain.getValue(1);
1649
1650     // RAX now acts like a return value.
1651     MRI.addLiveOut(X86::RAX);
1652   }
1653
1654   RetOps[0] = Chain;  // Update chain.
1655
1656   // Add the flag if we have it.
1657   if (Flag.getNode())
1658     RetOps.push_back(Flag);
1659
1660   return DAG.getNode(X86ISD::RET_FLAG, dl,
1661                      MVT::Other, &RetOps[0], RetOps.size());
1662 }
1663
1664 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1665   if (N->getNumValues() != 1)
1666     return false;
1667   if (!N->hasNUsesOfValue(1, 0))
1668     return false;
1669
1670   SDValue TCChain = Chain;
1671   SDNode *Copy = *N->use_begin();
1672   if (Copy->getOpcode() == ISD::CopyToReg) {
1673     // If the copy has a glue operand, we conservatively assume it isn't safe to
1674     // perform a tail call.
1675     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1676       return false;
1677     TCChain = Copy->getOperand(0);
1678   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1679     return false;
1680
1681   bool HasRet = false;
1682   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1683        UI != UE; ++UI) {
1684     if (UI->getOpcode() != X86ISD::RET_FLAG)
1685       return false;
1686     HasRet = true;
1687   }
1688
1689   if (!HasRet)
1690     return false;
1691
1692   Chain = TCChain;
1693   return true;
1694 }
1695
1696 MVT
1697 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1698                                             ISD::NodeType ExtendKind) const {
1699   MVT ReturnMVT;
1700   // TODO: Is this also valid on 32-bit?
1701   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1702     ReturnMVT = MVT::i8;
1703   else
1704     ReturnMVT = MVT::i32;
1705
1706   MVT MinVT = getRegisterType(ReturnMVT);
1707   return VT.bitsLT(MinVT) ? MinVT : VT;
1708 }
1709
1710 /// LowerCallResult - Lower the result values of a call into the
1711 /// appropriate copies out of appropriate physical registers.
1712 ///
1713 SDValue
1714 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1715                                    CallingConv::ID CallConv, bool isVarArg,
1716                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1717                                    DebugLoc dl, SelectionDAG &DAG,
1718                                    SmallVectorImpl<SDValue> &InVals) const {
1719
1720   // Assign locations to each value returned by this call.
1721   SmallVector<CCValAssign, 16> RVLocs;
1722   bool Is64Bit = Subtarget->is64Bit();
1723   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1724                  getTargetMachine(), RVLocs, *DAG.getContext());
1725   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1726
1727   // Copy all of the result registers out of their specified physreg.
1728   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1729     CCValAssign &VA = RVLocs[i];
1730     EVT CopyVT = VA.getValVT();
1731
1732     // If this is x86-64, and we disabled SSE, we can't return FP values
1733     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1734         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1735       report_fatal_error("SSE register return with SSE disabled");
1736     }
1737
1738     SDValue Val;
1739
1740     // If this is a call to a function that returns an fp value on the floating
1741     // point stack, we must guarantee the value is popped from the stack, so
1742     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1743     // if the return value is not used. We use the FpPOP_RETVAL instruction
1744     // instead.
1745     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1746       // If we prefer to use the value in xmm registers, copy it out as f80 and
1747       // use a truncate to move it from fp stack reg to xmm reg.
1748       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1749       SDValue Ops[] = { Chain, InFlag };
1750       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1751                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1752       Val = Chain.getValue(0);
1753
1754       // Round the f80 to the right size, which also moves it to the appropriate
1755       // xmm register.
1756       if (CopyVT != VA.getValVT())
1757         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1758                           // This truncation won't change the value.
1759                           DAG.getIntPtrConstant(1));
1760     } else {
1761       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1762                                  CopyVT, InFlag).getValue(1);
1763       Val = Chain.getValue(0);
1764     }
1765     InFlag = Chain.getValue(2);
1766     InVals.push_back(Val);
1767   }
1768
1769   return Chain;
1770 }
1771
1772 //===----------------------------------------------------------------------===//
1773 //                C & StdCall & Fast Calling Convention implementation
1774 //===----------------------------------------------------------------------===//
1775 //  StdCall calling convention seems to be standard for many Windows' API
1776 //  routines and around. It differs from C calling convention just a little:
1777 //  callee should clean up the stack, not caller. Symbols should be also
1778 //  decorated in some fancy way :) It doesn't support any vector arguments.
1779 //  For info on fast calling convention see Fast Calling Convention (tail call)
1780 //  implementation LowerX86_32FastCCCallTo.
1781
1782 /// CallIsStructReturn - Determines whether a call uses struct return
1783 /// semantics.
1784 enum StructReturnType {
1785   NotStructReturn,
1786   RegStructReturn,
1787   StackStructReturn
1788 };
1789 static StructReturnType
1790 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1791   if (Outs.empty())
1792     return NotStructReturn;
1793
1794   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1795   if (!Flags.isSRet())
1796     return NotStructReturn;
1797   if (Flags.isInReg())
1798     return RegStructReturn;
1799   return StackStructReturn;
1800 }
1801
1802 /// ArgsAreStructReturn - Determines whether a function uses struct
1803 /// return semantics.
1804 static StructReturnType
1805 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1806   if (Ins.empty())
1807     return NotStructReturn;
1808
1809   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1810   if (!Flags.isSRet())
1811     return NotStructReturn;
1812   if (Flags.isInReg())
1813     return RegStructReturn;
1814   return StackStructReturn;
1815 }
1816
1817 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1818 /// by "Src" to address "Dst" with size and alignment information specified by
1819 /// the specific parameter attribute. The copy will be passed as a byval
1820 /// function parameter.
1821 static SDValue
1822 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1823                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1824                           DebugLoc dl) {
1825   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1826
1827   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1828                        /*isVolatile*/false, /*AlwaysInline=*/true,
1829                        MachinePointerInfo(), MachinePointerInfo());
1830 }
1831
1832 /// IsTailCallConvention - Return true if the calling convention is one that
1833 /// supports tail call optimization.
1834 static bool IsTailCallConvention(CallingConv::ID CC) {
1835   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1836           CC == CallingConv::HiPE);
1837 }
1838
1839 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1840   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1841     return false;
1842
1843   CallSite CS(CI);
1844   CallingConv::ID CalleeCC = CS.getCallingConv();
1845   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1846     return false;
1847
1848   return true;
1849 }
1850
1851 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1852 /// a tailcall target by changing its ABI.
1853 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1854                                    bool GuaranteedTailCallOpt) {
1855   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1856 }
1857
1858 SDValue
1859 X86TargetLowering::LowerMemArgument(SDValue Chain,
1860                                     CallingConv::ID CallConv,
1861                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1862                                     DebugLoc dl, SelectionDAG &DAG,
1863                                     const CCValAssign &VA,
1864                                     MachineFrameInfo *MFI,
1865                                     unsigned i) const {
1866   // Create the nodes corresponding to a load from this parameter slot.
1867   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1868   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1869                               getTargetMachine().Options.GuaranteedTailCallOpt);
1870   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1871   EVT ValVT;
1872
1873   // If value is passed by pointer we have address passed instead of the value
1874   // itself.
1875   if (VA.getLocInfo() == CCValAssign::Indirect)
1876     ValVT = VA.getLocVT();
1877   else
1878     ValVT = VA.getValVT();
1879
1880   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1881   // changed with more analysis.
1882   // In case of tail call optimization mark all arguments mutable. Since they
1883   // could be overwritten by lowering of arguments in case of a tail call.
1884   if (Flags.isByVal()) {
1885     unsigned Bytes = Flags.getByValSize();
1886     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1887     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1888     return DAG.getFrameIndex(FI, getPointerTy());
1889   } else {
1890     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1891                                     VA.getLocMemOffset(), isImmutable);
1892     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1893     return DAG.getLoad(ValVT, dl, Chain, FIN,
1894                        MachinePointerInfo::getFixedStack(FI),
1895                        false, false, false, 0);
1896   }
1897 }
1898
1899 SDValue
1900 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1901                                         CallingConv::ID CallConv,
1902                                         bool isVarArg,
1903                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1904                                         DebugLoc dl,
1905                                         SelectionDAG &DAG,
1906                                         SmallVectorImpl<SDValue> &InVals)
1907                                           const {
1908   MachineFunction &MF = DAG.getMachineFunction();
1909   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1910
1911   const Function* Fn = MF.getFunction();
1912   if (Fn->hasExternalLinkage() &&
1913       Subtarget->isTargetCygMing() &&
1914       Fn->getName() == "main")
1915     FuncInfo->setForceFramePointer(true);
1916
1917   MachineFrameInfo *MFI = MF.getFrameInfo();
1918   bool Is64Bit = Subtarget->is64Bit();
1919   bool IsWindows = Subtarget->isTargetWindows();
1920   bool IsWin64 = Subtarget->isTargetWin64();
1921
1922   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1923          "Var args not supported with calling convention fastcc, ghc or hipe");
1924
1925   // Assign locations to all of the incoming arguments.
1926   SmallVector<CCValAssign, 16> ArgLocs;
1927   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1928                  ArgLocs, *DAG.getContext());
1929
1930   // Allocate shadow area for Win64
1931   if (IsWin64) {
1932     CCInfo.AllocateStack(32, 8);
1933   }
1934
1935   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1936
1937   unsigned LastVal = ~0U;
1938   SDValue ArgValue;
1939   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1940     CCValAssign &VA = ArgLocs[i];
1941     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1942     // places.
1943     assert(VA.getValNo() != LastVal &&
1944            "Don't support value assigned to multiple locs yet");
1945     (void)LastVal;
1946     LastVal = VA.getValNo();
1947
1948     if (VA.isRegLoc()) {
1949       EVT RegVT = VA.getLocVT();
1950       const TargetRegisterClass *RC;
1951       if (RegVT == MVT::i32)
1952         RC = &X86::GR32RegClass;
1953       else if (Is64Bit && RegVT == MVT::i64)
1954         RC = &X86::GR64RegClass;
1955       else if (RegVT == MVT::f32)
1956         RC = &X86::FR32RegClass;
1957       else if (RegVT == MVT::f64)
1958         RC = &X86::FR64RegClass;
1959       else if (RegVT.is256BitVector())
1960         RC = &X86::VR256RegClass;
1961       else if (RegVT.is128BitVector())
1962         RC = &X86::VR128RegClass;
1963       else if (RegVT == MVT::x86mmx)
1964         RC = &X86::VR64RegClass;
1965       else
1966         llvm_unreachable("Unknown argument type!");
1967
1968       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1969       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1970
1971       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1972       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1973       // right size.
1974       if (VA.getLocInfo() == CCValAssign::SExt)
1975         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1976                                DAG.getValueType(VA.getValVT()));
1977       else if (VA.getLocInfo() == CCValAssign::ZExt)
1978         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1979                                DAG.getValueType(VA.getValVT()));
1980       else if (VA.getLocInfo() == CCValAssign::BCvt)
1981         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1982
1983       if (VA.isExtInLoc()) {
1984         // Handle MMX values passed in XMM regs.
1985         if (RegVT.isVector()) {
1986           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1987                                  ArgValue);
1988         } else
1989           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1990       }
1991     } else {
1992       assert(VA.isMemLoc());
1993       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1994     }
1995
1996     // If value is passed via pointer - do a load.
1997     if (VA.getLocInfo() == CCValAssign::Indirect)
1998       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1999                              MachinePointerInfo(), false, false, false, 0);
2000
2001     InVals.push_back(ArgValue);
2002   }
2003
2004   // The x86-64 ABI for returning structs by value requires that we copy
2005   // the sret argument into %rax for the return. Save the argument into
2006   // a virtual register so that we can access it from the return points.
2007   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2008     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2009     unsigned Reg = FuncInfo->getSRetReturnReg();
2010     if (!Reg) {
2011       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
2012       FuncInfo->setSRetReturnReg(Reg);
2013     }
2014     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2015     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2016   }
2017
2018   unsigned StackSize = CCInfo.getNextStackOffset();
2019   // Align stack specially for tail calls.
2020   if (FuncIsMadeTailCallSafe(CallConv,
2021                              MF.getTarget().Options.GuaranteedTailCallOpt))
2022     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2023
2024   // If the function takes variable number of arguments, make a frame index for
2025   // the start of the first vararg value... for expansion of llvm.va_start.
2026   if (isVarArg) {
2027     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2028                     CallConv != CallingConv::X86_ThisCall)) {
2029       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2030     }
2031     if (Is64Bit) {
2032       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2033
2034       // FIXME: We should really autogenerate these arrays
2035       static const uint16_t GPR64ArgRegsWin64[] = {
2036         X86::RCX, X86::RDX, X86::R8,  X86::R9
2037       };
2038       static const uint16_t GPR64ArgRegs64Bit[] = {
2039         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2040       };
2041       static const uint16_t XMMArgRegs64Bit[] = {
2042         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2043         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2044       };
2045       const uint16_t *GPR64ArgRegs;
2046       unsigned NumXMMRegs = 0;
2047
2048       if (IsWin64) {
2049         // The XMM registers which might contain var arg parameters are shadowed
2050         // in their paired GPR.  So we only need to save the GPR to their home
2051         // slots.
2052         TotalNumIntRegs = 4;
2053         GPR64ArgRegs = GPR64ArgRegsWin64;
2054       } else {
2055         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2056         GPR64ArgRegs = GPR64ArgRegs64Bit;
2057
2058         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2059                                                 TotalNumXMMRegs);
2060       }
2061       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2062                                                        TotalNumIntRegs);
2063
2064       bool NoImplicitFloatOps = Fn->getFnAttributes().
2065         hasAttribute(Attribute::NoImplicitFloat);
2066       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2067              "SSE register cannot be used when SSE is disabled!");
2068       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2069                NoImplicitFloatOps) &&
2070              "SSE register cannot be used when SSE is disabled!");
2071       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2072           !Subtarget->hasSSE1())
2073         // Kernel mode asks for SSE to be disabled, so don't push them
2074         // on the stack.
2075         TotalNumXMMRegs = 0;
2076
2077       if (IsWin64) {
2078         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2079         // Get to the caller-allocated home save location.  Add 8 to account
2080         // for the return address.
2081         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2082         FuncInfo->setRegSaveFrameIndex(
2083           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2084         // Fixup to set vararg frame on shadow area (4 x i64).
2085         if (NumIntRegs < 4)
2086           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2087       } else {
2088         // For X86-64, if there are vararg parameters that are passed via
2089         // registers, then we must store them to their spots on the stack so
2090         // they may be loaded by deferencing the result of va_next.
2091         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2092         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2093         FuncInfo->setRegSaveFrameIndex(
2094           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2095                                false));
2096       }
2097
2098       // Store the integer parameter registers.
2099       SmallVector<SDValue, 8> MemOps;
2100       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2101                                         getPointerTy());
2102       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2103       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2104         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2105                                   DAG.getIntPtrConstant(Offset));
2106         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2107                                      &X86::GR64RegClass);
2108         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2109         SDValue Store =
2110           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2111                        MachinePointerInfo::getFixedStack(
2112                          FuncInfo->getRegSaveFrameIndex(), Offset),
2113                        false, false, 0);
2114         MemOps.push_back(Store);
2115         Offset += 8;
2116       }
2117
2118       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2119         // Now store the XMM (fp + vector) parameter registers.
2120         SmallVector<SDValue, 11> SaveXMMOps;
2121         SaveXMMOps.push_back(Chain);
2122
2123         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2124         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2125         SaveXMMOps.push_back(ALVal);
2126
2127         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2128                                FuncInfo->getRegSaveFrameIndex()));
2129         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2130                                FuncInfo->getVarArgsFPOffset()));
2131
2132         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2133           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2134                                        &X86::VR128RegClass);
2135           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2136           SaveXMMOps.push_back(Val);
2137         }
2138         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2139                                      MVT::Other,
2140                                      &SaveXMMOps[0], SaveXMMOps.size()));
2141       }
2142
2143       if (!MemOps.empty())
2144         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2145                             &MemOps[0], MemOps.size());
2146     }
2147   }
2148
2149   // Some CCs need callee pop.
2150   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2151                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2152     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2153   } else {
2154     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2155     // If this is an sret function, the return should pop the hidden pointer.
2156     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2157         argsAreStructReturn(Ins) == StackStructReturn)
2158       FuncInfo->setBytesToPopOnReturn(4);
2159   }
2160
2161   if (!Is64Bit) {
2162     // RegSaveFrameIndex is X86-64 only.
2163     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2164     if (CallConv == CallingConv::X86_FastCall ||
2165         CallConv == CallingConv::X86_ThisCall)
2166       // fastcc functions can't have varargs.
2167       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2168   }
2169
2170   FuncInfo->setArgumentStackSize(StackSize);
2171
2172   return Chain;
2173 }
2174
2175 SDValue
2176 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2177                                     SDValue StackPtr, SDValue Arg,
2178                                     DebugLoc dl, SelectionDAG &DAG,
2179                                     const CCValAssign &VA,
2180                                     ISD::ArgFlagsTy Flags) const {
2181   unsigned LocMemOffset = VA.getLocMemOffset();
2182   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2183   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2184   if (Flags.isByVal())
2185     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2186
2187   return DAG.getStore(Chain, dl, Arg, PtrOff,
2188                       MachinePointerInfo::getStack(LocMemOffset),
2189                       false, false, 0);
2190 }
2191
2192 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2193 /// optimization is performed and it is required.
2194 SDValue
2195 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2196                                            SDValue &OutRetAddr, SDValue Chain,
2197                                            bool IsTailCall, bool Is64Bit,
2198                                            int FPDiff, DebugLoc dl) const {
2199   // Adjust the Return address stack slot.
2200   EVT VT = getPointerTy();
2201   OutRetAddr = getReturnAddressFrameIndex(DAG);
2202
2203   // Load the "old" Return address.
2204   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2205                            false, false, false, 0);
2206   return SDValue(OutRetAddr.getNode(), 1);
2207 }
2208
2209 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2210 /// optimization is performed and it is required (FPDiff!=0).
2211 static SDValue
2212 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2213                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2214                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
2215   // Store the return address to the appropriate stack slot.
2216   if (!FPDiff) return Chain;
2217   // Calculate the new stack slot for the return address.
2218   int NewReturnAddrFI =
2219     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2220   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2221   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2222                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2223                        false, false, 0);
2224   return Chain;
2225 }
2226
2227 SDValue
2228 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2229                              SmallVectorImpl<SDValue> &InVals) const {
2230   SelectionDAG &DAG                     = CLI.DAG;
2231   DebugLoc &dl                          = CLI.DL;
2232   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2233   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2234   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2235   SDValue Chain                         = CLI.Chain;
2236   SDValue Callee                        = CLI.Callee;
2237   CallingConv::ID CallConv              = CLI.CallConv;
2238   bool &isTailCall                      = CLI.IsTailCall;
2239   bool isVarArg                         = CLI.IsVarArg;
2240
2241   MachineFunction &MF = DAG.getMachineFunction();
2242   bool Is64Bit        = Subtarget->is64Bit();
2243   bool IsWin64        = Subtarget->isTargetWin64();
2244   bool IsWindows      = Subtarget->isTargetWindows();
2245   StructReturnType SR = callIsStructReturn(Outs);
2246   bool IsSibcall      = false;
2247
2248   if (MF.getTarget().Options.DisableTailCalls)
2249     isTailCall = false;
2250
2251   if (isTailCall) {
2252     // Check if it's really possible to do a tail call.
2253     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2254                     isVarArg, SR != NotStructReturn,
2255                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2256                     Outs, OutVals, Ins, DAG);
2257
2258     // Sibcalls are automatically detected tailcalls which do not require
2259     // ABI changes.
2260     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2261       IsSibcall = true;
2262
2263     if (isTailCall)
2264       ++NumTailCalls;
2265   }
2266
2267   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2268          "Var args not supported with calling convention fastcc, ghc or hipe");
2269
2270   // Analyze operands of the call, assigning locations to each operand.
2271   SmallVector<CCValAssign, 16> ArgLocs;
2272   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2273                  ArgLocs, *DAG.getContext());
2274
2275   // Allocate shadow area for Win64
2276   if (IsWin64) {
2277     CCInfo.AllocateStack(32, 8);
2278   }
2279
2280   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2281
2282   // Get a count of how many bytes are to be pushed on the stack.
2283   unsigned NumBytes = CCInfo.getNextStackOffset();
2284   if (IsSibcall)
2285     // This is a sibcall. The memory operands are available in caller's
2286     // own caller's stack.
2287     NumBytes = 0;
2288   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2289            IsTailCallConvention(CallConv))
2290     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2291
2292   int FPDiff = 0;
2293   if (isTailCall && !IsSibcall) {
2294     // Lower arguments at fp - stackoffset + fpdiff.
2295     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2296     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2297
2298     FPDiff = NumBytesCallerPushed - NumBytes;
2299
2300     // Set the delta of movement of the returnaddr stackslot.
2301     // But only set if delta is greater than previous delta.
2302     if (FPDiff < X86Info->getTCReturnAddrDelta())
2303       X86Info->setTCReturnAddrDelta(FPDiff);
2304   }
2305
2306   if (!IsSibcall)
2307     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2308
2309   SDValue RetAddrFrIdx;
2310   // Load return address for tail calls.
2311   if (isTailCall && FPDiff)
2312     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2313                                     Is64Bit, FPDiff, dl);
2314
2315   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2316   SmallVector<SDValue, 8> MemOpChains;
2317   SDValue StackPtr;
2318
2319   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2320   // of tail call optimization arguments are handle later.
2321   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2322     CCValAssign &VA = ArgLocs[i];
2323     EVT RegVT = VA.getLocVT();
2324     SDValue Arg = OutVals[i];
2325     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2326     bool isByVal = Flags.isByVal();
2327
2328     // Promote the value if needed.
2329     switch (VA.getLocInfo()) {
2330     default: llvm_unreachable("Unknown loc info!");
2331     case CCValAssign::Full: break;
2332     case CCValAssign::SExt:
2333       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2334       break;
2335     case CCValAssign::ZExt:
2336       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2337       break;
2338     case CCValAssign::AExt:
2339       if (RegVT.is128BitVector()) {
2340         // Special case: passing MMX values in XMM registers.
2341         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2342         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2343         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2344       } else
2345         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2346       break;
2347     case CCValAssign::BCvt:
2348       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2349       break;
2350     case CCValAssign::Indirect: {
2351       // Store the argument.
2352       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2353       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2354       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2355                            MachinePointerInfo::getFixedStack(FI),
2356                            false, false, 0);
2357       Arg = SpillSlot;
2358       break;
2359     }
2360     }
2361
2362     if (VA.isRegLoc()) {
2363       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2364       if (isVarArg && IsWin64) {
2365         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2366         // shadow reg if callee is a varargs function.
2367         unsigned ShadowReg = 0;
2368         switch (VA.getLocReg()) {
2369         case X86::XMM0: ShadowReg = X86::RCX; break;
2370         case X86::XMM1: ShadowReg = X86::RDX; break;
2371         case X86::XMM2: ShadowReg = X86::R8; break;
2372         case X86::XMM3: ShadowReg = X86::R9; break;
2373         }
2374         if (ShadowReg)
2375           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2376       }
2377     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2378       assert(VA.isMemLoc());
2379       if (StackPtr.getNode() == 0)
2380         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2381                                       getPointerTy());
2382       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2383                                              dl, DAG, VA, Flags));
2384     }
2385   }
2386
2387   if (!MemOpChains.empty())
2388     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2389                         &MemOpChains[0], MemOpChains.size());
2390
2391   if (Subtarget->isPICStyleGOT()) {
2392     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2393     // GOT pointer.
2394     if (!isTailCall) {
2395       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2396                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2397     } else {
2398       // If we are tail calling and generating PIC/GOT style code load the
2399       // address of the callee into ECX. The value in ecx is used as target of
2400       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2401       // for tail calls on PIC/GOT architectures. Normally we would just put the
2402       // address of GOT into ebx and then call target@PLT. But for tail calls
2403       // ebx would be restored (since ebx is callee saved) before jumping to the
2404       // target@PLT.
2405
2406       // Note: The actual moving to ECX is done further down.
2407       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2408       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2409           !G->getGlobal()->hasProtectedVisibility())
2410         Callee = LowerGlobalAddress(Callee, DAG);
2411       else if (isa<ExternalSymbolSDNode>(Callee))
2412         Callee = LowerExternalSymbol(Callee, DAG);
2413     }
2414   }
2415
2416   if (Is64Bit && isVarArg && !IsWin64) {
2417     // From AMD64 ABI document:
2418     // For calls that may call functions that use varargs or stdargs
2419     // (prototype-less calls or calls to functions containing ellipsis (...) in
2420     // the declaration) %al is used as hidden argument to specify the number
2421     // of SSE registers used. The contents of %al do not need to match exactly
2422     // the number of registers, but must be an ubound on the number of SSE
2423     // registers used and is in the range 0 - 8 inclusive.
2424
2425     // Count the number of XMM registers allocated.
2426     static const uint16_t XMMArgRegs[] = {
2427       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2428       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2429     };
2430     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2431     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2432            && "SSE registers cannot be used when SSE is disabled");
2433
2434     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2435                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2436   }
2437
2438   // For tail calls lower the arguments to the 'real' stack slot.
2439   if (isTailCall) {
2440     // Force all the incoming stack arguments to be loaded from the stack
2441     // before any new outgoing arguments are stored to the stack, because the
2442     // outgoing stack slots may alias the incoming argument stack slots, and
2443     // the alias isn't otherwise explicit. This is slightly more conservative
2444     // than necessary, because it means that each store effectively depends
2445     // on every argument instead of just those arguments it would clobber.
2446     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2447
2448     SmallVector<SDValue, 8> MemOpChains2;
2449     SDValue FIN;
2450     int FI = 0;
2451     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2452       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2453         CCValAssign &VA = ArgLocs[i];
2454         if (VA.isRegLoc())
2455           continue;
2456         assert(VA.isMemLoc());
2457         SDValue Arg = OutVals[i];
2458         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2459         // Create frame index.
2460         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2461         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2462         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2463         FIN = DAG.getFrameIndex(FI, getPointerTy());
2464
2465         if (Flags.isByVal()) {
2466           // Copy relative to framepointer.
2467           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2468           if (StackPtr.getNode() == 0)
2469             StackPtr = DAG.getCopyFromReg(Chain, dl,
2470                                           RegInfo->getStackRegister(),
2471                                           getPointerTy());
2472           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2473
2474           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2475                                                            ArgChain,
2476                                                            Flags, DAG, dl));
2477         } else {
2478           // Store relative to framepointer.
2479           MemOpChains2.push_back(
2480             DAG.getStore(ArgChain, dl, Arg, FIN,
2481                          MachinePointerInfo::getFixedStack(FI),
2482                          false, false, 0));
2483         }
2484       }
2485     }
2486
2487     if (!MemOpChains2.empty())
2488       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2489                           &MemOpChains2[0], MemOpChains2.size());
2490
2491     // Store the return address to the appropriate stack slot.
2492     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2493                                      getPointerTy(), RegInfo->getSlotSize(),
2494                                      FPDiff, dl);
2495   }
2496
2497   // Build a sequence of copy-to-reg nodes chained together with token chain
2498   // and flag operands which copy the outgoing args into registers.
2499   SDValue InFlag;
2500   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2501     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2502                              RegsToPass[i].second, InFlag);
2503     InFlag = Chain.getValue(1);
2504   }
2505
2506   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2507     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2508     // In the 64-bit large code model, we have to make all calls
2509     // through a register, since the call instruction's 32-bit
2510     // pc-relative offset may not be large enough to hold the whole
2511     // address.
2512   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2513     // If the callee is a GlobalAddress node (quite common, every direct call
2514     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2515     // it.
2516
2517     // We should use extra load for direct calls to dllimported functions in
2518     // non-JIT mode.
2519     const GlobalValue *GV = G->getGlobal();
2520     if (!GV->hasDLLImportLinkage()) {
2521       unsigned char OpFlags = 0;
2522       bool ExtraLoad = false;
2523       unsigned WrapperKind = ISD::DELETED_NODE;
2524
2525       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2526       // external symbols most go through the PLT in PIC mode.  If the symbol
2527       // has hidden or protected visibility, or if it is static or local, then
2528       // we don't need to use the PLT - we can directly call it.
2529       if (Subtarget->isTargetELF() &&
2530           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2531           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2532         OpFlags = X86II::MO_PLT;
2533       } else if (Subtarget->isPICStyleStubAny() &&
2534                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2535                  (!Subtarget->getTargetTriple().isMacOSX() ||
2536                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2537         // PC-relative references to external symbols should go through $stub,
2538         // unless we're building with the leopard linker or later, which
2539         // automatically synthesizes these stubs.
2540         OpFlags = X86II::MO_DARWIN_STUB;
2541       } else if (Subtarget->isPICStyleRIPRel() &&
2542                  isa<Function>(GV) &&
2543                  cast<Function>(GV)->getFnAttributes().
2544                    hasAttribute(Attribute::NonLazyBind)) {
2545         // If the function is marked as non-lazy, generate an indirect call
2546         // which loads from the GOT directly. This avoids runtime overhead
2547         // at the cost of eager binding (and one extra byte of encoding).
2548         OpFlags = X86II::MO_GOTPCREL;
2549         WrapperKind = X86ISD::WrapperRIP;
2550         ExtraLoad = true;
2551       }
2552
2553       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2554                                           G->getOffset(), OpFlags);
2555
2556       // Add a wrapper if needed.
2557       if (WrapperKind != ISD::DELETED_NODE)
2558         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2559       // Add extra indirection if needed.
2560       if (ExtraLoad)
2561         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2562                              MachinePointerInfo::getGOT(),
2563                              false, false, false, 0);
2564     }
2565   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2566     unsigned char OpFlags = 0;
2567
2568     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2569     // external symbols should go through the PLT.
2570     if (Subtarget->isTargetELF() &&
2571         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2572       OpFlags = X86II::MO_PLT;
2573     } else if (Subtarget->isPICStyleStubAny() &&
2574                (!Subtarget->getTargetTriple().isMacOSX() ||
2575                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2576       // PC-relative references to external symbols should go through $stub,
2577       // unless we're building with the leopard linker or later, which
2578       // automatically synthesizes these stubs.
2579       OpFlags = X86II::MO_DARWIN_STUB;
2580     }
2581
2582     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2583                                          OpFlags);
2584   }
2585
2586   // Returns a chain & a flag for retval copy to use.
2587   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2588   SmallVector<SDValue, 8> Ops;
2589
2590   if (!IsSibcall && isTailCall) {
2591     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2592                            DAG.getIntPtrConstant(0, true), InFlag);
2593     InFlag = Chain.getValue(1);
2594   }
2595
2596   Ops.push_back(Chain);
2597   Ops.push_back(Callee);
2598
2599   if (isTailCall)
2600     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2601
2602   // Add argument registers to the end of the list so that they are known live
2603   // into the call.
2604   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2605     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2606                                   RegsToPass[i].second.getValueType()));
2607
2608   // Add a register mask operand representing the call-preserved registers.
2609   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2610   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2611   assert(Mask && "Missing call preserved mask for calling convention");
2612   Ops.push_back(DAG.getRegisterMask(Mask));
2613
2614   if (InFlag.getNode())
2615     Ops.push_back(InFlag);
2616
2617   if (isTailCall) {
2618     // We used to do:
2619     //// If this is the first return lowered for this function, add the regs
2620     //// to the liveout set for the function.
2621     // This isn't right, although it's probably harmless on x86; liveouts
2622     // should be computed from returns not tail calls.  Consider a void
2623     // function making a tail call to a function returning int.
2624     return DAG.getNode(X86ISD::TC_RETURN, dl,
2625                        NodeTys, &Ops[0], Ops.size());
2626   }
2627
2628   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2629   InFlag = Chain.getValue(1);
2630
2631   // Create the CALLSEQ_END node.
2632   unsigned NumBytesForCalleeToPush;
2633   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2634                        getTargetMachine().Options.GuaranteedTailCallOpt))
2635     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2636   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2637            SR == StackStructReturn)
2638     // If this is a call to a struct-return function, the callee
2639     // pops the hidden struct pointer, so we have to push it back.
2640     // This is common for Darwin/X86, Linux & Mingw32 targets.
2641     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2642     NumBytesForCalleeToPush = 4;
2643   else
2644     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2645
2646   // Returns a flag for retval copy to use.
2647   if (!IsSibcall) {
2648     Chain = DAG.getCALLSEQ_END(Chain,
2649                                DAG.getIntPtrConstant(NumBytes, true),
2650                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2651                                                      true),
2652                                InFlag);
2653     InFlag = Chain.getValue(1);
2654   }
2655
2656   // Handle result values, copying them out of physregs into vregs that we
2657   // return.
2658   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2659                          Ins, dl, DAG, InVals);
2660 }
2661
2662 //===----------------------------------------------------------------------===//
2663 //                Fast Calling Convention (tail call) implementation
2664 //===----------------------------------------------------------------------===//
2665
2666 //  Like std call, callee cleans arguments, convention except that ECX is
2667 //  reserved for storing the tail called function address. Only 2 registers are
2668 //  free for argument passing (inreg). Tail call optimization is performed
2669 //  provided:
2670 //                * tailcallopt is enabled
2671 //                * caller/callee are fastcc
2672 //  On X86_64 architecture with GOT-style position independent code only local
2673 //  (within module) calls are supported at the moment.
2674 //  To keep the stack aligned according to platform abi the function
2675 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2676 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2677 //  If a tail called function callee has more arguments than the caller the
2678 //  caller needs to make sure that there is room to move the RETADDR to. This is
2679 //  achieved by reserving an area the size of the argument delta right after the
2680 //  original REtADDR, but before the saved framepointer or the spilled registers
2681 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2682 //  stack layout:
2683 //    arg1
2684 //    arg2
2685 //    RETADDR
2686 //    [ new RETADDR
2687 //      move area ]
2688 //    (possible EBP)
2689 //    ESI
2690 //    EDI
2691 //    local1 ..
2692
2693 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2694 /// for a 16 byte align requirement.
2695 unsigned
2696 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2697                                                SelectionDAG& DAG) const {
2698   MachineFunction &MF = DAG.getMachineFunction();
2699   const TargetMachine &TM = MF.getTarget();
2700   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2701   unsigned StackAlignment = TFI.getStackAlignment();
2702   uint64_t AlignMask = StackAlignment - 1;
2703   int64_t Offset = StackSize;
2704   unsigned SlotSize = RegInfo->getSlotSize();
2705   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2706     // Number smaller than 12 so just add the difference.
2707     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2708   } else {
2709     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2710     Offset = ((~AlignMask) & Offset) + StackAlignment +
2711       (StackAlignment-SlotSize);
2712   }
2713   return Offset;
2714 }
2715
2716 /// MatchingStackOffset - Return true if the given stack call argument is
2717 /// already available in the same position (relatively) of the caller's
2718 /// incoming argument stack.
2719 static
2720 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2721                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2722                          const X86InstrInfo *TII) {
2723   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2724   int FI = INT_MAX;
2725   if (Arg.getOpcode() == ISD::CopyFromReg) {
2726     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2727     if (!TargetRegisterInfo::isVirtualRegister(VR))
2728       return false;
2729     MachineInstr *Def = MRI->getVRegDef(VR);
2730     if (!Def)
2731       return false;
2732     if (!Flags.isByVal()) {
2733       if (!TII->isLoadFromStackSlot(Def, FI))
2734         return false;
2735     } else {
2736       unsigned Opcode = Def->getOpcode();
2737       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2738           Def->getOperand(1).isFI()) {
2739         FI = Def->getOperand(1).getIndex();
2740         Bytes = Flags.getByValSize();
2741       } else
2742         return false;
2743     }
2744   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2745     if (Flags.isByVal())
2746       // ByVal argument is passed in as a pointer but it's now being
2747       // dereferenced. e.g.
2748       // define @foo(%struct.X* %A) {
2749       //   tail call @bar(%struct.X* byval %A)
2750       // }
2751       return false;
2752     SDValue Ptr = Ld->getBasePtr();
2753     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2754     if (!FINode)
2755       return false;
2756     FI = FINode->getIndex();
2757   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2758     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2759     FI = FINode->getIndex();
2760     Bytes = Flags.getByValSize();
2761   } else
2762     return false;
2763
2764   assert(FI != INT_MAX);
2765   if (!MFI->isFixedObjectIndex(FI))
2766     return false;
2767   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2768 }
2769
2770 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2771 /// for tail call optimization. Targets which want to do tail call
2772 /// optimization should implement this function.
2773 bool
2774 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2775                                                      CallingConv::ID CalleeCC,
2776                                                      bool isVarArg,
2777                                                      bool isCalleeStructRet,
2778                                                      bool isCallerStructRet,
2779                                                      Type *RetTy,
2780                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2781                                     const SmallVectorImpl<SDValue> &OutVals,
2782                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2783                                                      SelectionDAG& DAG) const {
2784   if (!IsTailCallConvention(CalleeCC) &&
2785       CalleeCC != CallingConv::C)
2786     return false;
2787
2788   // If -tailcallopt is specified, make fastcc functions tail-callable.
2789   const MachineFunction &MF = DAG.getMachineFunction();
2790   const Function *CallerF = DAG.getMachineFunction().getFunction();
2791
2792   // If the function return type is x86_fp80 and the callee return type is not,
2793   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2794   // perform a tailcall optimization here.
2795   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2796     return false;
2797
2798   CallingConv::ID CallerCC = CallerF->getCallingConv();
2799   bool CCMatch = CallerCC == CalleeCC;
2800
2801   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2802     if (IsTailCallConvention(CalleeCC) && CCMatch)
2803       return true;
2804     return false;
2805   }
2806
2807   // Look for obvious safe cases to perform tail call optimization that do not
2808   // require ABI changes. This is what gcc calls sibcall.
2809
2810   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2811   // emit a special epilogue.
2812   if (RegInfo->needsStackRealignment(MF))
2813     return false;
2814
2815   // Also avoid sibcall optimization if either caller or callee uses struct
2816   // return semantics.
2817   if (isCalleeStructRet || isCallerStructRet)
2818     return false;
2819
2820   // An stdcall caller is expected to clean up its arguments; the callee
2821   // isn't going to do that.
2822   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2823     return false;
2824
2825   // Do not sibcall optimize vararg calls unless all arguments are passed via
2826   // registers.
2827   if (isVarArg && !Outs.empty()) {
2828
2829     // Optimizing for varargs on Win64 is unlikely to be safe without
2830     // additional testing.
2831     if (Subtarget->isTargetWin64())
2832       return false;
2833
2834     SmallVector<CCValAssign, 16> ArgLocs;
2835     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2836                    getTargetMachine(), ArgLocs, *DAG.getContext());
2837
2838     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2839     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2840       if (!ArgLocs[i].isRegLoc())
2841         return false;
2842   }
2843
2844   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2845   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2846   // this into a sibcall.
2847   bool Unused = false;
2848   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2849     if (!Ins[i].Used) {
2850       Unused = true;
2851       break;
2852     }
2853   }
2854   if (Unused) {
2855     SmallVector<CCValAssign, 16> RVLocs;
2856     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2857                    getTargetMachine(), RVLocs, *DAG.getContext());
2858     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2859     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2860       CCValAssign &VA = RVLocs[i];
2861       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2862         return false;
2863     }
2864   }
2865
2866   // If the calling conventions do not match, then we'd better make sure the
2867   // results are returned in the same way as what the caller expects.
2868   if (!CCMatch) {
2869     SmallVector<CCValAssign, 16> RVLocs1;
2870     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2871                     getTargetMachine(), RVLocs1, *DAG.getContext());
2872     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2873
2874     SmallVector<CCValAssign, 16> RVLocs2;
2875     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2876                     getTargetMachine(), RVLocs2, *DAG.getContext());
2877     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2878
2879     if (RVLocs1.size() != RVLocs2.size())
2880       return false;
2881     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2882       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2883         return false;
2884       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2885         return false;
2886       if (RVLocs1[i].isRegLoc()) {
2887         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2888           return false;
2889       } else {
2890         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2891           return false;
2892       }
2893     }
2894   }
2895
2896   // If the callee takes no arguments then go on to check the results of the
2897   // call.
2898   if (!Outs.empty()) {
2899     // Check if stack adjustment is needed. For now, do not do this if any
2900     // argument is passed on the stack.
2901     SmallVector<CCValAssign, 16> ArgLocs;
2902     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2903                    getTargetMachine(), ArgLocs, *DAG.getContext());
2904
2905     // Allocate shadow area for Win64
2906     if (Subtarget->isTargetWin64()) {
2907       CCInfo.AllocateStack(32, 8);
2908     }
2909
2910     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2911     if (CCInfo.getNextStackOffset()) {
2912       MachineFunction &MF = DAG.getMachineFunction();
2913       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2914         return false;
2915
2916       // Check if the arguments are already laid out in the right way as
2917       // the caller's fixed stack objects.
2918       MachineFrameInfo *MFI = MF.getFrameInfo();
2919       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2920       const X86InstrInfo *TII =
2921         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2922       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2923         CCValAssign &VA = ArgLocs[i];
2924         SDValue Arg = OutVals[i];
2925         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2926         if (VA.getLocInfo() == CCValAssign::Indirect)
2927           return false;
2928         if (!VA.isRegLoc()) {
2929           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2930                                    MFI, MRI, TII))
2931             return false;
2932         }
2933       }
2934     }
2935
2936     // If the tailcall address may be in a register, then make sure it's
2937     // possible to register allocate for it. In 32-bit, the call address can
2938     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2939     // callee-saved registers are restored. These happen to be the same
2940     // registers used to pass 'inreg' arguments so watch out for those.
2941     if (!Subtarget->is64Bit() &&
2942         !isa<GlobalAddressSDNode>(Callee) &&
2943         !isa<ExternalSymbolSDNode>(Callee)) {
2944       unsigned NumInRegs = 0;
2945       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2946         CCValAssign &VA = ArgLocs[i];
2947         if (!VA.isRegLoc())
2948           continue;
2949         unsigned Reg = VA.getLocReg();
2950         switch (Reg) {
2951         default: break;
2952         case X86::EAX: case X86::EDX: case X86::ECX:
2953           if (++NumInRegs == 3)
2954             return false;
2955           break;
2956         }
2957       }
2958     }
2959   }
2960
2961   return true;
2962 }
2963
2964 FastISel *
2965 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2966                                   const TargetLibraryInfo *libInfo) const {
2967   return X86::createFastISel(funcInfo, libInfo);
2968 }
2969
2970 //===----------------------------------------------------------------------===//
2971 //                           Other Lowering Hooks
2972 //===----------------------------------------------------------------------===//
2973
2974 static bool MayFoldLoad(SDValue Op) {
2975   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2976 }
2977
2978 static bool MayFoldIntoStore(SDValue Op) {
2979   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2980 }
2981
2982 static bool isTargetShuffle(unsigned Opcode) {
2983   switch(Opcode) {
2984   default: return false;
2985   case X86ISD::PSHUFD:
2986   case X86ISD::PSHUFHW:
2987   case X86ISD::PSHUFLW:
2988   case X86ISD::SHUFP:
2989   case X86ISD::PALIGN:
2990   case X86ISD::MOVLHPS:
2991   case X86ISD::MOVLHPD:
2992   case X86ISD::MOVHLPS:
2993   case X86ISD::MOVLPS:
2994   case X86ISD::MOVLPD:
2995   case X86ISD::MOVSHDUP:
2996   case X86ISD::MOVSLDUP:
2997   case X86ISD::MOVDDUP:
2998   case X86ISD::MOVSS:
2999   case X86ISD::MOVSD:
3000   case X86ISD::UNPCKL:
3001   case X86ISD::UNPCKH:
3002   case X86ISD::VPERMILP:
3003   case X86ISD::VPERM2X128:
3004   case X86ISD::VPERMI:
3005     return true;
3006   }
3007 }
3008
3009 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3010                                     SDValue V1, SelectionDAG &DAG) {
3011   switch(Opc) {
3012   default: llvm_unreachable("Unknown x86 shuffle node");
3013   case X86ISD::MOVSHDUP:
3014   case X86ISD::MOVSLDUP:
3015   case X86ISD::MOVDDUP:
3016     return DAG.getNode(Opc, dl, VT, V1);
3017   }
3018 }
3019
3020 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3021                                     SDValue V1, unsigned TargetMask,
3022                                     SelectionDAG &DAG) {
3023   switch(Opc) {
3024   default: llvm_unreachable("Unknown x86 shuffle node");
3025   case X86ISD::PSHUFD:
3026   case X86ISD::PSHUFHW:
3027   case X86ISD::PSHUFLW:
3028   case X86ISD::VPERMILP:
3029   case X86ISD::VPERMI:
3030     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3031   }
3032 }
3033
3034 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3035                                     SDValue V1, SDValue V2, unsigned TargetMask,
3036                                     SelectionDAG &DAG) {
3037   switch(Opc) {
3038   default: llvm_unreachable("Unknown x86 shuffle node");
3039   case X86ISD::PALIGN:
3040   case X86ISD::SHUFP:
3041   case X86ISD::VPERM2X128:
3042     return DAG.getNode(Opc, dl, VT, V1, V2,
3043                        DAG.getConstant(TargetMask, MVT::i8));
3044   }
3045 }
3046
3047 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3048                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3049   switch(Opc) {
3050   default: llvm_unreachable("Unknown x86 shuffle node");
3051   case X86ISD::MOVLHPS:
3052   case X86ISD::MOVLHPD:
3053   case X86ISD::MOVHLPS:
3054   case X86ISD::MOVLPS:
3055   case X86ISD::MOVLPD:
3056   case X86ISD::MOVSS:
3057   case X86ISD::MOVSD:
3058   case X86ISD::UNPCKL:
3059   case X86ISD::UNPCKH:
3060     return DAG.getNode(Opc, dl, VT, V1, V2);
3061   }
3062 }
3063
3064 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3065   MachineFunction &MF = DAG.getMachineFunction();
3066   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3067   int ReturnAddrIndex = FuncInfo->getRAIndex();
3068
3069   if (ReturnAddrIndex == 0) {
3070     // Set up a frame object for the return address.
3071     unsigned SlotSize = RegInfo->getSlotSize();
3072     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3073                                                            false);
3074     FuncInfo->setRAIndex(ReturnAddrIndex);
3075   }
3076
3077   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3078 }
3079
3080 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3081                                        bool hasSymbolicDisplacement) {
3082   // Offset should fit into 32 bit immediate field.
3083   if (!isInt<32>(Offset))
3084     return false;
3085
3086   // If we don't have a symbolic displacement - we don't have any extra
3087   // restrictions.
3088   if (!hasSymbolicDisplacement)
3089     return true;
3090
3091   // FIXME: Some tweaks might be needed for medium code model.
3092   if (M != CodeModel::Small && M != CodeModel::Kernel)
3093     return false;
3094
3095   // For small code model we assume that latest object is 16MB before end of 31
3096   // bits boundary. We may also accept pretty large negative constants knowing
3097   // that all objects are in the positive half of address space.
3098   if (M == CodeModel::Small && Offset < 16*1024*1024)
3099     return true;
3100
3101   // For kernel code model we know that all object resist in the negative half
3102   // of 32bits address space. We may not accept negative offsets, since they may
3103   // be just off and we may accept pretty large positive ones.
3104   if (M == CodeModel::Kernel && Offset > 0)
3105     return true;
3106
3107   return false;
3108 }
3109
3110 /// isCalleePop - Determines whether the callee is required to pop its
3111 /// own arguments. Callee pop is necessary to support tail calls.
3112 bool X86::isCalleePop(CallingConv::ID CallingConv,
3113                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3114   if (IsVarArg)
3115     return false;
3116
3117   switch (CallingConv) {
3118   default:
3119     return false;
3120   case CallingConv::X86_StdCall:
3121     return !is64Bit;
3122   case CallingConv::X86_FastCall:
3123     return !is64Bit;
3124   case CallingConv::X86_ThisCall:
3125     return !is64Bit;
3126   case CallingConv::Fast:
3127     return TailCallOpt;
3128   case CallingConv::GHC:
3129     return TailCallOpt;
3130   case CallingConv::HiPE:
3131     return TailCallOpt;
3132   }
3133 }
3134
3135 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3136 /// specific condition code, returning the condition code and the LHS/RHS of the
3137 /// comparison to make.
3138 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3139                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3140   if (!isFP) {
3141     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3142       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3143         // X > -1   -> X == 0, jump !sign.
3144         RHS = DAG.getConstant(0, RHS.getValueType());
3145         return X86::COND_NS;
3146       }
3147       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3148         // X < 0   -> X == 0, jump on sign.
3149         return X86::COND_S;
3150       }
3151       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3152         // X < 1   -> X <= 0
3153         RHS = DAG.getConstant(0, RHS.getValueType());
3154         return X86::COND_LE;
3155       }
3156     }
3157
3158     switch (SetCCOpcode) {
3159     default: llvm_unreachable("Invalid integer condition!");
3160     case ISD::SETEQ:  return X86::COND_E;
3161     case ISD::SETGT:  return X86::COND_G;
3162     case ISD::SETGE:  return X86::COND_GE;
3163     case ISD::SETLT:  return X86::COND_L;
3164     case ISD::SETLE:  return X86::COND_LE;
3165     case ISD::SETNE:  return X86::COND_NE;
3166     case ISD::SETULT: return X86::COND_B;
3167     case ISD::SETUGT: return X86::COND_A;
3168     case ISD::SETULE: return X86::COND_BE;
3169     case ISD::SETUGE: return X86::COND_AE;
3170     }
3171   }
3172
3173   // First determine if it is required or is profitable to flip the operands.
3174
3175   // If LHS is a foldable load, but RHS is not, flip the condition.
3176   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3177       !ISD::isNON_EXTLoad(RHS.getNode())) {
3178     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3179     std::swap(LHS, RHS);
3180   }
3181
3182   switch (SetCCOpcode) {
3183   default: break;
3184   case ISD::SETOLT:
3185   case ISD::SETOLE:
3186   case ISD::SETUGT:
3187   case ISD::SETUGE:
3188     std::swap(LHS, RHS);
3189     break;
3190   }
3191
3192   // On a floating point condition, the flags are set as follows:
3193   // ZF  PF  CF   op
3194   //  0 | 0 | 0 | X > Y
3195   //  0 | 0 | 1 | X < Y
3196   //  1 | 0 | 0 | X == Y
3197   //  1 | 1 | 1 | unordered
3198   switch (SetCCOpcode) {
3199   default: llvm_unreachable("Condcode should be pre-legalized away");
3200   case ISD::SETUEQ:
3201   case ISD::SETEQ:   return X86::COND_E;
3202   case ISD::SETOLT:              // flipped
3203   case ISD::SETOGT:
3204   case ISD::SETGT:   return X86::COND_A;
3205   case ISD::SETOLE:              // flipped
3206   case ISD::SETOGE:
3207   case ISD::SETGE:   return X86::COND_AE;
3208   case ISD::SETUGT:              // flipped
3209   case ISD::SETULT:
3210   case ISD::SETLT:   return X86::COND_B;
3211   case ISD::SETUGE:              // flipped
3212   case ISD::SETULE:
3213   case ISD::SETLE:   return X86::COND_BE;
3214   case ISD::SETONE:
3215   case ISD::SETNE:   return X86::COND_NE;
3216   case ISD::SETUO:   return X86::COND_P;
3217   case ISD::SETO:    return X86::COND_NP;
3218   case ISD::SETOEQ:
3219   case ISD::SETUNE:  return X86::COND_INVALID;
3220   }
3221 }
3222
3223 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3224 /// code. Current x86 isa includes the following FP cmov instructions:
3225 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3226 static bool hasFPCMov(unsigned X86CC) {
3227   switch (X86CC) {
3228   default:
3229     return false;
3230   case X86::COND_B:
3231   case X86::COND_BE:
3232   case X86::COND_E:
3233   case X86::COND_P:
3234   case X86::COND_A:
3235   case X86::COND_AE:
3236   case X86::COND_NE:
3237   case X86::COND_NP:
3238     return true;
3239   }
3240 }
3241
3242 /// isFPImmLegal - Returns true if the target can instruction select the
3243 /// specified FP immediate natively. If false, the legalizer will
3244 /// materialize the FP immediate as a load from a constant pool.
3245 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3246   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3247     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3248       return true;
3249   }
3250   return false;
3251 }
3252
3253 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3254 /// the specified range (L, H].
3255 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3256   return (Val < 0) || (Val >= Low && Val < Hi);
3257 }
3258
3259 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3260 /// specified value.
3261 static bool isUndefOrEqual(int Val, int CmpVal) {
3262   return (Val < 0 || Val == CmpVal);
3263 }
3264
3265 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3266 /// from position Pos and ending in Pos+Size, falls within the specified
3267 /// sequential range (L, L+Pos]. or is undef.
3268 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3269                                        unsigned Pos, unsigned Size, int Low) {
3270   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3271     if (!isUndefOrEqual(Mask[i], Low))
3272       return false;
3273   return true;
3274 }
3275
3276 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3277 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3278 /// the second operand.
3279 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3280   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3281     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3282   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3283     return (Mask[0] < 2 && Mask[1] < 2);
3284   return false;
3285 }
3286
3287 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3288 /// is suitable for input to PSHUFHW.
3289 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3290   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3291     return false;
3292
3293   // Lower quadword copied in order or undef.
3294   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3295     return false;
3296
3297   // Upper quadword shuffled.
3298   for (unsigned i = 4; i != 8; ++i)
3299     if (!isUndefOrInRange(Mask[i], 4, 8))
3300       return false;
3301
3302   if (VT == MVT::v16i16) {
3303     // Lower quadword copied in order or undef.
3304     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3305       return false;
3306
3307     // Upper quadword shuffled.
3308     for (unsigned i = 12; i != 16; ++i)
3309       if (!isUndefOrInRange(Mask[i], 12, 16))
3310         return false;
3311   }
3312
3313   return true;
3314 }
3315
3316 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3317 /// is suitable for input to PSHUFLW.
3318 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3319   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3320     return false;
3321
3322   // Upper quadword copied in order.
3323   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3324     return false;
3325
3326   // Lower quadword shuffled.
3327   for (unsigned i = 0; i != 4; ++i)
3328     if (!isUndefOrInRange(Mask[i], 0, 4))
3329       return false;
3330
3331   if (VT == MVT::v16i16) {
3332     // Upper quadword copied in order.
3333     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3334       return false;
3335
3336     // Lower quadword shuffled.
3337     for (unsigned i = 8; i != 12; ++i)
3338       if (!isUndefOrInRange(Mask[i], 8, 12))
3339         return false;
3340   }
3341
3342   return true;
3343 }
3344
3345 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3346 /// is suitable for input to PALIGNR.
3347 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3348                           const X86Subtarget *Subtarget) {
3349   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3350       (VT.getSizeInBits() == 256 && !Subtarget->hasInt256()))
3351     return false;
3352
3353   unsigned NumElts = VT.getVectorNumElements();
3354   unsigned NumLanes = VT.getSizeInBits()/128;
3355   unsigned NumLaneElts = NumElts/NumLanes;
3356
3357   // Do not handle 64-bit element shuffles with palignr.
3358   if (NumLaneElts == 2)
3359     return false;
3360
3361   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3362     unsigned i;
3363     for (i = 0; i != NumLaneElts; ++i) {
3364       if (Mask[i+l] >= 0)
3365         break;
3366     }
3367
3368     // Lane is all undef, go to next lane
3369     if (i == NumLaneElts)
3370       continue;
3371
3372     int Start = Mask[i+l];
3373
3374     // Make sure its in this lane in one of the sources
3375     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3376         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3377       return false;
3378
3379     // If not lane 0, then we must match lane 0
3380     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3381       return false;
3382
3383     // Correct second source to be contiguous with first source
3384     if (Start >= (int)NumElts)
3385       Start -= NumElts - NumLaneElts;
3386
3387     // Make sure we're shifting in the right direction.
3388     if (Start <= (int)(i+l))
3389       return false;
3390
3391     Start -= i;
3392
3393     // Check the rest of the elements to see if they are consecutive.
3394     for (++i; i != NumLaneElts; ++i) {
3395       int Idx = Mask[i+l];
3396
3397       // Make sure its in this lane
3398       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3399           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3400         return false;
3401
3402       // If not lane 0, then we must match lane 0
3403       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3404         return false;
3405
3406       if (Idx >= (int)NumElts)
3407         Idx -= NumElts - NumLaneElts;
3408
3409       if (!isUndefOrEqual(Idx, Start+i))
3410         return false;
3411
3412     }
3413   }
3414
3415   return true;
3416 }
3417
3418 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3419 /// the two vector operands have swapped position.
3420 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3421                                      unsigned NumElems) {
3422   for (unsigned i = 0; i != NumElems; ++i) {
3423     int idx = Mask[i];
3424     if (idx < 0)
3425       continue;
3426     else if (idx < (int)NumElems)
3427       Mask[i] = idx + NumElems;
3428     else
3429       Mask[i] = idx - NumElems;
3430   }
3431 }
3432
3433 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3434 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3435 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3436 /// reverse of what x86 shuffles want.
3437 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3438                         bool Commuted = false) {
3439   if (!HasFp256 && VT.getSizeInBits() == 256)
3440     return false;
3441
3442   unsigned NumElems = VT.getVectorNumElements();
3443   unsigned NumLanes = VT.getSizeInBits()/128;
3444   unsigned NumLaneElems = NumElems/NumLanes;
3445
3446   if (NumLaneElems != 2 && NumLaneElems != 4)
3447     return false;
3448
3449   // VSHUFPSY divides the resulting vector into 4 chunks.
3450   // The sources are also splitted into 4 chunks, and each destination
3451   // chunk must come from a different source chunk.
3452   //
3453   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3454   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3455   //
3456   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3457   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3458   //
3459   // VSHUFPDY divides the resulting vector into 4 chunks.
3460   // The sources are also splitted into 4 chunks, and each destination
3461   // chunk must come from a different source chunk.
3462   //
3463   //  SRC1 =>      X3       X2       X1       X0
3464   //  SRC2 =>      Y3       Y2       Y1       Y0
3465   //
3466   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3467   //
3468   unsigned HalfLaneElems = NumLaneElems/2;
3469   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3470     for (unsigned i = 0; i != NumLaneElems; ++i) {
3471       int Idx = Mask[i+l];
3472       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3473       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3474         return false;
3475       // For VSHUFPSY, the mask of the second half must be the same as the
3476       // first but with the appropriate offsets. This works in the same way as
3477       // VPERMILPS works with masks.
3478       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3479         continue;
3480       if (!isUndefOrEqual(Idx, Mask[i]+l))
3481         return false;
3482     }
3483   }
3484
3485   return true;
3486 }
3487
3488 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3489 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3490 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3491   if (!VT.is128BitVector())
3492     return false;
3493
3494   unsigned NumElems = VT.getVectorNumElements();
3495
3496   if (NumElems != 4)
3497     return false;
3498
3499   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3500   return isUndefOrEqual(Mask[0], 6) &&
3501          isUndefOrEqual(Mask[1], 7) &&
3502          isUndefOrEqual(Mask[2], 2) &&
3503          isUndefOrEqual(Mask[3], 3);
3504 }
3505
3506 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3507 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3508 /// <2, 3, 2, 3>
3509 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3510   if (!VT.is128BitVector())
3511     return false;
3512
3513   unsigned NumElems = VT.getVectorNumElements();
3514
3515   if (NumElems != 4)
3516     return false;
3517
3518   return isUndefOrEqual(Mask[0], 2) &&
3519          isUndefOrEqual(Mask[1], 3) &&
3520          isUndefOrEqual(Mask[2], 2) &&
3521          isUndefOrEqual(Mask[3], 3);
3522 }
3523
3524 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3525 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3526 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3527   if (!VT.is128BitVector())
3528     return false;
3529
3530   unsigned NumElems = VT.getVectorNumElements();
3531
3532   if (NumElems != 2 && NumElems != 4)
3533     return false;
3534
3535   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3536     if (!isUndefOrEqual(Mask[i], i + NumElems))
3537       return false;
3538
3539   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3540     if (!isUndefOrEqual(Mask[i], i))
3541       return false;
3542
3543   return true;
3544 }
3545
3546 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3547 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3548 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3549   if (!VT.is128BitVector())
3550     return false;
3551
3552   unsigned NumElems = VT.getVectorNumElements();
3553
3554   if (NumElems != 2 && NumElems != 4)
3555     return false;
3556
3557   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3558     if (!isUndefOrEqual(Mask[i], i))
3559       return false;
3560
3561   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3562     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3563       return false;
3564
3565   return true;
3566 }
3567
3568 //
3569 // Some special combinations that can be optimized.
3570 //
3571 static
3572 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3573                                SelectionDAG &DAG) {
3574   EVT VT = SVOp->getValueType(0);
3575   DebugLoc dl = SVOp->getDebugLoc();
3576
3577   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3578     return SDValue();
3579
3580   ArrayRef<int> Mask = SVOp->getMask();
3581
3582   // These are the special masks that may be optimized.
3583   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3584   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3585   bool MatchEvenMask = true;
3586   bool MatchOddMask  = true;
3587   for (int i=0; i<8; ++i) {
3588     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3589       MatchEvenMask = false;
3590     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3591       MatchOddMask = false;
3592   }
3593
3594   if (!MatchEvenMask && !MatchOddMask)
3595     return SDValue();
3596
3597   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3598
3599   SDValue Op0 = SVOp->getOperand(0);
3600   SDValue Op1 = SVOp->getOperand(1);
3601
3602   if (MatchEvenMask) {
3603     // Shift the second operand right to 32 bits.
3604     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3605     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3606   } else {
3607     // Shift the first operand left to 32 bits.
3608     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3609     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3610   }
3611   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3612   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3613 }
3614
3615 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3616 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3617 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3618                          bool HasInt256, bool V2IsSplat = false) {
3619   unsigned NumElts = VT.getVectorNumElements();
3620
3621   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3622          "Unsupported vector type for unpckh");
3623
3624   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3625       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
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       if (!isUndefOrEqual(BitI, j))
3640         return false;
3641       if (V2IsSplat) {
3642         if (!isUndefOrEqual(BitI1, NumElts))
3643           return false;
3644       } else {
3645         if (!isUndefOrEqual(BitI1, j + NumElts))
3646           return false;
3647       }
3648     }
3649   }
3650
3651   return true;
3652 }
3653
3654 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3655 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3656 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3657                          bool HasInt256, bool V2IsSplat = false) {
3658   unsigned NumElts = VT.getVectorNumElements();
3659
3660   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3661          "Unsupported vector type for unpckh");
3662
3663   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3664       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3665     return false;
3666
3667   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3668   // independently on 128-bit lanes.
3669   unsigned NumLanes = VT.getSizeInBits()/128;
3670   unsigned NumLaneElts = NumElts/NumLanes;
3671
3672   for (unsigned l = 0; l != NumLanes; ++l) {
3673     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3674          i != (l+1)*NumLaneElts; i += 2, ++j) {
3675       int BitI  = Mask[i];
3676       int BitI1 = Mask[i+1];
3677       if (!isUndefOrEqual(BitI, j))
3678         return false;
3679       if (V2IsSplat) {
3680         if (isUndefOrEqual(BitI1, NumElts))
3681           return false;
3682       } else {
3683         if (!isUndefOrEqual(BitI1, j+NumElts))
3684           return false;
3685       }
3686     }
3687   }
3688   return true;
3689 }
3690
3691 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3692 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3693 /// <0, 0, 1, 1>
3694 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3695                                   bool HasInt256) {
3696   unsigned NumElts = VT.getVectorNumElements();
3697
3698   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3699          "Unsupported vector type for unpckh");
3700
3701   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3702       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3703     return false;
3704
3705   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3706   // FIXME: Need a better way to get rid of this, there's no latency difference
3707   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3708   // the former later. We should also remove the "_undef" special mask.
3709   if (NumElts == 4 && VT.getSizeInBits() == 256)
3710     return false;
3711
3712   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3713   // independently on 128-bit lanes.
3714   unsigned NumLanes = VT.getSizeInBits()/128;
3715   unsigned NumLaneElts = NumElts/NumLanes;
3716
3717   for (unsigned l = 0; l != NumLanes; ++l) {
3718     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3719          i != (l+1)*NumLaneElts;
3720          i += 2, ++j) {
3721       int BitI  = Mask[i];
3722       int BitI1 = Mask[i+1];
3723
3724       if (!isUndefOrEqual(BitI, j))
3725         return false;
3726       if (!isUndefOrEqual(BitI1, j))
3727         return false;
3728     }
3729   }
3730
3731   return true;
3732 }
3733
3734 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3735 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3736 /// <2, 2, 3, 3>
3737 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3738   unsigned NumElts = VT.getVectorNumElements();
3739
3740   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3741          "Unsupported vector type for unpckh");
3742
3743   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3744       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3745     return false;
3746
3747   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3748   // independently on 128-bit lanes.
3749   unsigned NumLanes = VT.getSizeInBits()/128;
3750   unsigned NumLaneElts = NumElts/NumLanes;
3751
3752   for (unsigned l = 0; l != NumLanes; ++l) {
3753     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3754          i != (l+1)*NumLaneElts; i += 2, ++j) {
3755       int BitI  = Mask[i];
3756       int BitI1 = Mask[i+1];
3757       if (!isUndefOrEqual(BitI, j))
3758         return false;
3759       if (!isUndefOrEqual(BitI1, j))
3760         return false;
3761     }
3762   }
3763   return true;
3764 }
3765
3766 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3767 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3768 /// MOVSD, and MOVD, i.e. setting the lowest element.
3769 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3770   if (VT.getVectorElementType().getSizeInBits() < 32)
3771     return false;
3772   if (!VT.is128BitVector())
3773     return false;
3774
3775   unsigned NumElts = VT.getVectorNumElements();
3776
3777   if (!isUndefOrEqual(Mask[0], NumElts))
3778     return false;
3779
3780   for (unsigned i = 1; i != NumElts; ++i)
3781     if (!isUndefOrEqual(Mask[i], i))
3782       return false;
3783
3784   return true;
3785 }
3786
3787 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3788 /// as permutations between 128-bit chunks or halves. As an example: this
3789 /// shuffle bellow:
3790 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3791 /// The first half comes from the second half of V1 and the second half from the
3792 /// the second half of V2.
3793 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3794   if (!HasFp256 || !VT.is256BitVector())
3795     return false;
3796
3797   // The shuffle result is divided into half A and half B. In total the two
3798   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3799   // B must come from C, D, E or F.
3800   unsigned HalfSize = VT.getVectorNumElements()/2;
3801   bool MatchA = false, MatchB = false;
3802
3803   // Check if A comes from one of C, D, E, F.
3804   for (unsigned Half = 0; Half != 4; ++Half) {
3805     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3806       MatchA = true;
3807       break;
3808     }
3809   }
3810
3811   // Check if B comes from one of C, D, E, F.
3812   for (unsigned Half = 0; Half != 4; ++Half) {
3813     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3814       MatchB = true;
3815       break;
3816     }
3817   }
3818
3819   return MatchA && MatchB;
3820 }
3821
3822 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3823 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3824 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3825   EVT VT = SVOp->getValueType(0);
3826
3827   unsigned HalfSize = VT.getVectorNumElements()/2;
3828
3829   unsigned FstHalf = 0, SndHalf = 0;
3830   for (unsigned i = 0; i < HalfSize; ++i) {
3831     if (SVOp->getMaskElt(i) > 0) {
3832       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3833       break;
3834     }
3835   }
3836   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3837     if (SVOp->getMaskElt(i) > 0) {
3838       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3839       break;
3840     }
3841   }
3842
3843   return (FstHalf | (SndHalf << 4));
3844 }
3845
3846 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3847 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3848 /// Note that VPERMIL mask matching is different depending whether theunderlying
3849 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3850 /// to the same elements of the low, but to the higher half of the source.
3851 /// In VPERMILPD the two lanes could be shuffled independently of each other
3852 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3853 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3854   if (!HasFp256)
3855     return false;
3856
3857   unsigned NumElts = VT.getVectorNumElements();
3858   // Only match 256-bit with 32/64-bit types
3859   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3860     return false;
3861
3862   unsigned NumLanes = VT.getSizeInBits()/128;
3863   unsigned LaneSize = NumElts/NumLanes;
3864   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3865     for (unsigned i = 0; i != LaneSize; ++i) {
3866       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3867         return false;
3868       if (NumElts != 8 || l == 0)
3869         continue;
3870       // VPERMILPS handling
3871       if (Mask[i] < 0)
3872         continue;
3873       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3874         return false;
3875     }
3876   }
3877
3878   return true;
3879 }
3880
3881 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3882 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3883 /// element of vector 2 and the other elements to come from vector 1 in order.
3884 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3885                                bool V2IsSplat = false, bool V2IsUndef = false) {
3886   if (!VT.is128BitVector())
3887     return false;
3888
3889   unsigned NumOps = VT.getVectorNumElements();
3890   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3891     return false;
3892
3893   if (!isUndefOrEqual(Mask[0], 0))
3894     return false;
3895
3896   for (unsigned i = 1; i != NumOps; ++i)
3897     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3898           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3899           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3900       return false;
3901
3902   return true;
3903 }
3904
3905 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3906 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3907 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3908 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3909                            const X86Subtarget *Subtarget) {
3910   if (!Subtarget->hasSSE3())
3911     return false;
3912
3913   unsigned NumElems = VT.getVectorNumElements();
3914
3915   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3916       (VT.getSizeInBits() == 256 && NumElems != 8))
3917     return false;
3918
3919   // "i+1" is the value the indexed mask element must have
3920   for (unsigned i = 0; i != NumElems; i += 2)
3921     if (!isUndefOrEqual(Mask[i], i+1) ||
3922         !isUndefOrEqual(Mask[i+1], i+1))
3923       return false;
3924
3925   return true;
3926 }
3927
3928 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3929 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3930 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3931 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3932                            const X86Subtarget *Subtarget) {
3933   if (!Subtarget->hasSSE3())
3934     return false;
3935
3936   unsigned NumElems = VT.getVectorNumElements();
3937
3938   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3939       (VT.getSizeInBits() == 256 && NumElems != 8))
3940     return false;
3941
3942   // "i" is the value the indexed mask element must have
3943   for (unsigned i = 0; i != NumElems; i += 2)
3944     if (!isUndefOrEqual(Mask[i], i) ||
3945         !isUndefOrEqual(Mask[i+1], i))
3946       return false;
3947
3948   return true;
3949 }
3950
3951 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3952 /// specifies a shuffle of elements that is suitable for input to 256-bit
3953 /// version of MOVDDUP.
3954 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3955   if (!HasFp256 || !VT.is256BitVector())
3956     return false;
3957
3958   unsigned NumElts = VT.getVectorNumElements();
3959   if (NumElts != 4)
3960     return false;
3961
3962   for (unsigned i = 0; i != NumElts/2; ++i)
3963     if (!isUndefOrEqual(Mask[i], 0))
3964       return false;
3965   for (unsigned i = NumElts/2; i != NumElts; ++i)
3966     if (!isUndefOrEqual(Mask[i], NumElts/2))
3967       return false;
3968   return true;
3969 }
3970
3971 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3972 /// specifies a shuffle of elements that is suitable for input to 128-bit
3973 /// version of MOVDDUP.
3974 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3975   if (!VT.is128BitVector())
3976     return false;
3977
3978   unsigned e = VT.getVectorNumElements() / 2;
3979   for (unsigned i = 0; i != e; ++i)
3980     if (!isUndefOrEqual(Mask[i], i))
3981       return false;
3982   for (unsigned i = 0; i != e; ++i)
3983     if (!isUndefOrEqual(Mask[e+i], i))
3984       return false;
3985   return true;
3986 }
3987
3988 /// isVEXTRACTF128Index - Return true if the specified
3989 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3990 /// suitable for input to VEXTRACTF128.
3991 bool X86::isVEXTRACTF128Index(SDNode *N) {
3992   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3993     return false;
3994
3995   // The index should be aligned on a 128-bit boundary.
3996   uint64_t Index =
3997     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3998
3999   unsigned VL = N->getValueType(0).getVectorNumElements();
4000   unsigned VBits = N->getValueType(0).getSizeInBits();
4001   unsigned ElSize = VBits / VL;
4002   bool Result = (Index * ElSize) % 128 == 0;
4003
4004   return Result;
4005 }
4006
4007 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4008 /// operand specifies a subvector insert that is suitable for input to
4009 /// VINSERTF128.
4010 bool X86::isVINSERTF128Index(SDNode *N) {
4011   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4012     return false;
4013
4014   // The index should be aligned on a 128-bit boundary.
4015   uint64_t Index =
4016     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4017
4018   unsigned VL = N->getValueType(0).getVectorNumElements();
4019   unsigned VBits = N->getValueType(0).getSizeInBits();
4020   unsigned ElSize = VBits / VL;
4021   bool Result = (Index * ElSize) % 128 == 0;
4022
4023   return Result;
4024 }
4025
4026 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4027 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4028 /// Handles 128-bit and 256-bit.
4029 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4030   EVT VT = N->getValueType(0);
4031
4032   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4033          "Unsupported vector type for PSHUF/SHUFP");
4034
4035   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4036   // independently on 128-bit lanes.
4037   unsigned NumElts = VT.getVectorNumElements();
4038   unsigned NumLanes = VT.getSizeInBits()/128;
4039   unsigned NumLaneElts = NumElts/NumLanes;
4040
4041   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4042          "Only supports 2 or 4 elements per lane");
4043
4044   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4045   unsigned Mask = 0;
4046   for (unsigned i = 0; i != NumElts; ++i) {
4047     int Elt = N->getMaskElt(i);
4048     if (Elt < 0) continue;
4049     Elt &= NumLaneElts - 1;
4050     unsigned ShAmt = (i << Shift) % 8;
4051     Mask |= Elt << ShAmt;
4052   }
4053
4054   return Mask;
4055 }
4056
4057 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4058 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4059 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4060   EVT VT = N->getValueType(0);
4061
4062   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4063          "Unsupported vector type for PSHUFHW");
4064
4065   unsigned NumElts = VT.getVectorNumElements();
4066
4067   unsigned Mask = 0;
4068   for (unsigned l = 0; l != NumElts; l += 8) {
4069     // 8 nodes per lane, but we only care about the last 4.
4070     for (unsigned i = 0; i < 4; ++i) {
4071       int Elt = N->getMaskElt(l+i+4);
4072       if (Elt < 0) continue;
4073       Elt &= 0x3; // only 2-bits.
4074       Mask |= Elt << (i * 2);
4075     }
4076   }
4077
4078   return Mask;
4079 }
4080
4081 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4082 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4083 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4084   EVT VT = N->getValueType(0);
4085
4086   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4087          "Unsupported vector type for PSHUFHW");
4088
4089   unsigned NumElts = VT.getVectorNumElements();
4090
4091   unsigned Mask = 0;
4092   for (unsigned l = 0; l != NumElts; l += 8) {
4093     // 8 nodes per lane, but we only care about the first 4.
4094     for (unsigned i = 0; i < 4; ++i) {
4095       int Elt = N->getMaskElt(l+i);
4096       if (Elt < 0) continue;
4097       Elt &= 0x3; // only 2-bits
4098       Mask |= Elt << (i * 2);
4099     }
4100   }
4101
4102   return Mask;
4103 }
4104
4105 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4106 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4107 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4108   EVT VT = SVOp->getValueType(0);
4109   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4110
4111   unsigned NumElts = VT.getVectorNumElements();
4112   unsigned NumLanes = VT.getSizeInBits()/128;
4113   unsigned NumLaneElts = NumElts/NumLanes;
4114
4115   int Val = 0;
4116   unsigned i;
4117   for (i = 0; i != NumElts; ++i) {
4118     Val = SVOp->getMaskElt(i);
4119     if (Val >= 0)
4120       break;
4121   }
4122   if (Val >= (int)NumElts)
4123     Val -= NumElts - NumLaneElts;
4124
4125   assert(Val - i > 0 && "PALIGNR imm should be positive");
4126   return (Val - i) * EltSize;
4127 }
4128
4129 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4130 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4131 /// instructions.
4132 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4133   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4134     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4135
4136   uint64_t Index =
4137     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4138
4139   EVT VecVT = N->getOperand(0).getValueType();
4140   EVT ElVT = VecVT.getVectorElementType();
4141
4142   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4143   return Index / NumElemsPerChunk;
4144 }
4145
4146 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4147 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4148 /// instructions.
4149 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4150   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4151     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4152
4153   uint64_t Index =
4154     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4155
4156   EVT VecVT = N->getValueType(0);
4157   EVT ElVT = VecVT.getVectorElementType();
4158
4159   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4160   return Index / NumElemsPerChunk;
4161 }
4162
4163 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4164 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4165 /// Handles 256-bit.
4166 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4167   EVT VT = N->getValueType(0);
4168
4169   unsigned NumElts = VT.getVectorNumElements();
4170
4171   assert((VT.is256BitVector() && NumElts == 4) &&
4172          "Unsupported vector type for VPERMQ/VPERMPD");
4173
4174   unsigned Mask = 0;
4175   for (unsigned i = 0; i != NumElts; ++i) {
4176     int Elt = N->getMaskElt(i);
4177     if (Elt < 0)
4178       continue;
4179     Mask |= Elt << (i*2);
4180   }
4181
4182   return Mask;
4183 }
4184 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4185 /// constant +0.0.
4186 bool X86::isZeroNode(SDValue Elt) {
4187   return ((isa<ConstantSDNode>(Elt) &&
4188            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4189           (isa<ConstantFPSDNode>(Elt) &&
4190            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4191 }
4192
4193 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4194 /// their permute mask.
4195 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4196                                     SelectionDAG &DAG) {
4197   EVT VT = SVOp->getValueType(0);
4198   unsigned NumElems = VT.getVectorNumElements();
4199   SmallVector<int, 8> MaskVec;
4200
4201   for (unsigned i = 0; i != NumElems; ++i) {
4202     int Idx = SVOp->getMaskElt(i);
4203     if (Idx >= 0) {
4204       if (Idx < (int)NumElems)
4205         Idx += NumElems;
4206       else
4207         Idx -= NumElems;
4208     }
4209     MaskVec.push_back(Idx);
4210   }
4211   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4212                               SVOp->getOperand(0), &MaskVec[0]);
4213 }
4214
4215 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4216 /// match movhlps. The lower half elements should come from upper half of
4217 /// V1 (and in order), and the upper half elements should come from the upper
4218 /// half of V2 (and in order).
4219 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4220   if (!VT.is128BitVector())
4221     return false;
4222   if (VT.getVectorNumElements() != 4)
4223     return false;
4224   for (unsigned i = 0, e = 2; i != e; ++i)
4225     if (!isUndefOrEqual(Mask[i], i+2))
4226       return false;
4227   for (unsigned i = 2; i != 4; ++i)
4228     if (!isUndefOrEqual(Mask[i], i+4))
4229       return false;
4230   return true;
4231 }
4232
4233 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4234 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4235 /// required.
4236 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4237   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4238     return false;
4239   N = N->getOperand(0).getNode();
4240   if (!ISD::isNON_EXTLoad(N))
4241     return false;
4242   if (LD)
4243     *LD = cast<LoadSDNode>(N);
4244   return true;
4245 }
4246
4247 // Test whether the given value is a vector value which will be legalized
4248 // into a load.
4249 static bool WillBeConstantPoolLoad(SDNode *N) {
4250   if (N->getOpcode() != ISD::BUILD_VECTOR)
4251     return false;
4252
4253   // Check for any non-constant elements.
4254   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4255     switch (N->getOperand(i).getNode()->getOpcode()) {
4256     case ISD::UNDEF:
4257     case ISD::ConstantFP:
4258     case ISD::Constant:
4259       break;
4260     default:
4261       return false;
4262     }
4263
4264   // Vectors of all-zeros and all-ones are materialized with special
4265   // instructions rather than being loaded.
4266   return !ISD::isBuildVectorAllZeros(N) &&
4267          !ISD::isBuildVectorAllOnes(N);
4268 }
4269
4270 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4271 /// match movlp{s|d}. The lower half elements should come from lower half of
4272 /// V1 (and in order), and the upper half elements should come from the upper
4273 /// half of V2 (and in order). And since V1 will become the source of the
4274 /// MOVLP, it must be either a vector load or a scalar load to vector.
4275 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4276                                ArrayRef<int> Mask, EVT VT) {
4277   if (!VT.is128BitVector())
4278     return false;
4279
4280   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4281     return false;
4282   // Is V2 is a vector load, don't do this transformation. We will try to use
4283   // load folding shufps op.
4284   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4285     return false;
4286
4287   unsigned NumElems = VT.getVectorNumElements();
4288
4289   if (NumElems != 2 && NumElems != 4)
4290     return false;
4291   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4292     if (!isUndefOrEqual(Mask[i], i))
4293       return false;
4294   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4295     if (!isUndefOrEqual(Mask[i], i+NumElems))
4296       return false;
4297   return true;
4298 }
4299
4300 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4301 /// all the same.
4302 static bool isSplatVector(SDNode *N) {
4303   if (N->getOpcode() != ISD::BUILD_VECTOR)
4304     return false;
4305
4306   SDValue SplatValue = N->getOperand(0);
4307   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4308     if (N->getOperand(i) != SplatValue)
4309       return false;
4310   return true;
4311 }
4312
4313 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4314 /// to an zero vector.
4315 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4316 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4317   SDValue V1 = N->getOperand(0);
4318   SDValue V2 = N->getOperand(1);
4319   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4320   for (unsigned i = 0; i != NumElems; ++i) {
4321     int Idx = N->getMaskElt(i);
4322     if (Idx >= (int)NumElems) {
4323       unsigned Opc = V2.getOpcode();
4324       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4325         continue;
4326       if (Opc != ISD::BUILD_VECTOR ||
4327           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4328         return false;
4329     } else if (Idx >= 0) {
4330       unsigned Opc = V1.getOpcode();
4331       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4332         continue;
4333       if (Opc != ISD::BUILD_VECTOR ||
4334           !X86::isZeroNode(V1.getOperand(Idx)))
4335         return false;
4336     }
4337   }
4338   return true;
4339 }
4340
4341 /// getZeroVector - Returns a vector of specified type with all zero elements.
4342 ///
4343 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4344                              SelectionDAG &DAG, DebugLoc dl) {
4345   assert(VT.isVector() && "Expected a vector type");
4346   unsigned Size = VT.getSizeInBits();
4347
4348   // Always build SSE zero vectors as <4 x i32> bitcasted
4349   // to their dest type. This ensures they get CSE'd.
4350   SDValue Vec;
4351   if (Size == 128) {  // SSE
4352     if (Subtarget->hasSSE2()) {  // SSE2
4353       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4354       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4355     } else { // SSE1
4356       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4357       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4358     }
4359   } else if (Size == 256) { // AVX
4360     if (Subtarget->hasInt256()) { // AVX2
4361       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4362       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4363       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4364     } else {
4365       // 256-bit logic and arithmetic instructions in AVX are all
4366       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4367       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4368       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4369       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4370     }
4371   } else
4372     llvm_unreachable("Unexpected vector type");
4373
4374   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4375 }
4376
4377 /// getOnesVector - Returns a vector of specified type with all bits set.
4378 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4379 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4380 /// Then bitcast to their original type, ensuring they get CSE'd.
4381 static SDValue getOnesVector(EVT VT, bool HasInt256, SelectionDAG &DAG,
4382                              DebugLoc dl) {
4383   assert(VT.isVector() && "Expected a vector type");
4384   unsigned Size = VT.getSizeInBits();
4385
4386   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4387   SDValue Vec;
4388   if (Size == 256) {
4389     if (HasInt256) { // AVX2
4390       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4391       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4392     } else { // AVX
4393       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4394       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4395     }
4396   } else if (Size == 128) {
4397     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4398   } else
4399     llvm_unreachable("Unexpected vector type");
4400
4401   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4402 }
4403
4404 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4405 /// that point to V2 points to its first element.
4406 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4407   for (unsigned i = 0; i != NumElems; ++i) {
4408     if (Mask[i] > (int)NumElems) {
4409       Mask[i] = NumElems;
4410     }
4411   }
4412 }
4413
4414 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4415 /// operation of specified width.
4416 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4417                        SDValue V2) {
4418   unsigned NumElems = VT.getVectorNumElements();
4419   SmallVector<int, 8> Mask;
4420   Mask.push_back(NumElems);
4421   for (unsigned i = 1; i != NumElems; ++i)
4422     Mask.push_back(i);
4423   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4424 }
4425
4426 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4427 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4428                           SDValue V2) {
4429   unsigned NumElems = VT.getVectorNumElements();
4430   SmallVector<int, 8> Mask;
4431   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4432     Mask.push_back(i);
4433     Mask.push_back(i + NumElems);
4434   }
4435   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4436 }
4437
4438 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4439 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4440                           SDValue V2) {
4441   unsigned NumElems = VT.getVectorNumElements();
4442   SmallVector<int, 8> Mask;
4443   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4444     Mask.push_back(i + Half);
4445     Mask.push_back(i + NumElems + Half);
4446   }
4447   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4448 }
4449
4450 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4451 // a generic shuffle instruction because the target has no such instructions.
4452 // Generate shuffles which repeat i16 and i8 several times until they can be
4453 // represented by v4f32 and then be manipulated by target suported shuffles.
4454 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4455   EVT VT = V.getValueType();
4456   int NumElems = VT.getVectorNumElements();
4457   DebugLoc dl = V.getDebugLoc();
4458
4459   while (NumElems > 4) {
4460     if (EltNo < NumElems/2) {
4461       V = getUnpackl(DAG, dl, VT, V, V);
4462     } else {
4463       V = getUnpackh(DAG, dl, VT, V, V);
4464       EltNo -= NumElems/2;
4465     }
4466     NumElems >>= 1;
4467   }
4468   return V;
4469 }
4470
4471 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4472 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4473   EVT VT = V.getValueType();
4474   DebugLoc dl = V.getDebugLoc();
4475   unsigned Size = VT.getSizeInBits();
4476
4477   if (Size == 128) {
4478     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4479     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4480     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4481                              &SplatMask[0]);
4482   } else if (Size == 256) {
4483     // To use VPERMILPS to splat scalars, the second half of indicies must
4484     // refer to the higher part, which is a duplication of the lower one,
4485     // because VPERMILPS can only handle in-lane permutations.
4486     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4487                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4488
4489     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4490     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4491                              &SplatMask[0]);
4492   } else
4493     llvm_unreachable("Vector size not supported");
4494
4495   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4496 }
4497
4498 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4499 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4500   EVT SrcVT = SV->getValueType(0);
4501   SDValue V1 = SV->getOperand(0);
4502   DebugLoc dl = SV->getDebugLoc();
4503
4504   int EltNo = SV->getSplatIndex();
4505   int NumElems = SrcVT.getVectorNumElements();
4506   unsigned Size = SrcVT.getSizeInBits();
4507
4508   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4509           "Unknown how to promote splat for type");
4510
4511   // Extract the 128-bit part containing the splat element and update
4512   // the splat element index when it refers to the higher register.
4513   if (Size == 256) {
4514     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4515     if (EltNo >= NumElems/2)
4516       EltNo -= NumElems/2;
4517   }
4518
4519   // All i16 and i8 vector types can't be used directly by a generic shuffle
4520   // instruction because the target has no such instruction. Generate shuffles
4521   // which repeat i16 and i8 several times until they fit in i32, and then can
4522   // be manipulated by target suported shuffles.
4523   EVT EltVT = SrcVT.getVectorElementType();
4524   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4525     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4526
4527   // Recreate the 256-bit vector and place the same 128-bit vector
4528   // into the low and high part. This is necessary because we want
4529   // to use VPERM* to shuffle the vectors
4530   if (Size == 256) {
4531     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4532   }
4533
4534   return getLegalSplat(DAG, V1, EltNo);
4535 }
4536
4537 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4538 /// vector of zero or undef vector.  This produces a shuffle where the low
4539 /// element of V2 is swizzled into the zero/undef vector, landing at element
4540 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4541 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4542                                            bool IsZero,
4543                                            const X86Subtarget *Subtarget,
4544                                            SelectionDAG &DAG) {
4545   EVT VT = V2.getValueType();
4546   SDValue V1 = IsZero
4547     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4548   unsigned NumElems = VT.getVectorNumElements();
4549   SmallVector<int, 16> MaskVec;
4550   for (unsigned i = 0; i != NumElems; ++i)
4551     // If this is the insertion idx, put the low elt of V2 here.
4552     MaskVec.push_back(i == Idx ? NumElems : i);
4553   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4554 }
4555
4556 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4557 /// target specific opcode. Returns true if the Mask could be calculated.
4558 /// Sets IsUnary to true if only uses one source.
4559 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4560                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4561   unsigned NumElems = VT.getVectorNumElements();
4562   SDValue ImmN;
4563
4564   IsUnary = false;
4565   switch(N->getOpcode()) {
4566   case X86ISD::SHUFP:
4567     ImmN = N->getOperand(N->getNumOperands()-1);
4568     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4569     break;
4570   case X86ISD::UNPCKH:
4571     DecodeUNPCKHMask(VT, Mask);
4572     break;
4573   case X86ISD::UNPCKL:
4574     DecodeUNPCKLMask(VT, Mask);
4575     break;
4576   case X86ISD::MOVHLPS:
4577     DecodeMOVHLPSMask(NumElems, Mask);
4578     break;
4579   case X86ISD::MOVLHPS:
4580     DecodeMOVLHPSMask(NumElems, Mask);
4581     break;
4582   case X86ISD::PSHUFD:
4583   case X86ISD::VPERMILP:
4584     ImmN = N->getOperand(N->getNumOperands()-1);
4585     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4586     IsUnary = true;
4587     break;
4588   case X86ISD::PSHUFHW:
4589     ImmN = N->getOperand(N->getNumOperands()-1);
4590     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4591     IsUnary = true;
4592     break;
4593   case X86ISD::PSHUFLW:
4594     ImmN = N->getOperand(N->getNumOperands()-1);
4595     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4596     IsUnary = true;
4597     break;
4598   case X86ISD::VPERMI:
4599     ImmN = N->getOperand(N->getNumOperands()-1);
4600     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4601     IsUnary = true;
4602     break;
4603   case X86ISD::MOVSS:
4604   case X86ISD::MOVSD: {
4605     // The index 0 always comes from the first element of the second source,
4606     // this is why MOVSS and MOVSD are used in the first place. The other
4607     // elements come from the other positions of the first source vector
4608     Mask.push_back(NumElems);
4609     for (unsigned i = 1; i != NumElems; ++i) {
4610       Mask.push_back(i);
4611     }
4612     break;
4613   }
4614   case X86ISD::VPERM2X128:
4615     ImmN = N->getOperand(N->getNumOperands()-1);
4616     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4617     if (Mask.empty()) return false;
4618     break;
4619   case X86ISD::MOVDDUP:
4620   case X86ISD::MOVLHPD:
4621   case X86ISD::MOVLPD:
4622   case X86ISD::MOVLPS:
4623   case X86ISD::MOVSHDUP:
4624   case X86ISD::MOVSLDUP:
4625   case X86ISD::PALIGN:
4626     // Not yet implemented
4627     return false;
4628   default: llvm_unreachable("unknown target shuffle node");
4629   }
4630
4631   return true;
4632 }
4633
4634 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4635 /// element of the result of the vector shuffle.
4636 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4637                                    unsigned Depth) {
4638   if (Depth == 6)
4639     return SDValue();  // Limit search depth.
4640
4641   SDValue V = SDValue(N, 0);
4642   EVT VT = V.getValueType();
4643   unsigned Opcode = V.getOpcode();
4644
4645   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4646   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4647     int Elt = SV->getMaskElt(Index);
4648
4649     if (Elt < 0)
4650       return DAG.getUNDEF(VT.getVectorElementType());
4651
4652     unsigned NumElems = VT.getVectorNumElements();
4653     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4654                                          : SV->getOperand(1);
4655     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4656   }
4657
4658   // Recurse into target specific vector shuffles to find scalars.
4659   if (isTargetShuffle(Opcode)) {
4660     MVT ShufVT = V.getValueType().getSimpleVT();
4661     unsigned NumElems = ShufVT.getVectorNumElements();
4662     SmallVector<int, 16> ShuffleMask;
4663     bool IsUnary;
4664
4665     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4666       return SDValue();
4667
4668     int Elt = ShuffleMask[Index];
4669     if (Elt < 0)
4670       return DAG.getUNDEF(ShufVT.getVectorElementType());
4671
4672     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4673                                          : N->getOperand(1);
4674     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4675                                Depth+1);
4676   }
4677
4678   // Actual nodes that may contain scalar elements
4679   if (Opcode == ISD::BITCAST) {
4680     V = V.getOperand(0);
4681     EVT SrcVT = V.getValueType();
4682     unsigned NumElems = VT.getVectorNumElements();
4683
4684     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4685       return SDValue();
4686   }
4687
4688   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4689     return (Index == 0) ? V.getOperand(0)
4690                         : DAG.getUNDEF(VT.getVectorElementType());
4691
4692   if (V.getOpcode() == ISD::BUILD_VECTOR)
4693     return V.getOperand(Index);
4694
4695   return SDValue();
4696 }
4697
4698 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4699 /// shuffle operation which come from a consecutively from a zero. The
4700 /// search can start in two different directions, from left or right.
4701 static
4702 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4703                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4704   unsigned i;
4705   for (i = 0; i != NumElems; ++i) {
4706     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4707     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4708     if (!(Elt.getNode() &&
4709          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4710       break;
4711   }
4712
4713   return i;
4714 }
4715
4716 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4717 /// correspond consecutively to elements from one of the vector operands,
4718 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4719 static
4720 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4721                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4722                               unsigned NumElems, unsigned &OpNum) {
4723   bool SeenV1 = false;
4724   bool SeenV2 = false;
4725
4726   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4727     int Idx = SVOp->getMaskElt(i);
4728     // Ignore undef indicies
4729     if (Idx < 0)
4730       continue;
4731
4732     if (Idx < (int)NumElems)
4733       SeenV1 = true;
4734     else
4735       SeenV2 = true;
4736
4737     // Only accept consecutive elements from the same vector
4738     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4739       return false;
4740   }
4741
4742   OpNum = SeenV1 ? 0 : 1;
4743   return true;
4744 }
4745
4746 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4747 /// logical left shift of a vector.
4748 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4749                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4750   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4751   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4752               false /* check zeros from right */, DAG);
4753   unsigned OpSrc;
4754
4755   if (!NumZeros)
4756     return false;
4757
4758   // Considering the elements in the mask that are not consecutive zeros,
4759   // check if they consecutively come from only one of the source vectors.
4760   //
4761   //               V1 = {X, A, B, C}     0
4762   //                         \  \  \    /
4763   //   vector_shuffle V1, V2 <1, 2, 3, X>
4764   //
4765   if (!isShuffleMaskConsecutive(SVOp,
4766             0,                   // Mask Start Index
4767             NumElems-NumZeros,   // Mask End Index(exclusive)
4768             NumZeros,            // Where to start looking in the src vector
4769             NumElems,            // Number of elements in vector
4770             OpSrc))              // Which source operand ?
4771     return false;
4772
4773   isLeft = false;
4774   ShAmt = NumZeros;
4775   ShVal = SVOp->getOperand(OpSrc);
4776   return true;
4777 }
4778
4779 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4780 /// logical left shift of a vector.
4781 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4782                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4783   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4784   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4785               true /* check zeros from left */, DAG);
4786   unsigned OpSrc;
4787
4788   if (!NumZeros)
4789     return false;
4790
4791   // Considering the elements in the mask that are not consecutive zeros,
4792   // check if they consecutively come from only one of the source vectors.
4793   //
4794   //                           0    { A, B, X, X } = V2
4795   //                          / \    /  /
4796   //   vector_shuffle V1, V2 <X, X, 4, 5>
4797   //
4798   if (!isShuffleMaskConsecutive(SVOp,
4799             NumZeros,     // Mask Start Index
4800             NumElems,     // Mask End Index(exclusive)
4801             0,            // Where to start looking in the src vector
4802             NumElems,     // Number of elements in vector
4803             OpSrc))       // Which source operand ?
4804     return false;
4805
4806   isLeft = true;
4807   ShAmt = NumZeros;
4808   ShVal = SVOp->getOperand(OpSrc);
4809   return true;
4810 }
4811
4812 /// isVectorShift - Returns true if the shuffle can be implemented as a
4813 /// logical left or right shift of a vector.
4814 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4815                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4816   // Although the logic below support any bitwidth size, there are no
4817   // shift instructions which handle more than 128-bit vectors.
4818   if (!SVOp->getValueType(0).is128BitVector())
4819     return false;
4820
4821   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4822       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4823     return true;
4824
4825   return false;
4826 }
4827
4828 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4829 ///
4830 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4831                                        unsigned NumNonZero, unsigned NumZero,
4832                                        SelectionDAG &DAG,
4833                                        const X86Subtarget* Subtarget,
4834                                        const TargetLowering &TLI) {
4835   if (NumNonZero > 8)
4836     return SDValue();
4837
4838   DebugLoc dl = Op.getDebugLoc();
4839   SDValue V(0, 0);
4840   bool First = true;
4841   for (unsigned i = 0; i < 16; ++i) {
4842     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4843     if (ThisIsNonZero && First) {
4844       if (NumZero)
4845         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4846       else
4847         V = DAG.getUNDEF(MVT::v8i16);
4848       First = false;
4849     }
4850
4851     if ((i & 1) != 0) {
4852       SDValue ThisElt(0, 0), LastElt(0, 0);
4853       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4854       if (LastIsNonZero) {
4855         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4856                               MVT::i16, Op.getOperand(i-1));
4857       }
4858       if (ThisIsNonZero) {
4859         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4860         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4861                               ThisElt, DAG.getConstant(8, MVT::i8));
4862         if (LastIsNonZero)
4863           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4864       } else
4865         ThisElt = LastElt;
4866
4867       if (ThisElt.getNode())
4868         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4869                         DAG.getIntPtrConstant(i/2));
4870     }
4871   }
4872
4873   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4874 }
4875
4876 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4877 ///
4878 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4879                                      unsigned NumNonZero, unsigned NumZero,
4880                                      SelectionDAG &DAG,
4881                                      const X86Subtarget* Subtarget,
4882                                      const TargetLowering &TLI) {
4883   if (NumNonZero > 4)
4884     return SDValue();
4885
4886   DebugLoc dl = Op.getDebugLoc();
4887   SDValue V(0, 0);
4888   bool First = true;
4889   for (unsigned i = 0; i < 8; ++i) {
4890     bool isNonZero = (NonZeros & (1 << i)) != 0;
4891     if (isNonZero) {
4892       if (First) {
4893         if (NumZero)
4894           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4895         else
4896           V = DAG.getUNDEF(MVT::v8i16);
4897         First = false;
4898       }
4899       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4900                       MVT::v8i16, V, Op.getOperand(i),
4901                       DAG.getIntPtrConstant(i));
4902     }
4903   }
4904
4905   return V;
4906 }
4907
4908 /// getVShift - Return a vector logical shift node.
4909 ///
4910 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4911                          unsigned NumBits, SelectionDAG &DAG,
4912                          const TargetLowering &TLI, DebugLoc dl) {
4913   assert(VT.is128BitVector() && "Unknown type for VShift");
4914   EVT ShVT = MVT::v2i64;
4915   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4916   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4917   return DAG.getNode(ISD::BITCAST, dl, VT,
4918                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4919                              DAG.getConstant(NumBits,
4920                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4921 }
4922
4923 SDValue
4924 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4925                                           SelectionDAG &DAG) const {
4926
4927   // Check if the scalar load can be widened into a vector load. And if
4928   // the address is "base + cst" see if the cst can be "absorbed" into
4929   // the shuffle mask.
4930   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4931     SDValue Ptr = LD->getBasePtr();
4932     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4933       return SDValue();
4934     EVT PVT = LD->getValueType(0);
4935     if (PVT != MVT::i32 && PVT != MVT::f32)
4936       return SDValue();
4937
4938     int FI = -1;
4939     int64_t Offset = 0;
4940     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4941       FI = FINode->getIndex();
4942       Offset = 0;
4943     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4944                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4945       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4946       Offset = Ptr.getConstantOperandVal(1);
4947       Ptr = Ptr.getOperand(0);
4948     } else {
4949       return SDValue();
4950     }
4951
4952     // FIXME: 256-bit vector instructions don't require a strict alignment,
4953     // improve this code to support it better.
4954     unsigned RequiredAlign = VT.getSizeInBits()/8;
4955     SDValue Chain = LD->getChain();
4956     // Make sure the stack object alignment is at least 16 or 32.
4957     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4958     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4959       if (MFI->isFixedObjectIndex(FI)) {
4960         // Can't change the alignment. FIXME: It's possible to compute
4961         // the exact stack offset and reference FI + adjust offset instead.
4962         // If someone *really* cares about this. That's the way to implement it.
4963         return SDValue();
4964       } else {
4965         MFI->setObjectAlignment(FI, RequiredAlign);
4966       }
4967     }
4968
4969     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4970     // Ptr + (Offset & ~15).
4971     if (Offset < 0)
4972       return SDValue();
4973     if ((Offset % RequiredAlign) & 3)
4974       return SDValue();
4975     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4976     if (StartOffset)
4977       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4978                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4979
4980     int EltNo = (Offset - StartOffset) >> 2;
4981     unsigned NumElems = VT.getVectorNumElements();
4982
4983     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4984     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4985                              LD->getPointerInfo().getWithOffset(StartOffset),
4986                              false, false, false, 0);
4987
4988     SmallVector<int, 8> Mask;
4989     for (unsigned i = 0; i != NumElems; ++i)
4990       Mask.push_back(EltNo);
4991
4992     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4993   }
4994
4995   return SDValue();
4996 }
4997
4998 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4999 /// vector of type 'VT', see if the elements can be replaced by a single large
5000 /// load which has the same value as a build_vector whose operands are 'elts'.
5001 ///
5002 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5003 ///
5004 /// FIXME: we'd also like to handle the case where the last elements are zero
5005 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5006 /// There's even a handy isZeroNode for that purpose.
5007 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5008                                         DebugLoc &DL, SelectionDAG &DAG) {
5009   EVT EltVT = VT.getVectorElementType();
5010   unsigned NumElems = Elts.size();
5011
5012   LoadSDNode *LDBase = NULL;
5013   unsigned LastLoadedElt = -1U;
5014
5015   // For each element in the initializer, see if we've found a load or an undef.
5016   // If we don't find an initial load element, or later load elements are
5017   // non-consecutive, bail out.
5018   for (unsigned i = 0; i < NumElems; ++i) {
5019     SDValue Elt = Elts[i];
5020
5021     if (!Elt.getNode() ||
5022         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5023       return SDValue();
5024     if (!LDBase) {
5025       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5026         return SDValue();
5027       LDBase = cast<LoadSDNode>(Elt.getNode());
5028       LastLoadedElt = i;
5029       continue;
5030     }
5031     if (Elt.getOpcode() == ISD::UNDEF)
5032       continue;
5033
5034     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5035     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5036       return SDValue();
5037     LastLoadedElt = i;
5038   }
5039
5040   // If we have found an entire vector of loads and undefs, then return a large
5041   // load of the entire vector width starting at the base pointer.  If we found
5042   // consecutive loads for the low half, generate a vzext_load node.
5043   if (LastLoadedElt == NumElems - 1) {
5044     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5045       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5046                          LDBase->getPointerInfo(),
5047                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5048                          LDBase->isInvariant(), 0);
5049     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5050                        LDBase->getPointerInfo(),
5051                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5052                        LDBase->isInvariant(), LDBase->getAlignment());
5053   }
5054   if (NumElems == 4 && LastLoadedElt == 1 &&
5055       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5056     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5057     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5058     SDValue ResNode =
5059         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5060                                 LDBase->getPointerInfo(),
5061                                 LDBase->getAlignment(),
5062                                 false/*isVolatile*/, true/*ReadMem*/,
5063                                 false/*WriteMem*/);
5064
5065     // Make sure the newly-created LOAD is in the same position as LDBase in
5066     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5067     // update uses of LDBase's output chain to use the TokenFactor.
5068     if (LDBase->hasAnyUseOfValue(1)) {
5069       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5070                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5071       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5072       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5073                              SDValue(ResNode.getNode(), 1));
5074     }
5075
5076     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5077   }
5078   return SDValue();
5079 }
5080
5081 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5082 /// to generate a splat value for the following cases:
5083 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5084 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5085 /// a scalar load, or a constant.
5086 /// The VBROADCAST node is returned when a pattern is found,
5087 /// or SDValue() otherwise.
5088 SDValue
5089 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5090   if (!Subtarget->hasFp256())
5091     return SDValue();
5092
5093   EVT VT = Op.getValueType();
5094   DebugLoc dl = Op.getDebugLoc();
5095
5096   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5097          "Unsupported vector type for broadcast.");
5098
5099   SDValue Ld;
5100   bool ConstSplatVal;
5101
5102   switch (Op.getOpcode()) {
5103     default:
5104       // Unknown pattern found.
5105       return SDValue();
5106
5107     case ISD::BUILD_VECTOR: {
5108       // The BUILD_VECTOR node must be a splat.
5109       if (!isSplatVector(Op.getNode()))
5110         return SDValue();
5111
5112       Ld = Op.getOperand(0);
5113       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5114                      Ld.getOpcode() == ISD::ConstantFP);
5115
5116       // The suspected load node has several users. Make sure that all
5117       // of its users are from the BUILD_VECTOR node.
5118       // Constants may have multiple users.
5119       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5120         return SDValue();
5121       break;
5122     }
5123
5124     case ISD::VECTOR_SHUFFLE: {
5125       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5126
5127       // Shuffles must have a splat mask where the first element is
5128       // broadcasted.
5129       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5130         return SDValue();
5131
5132       SDValue Sc = Op.getOperand(0);
5133       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5134           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5135
5136         if (!Subtarget->hasInt256())
5137           return SDValue();
5138
5139         // Use the register form of the broadcast instruction available on AVX2.
5140         if (VT.is256BitVector())
5141           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5142         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5143       }
5144
5145       Ld = Sc.getOperand(0);
5146       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5147                        Ld.getOpcode() == ISD::ConstantFP);
5148
5149       // The scalar_to_vector node and the suspected
5150       // load node must have exactly one user.
5151       // Constants may have multiple users.
5152       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5153         return SDValue();
5154       break;
5155     }
5156   }
5157
5158   bool Is256 = VT.is256BitVector();
5159
5160   // Handle the broadcasting a single constant scalar from the constant pool
5161   // into a vector. On Sandybridge it is still better to load a constant vector
5162   // from the constant pool and not to broadcast it from a scalar.
5163   if (ConstSplatVal && Subtarget->hasInt256()) {
5164     EVT CVT = Ld.getValueType();
5165     assert(!CVT.isVector() && "Must not broadcast a vector type");
5166     unsigned ScalarSize = CVT.getSizeInBits();
5167
5168     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5169       const Constant *C = 0;
5170       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5171         C = CI->getConstantIntValue();
5172       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5173         C = CF->getConstantFPValue();
5174
5175       assert(C && "Invalid constant type");
5176
5177       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5178       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5179       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5180                        MachinePointerInfo::getConstantPool(),
5181                        false, false, false, Alignment);
5182
5183       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5184     }
5185   }
5186
5187   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5188   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5189
5190   // Handle AVX2 in-register broadcasts.
5191   if (!IsLoad && Subtarget->hasInt256() &&
5192       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5193     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5194
5195   // The scalar source must be a normal load.
5196   if (!IsLoad)
5197     return SDValue();
5198
5199   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5200     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5201
5202   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5203   // double since there is no vbroadcastsd xmm
5204   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5205     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5206       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5207   }
5208
5209   // Unsupported broadcast.
5210   return SDValue();
5211 }
5212
5213 SDValue
5214 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5215   EVT VT = Op.getValueType();
5216
5217   // Skip if insert_vec_elt is not supported.
5218   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5219     return SDValue();
5220
5221   DebugLoc DL = Op.getDebugLoc();
5222   unsigned NumElems = Op.getNumOperands();
5223
5224   SDValue VecIn1;
5225   SDValue VecIn2;
5226   SmallVector<unsigned, 4> InsertIndices;
5227   SmallVector<int, 8> Mask(NumElems, -1);
5228
5229   for (unsigned i = 0; i != NumElems; ++i) {
5230     unsigned Opc = Op.getOperand(i).getOpcode();
5231
5232     if (Opc == ISD::UNDEF)
5233       continue;
5234
5235     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5236       // Quit if more than 1 elements need inserting.
5237       if (InsertIndices.size() > 1)
5238         return SDValue();
5239
5240       InsertIndices.push_back(i);
5241       continue;
5242     }
5243
5244     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5245     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5246
5247     // Quit if extracted from vector of different type.
5248     if (ExtractedFromVec.getValueType() != VT)
5249       return SDValue();
5250
5251     // Quit if non-constant index.
5252     if (!isa<ConstantSDNode>(ExtIdx))
5253       return SDValue();
5254
5255     if (VecIn1.getNode() == 0)
5256       VecIn1 = ExtractedFromVec;
5257     else if (VecIn1 != ExtractedFromVec) {
5258       if (VecIn2.getNode() == 0)
5259         VecIn2 = ExtractedFromVec;
5260       else if (VecIn2 != ExtractedFromVec)
5261         // Quit if more than 2 vectors to shuffle
5262         return SDValue();
5263     }
5264
5265     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5266
5267     if (ExtractedFromVec == VecIn1)
5268       Mask[i] = Idx;
5269     else if (ExtractedFromVec == VecIn2)
5270       Mask[i] = Idx + NumElems;
5271   }
5272
5273   if (VecIn1.getNode() == 0)
5274     return SDValue();
5275
5276   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5277   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5278   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5279     unsigned Idx = InsertIndices[i];
5280     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5281                      DAG.getIntPtrConstant(Idx));
5282   }
5283
5284   return NV;
5285 }
5286
5287 SDValue
5288 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5289   DebugLoc dl = Op.getDebugLoc();
5290
5291   EVT VT = Op.getValueType();
5292   EVT ExtVT = VT.getVectorElementType();
5293   unsigned NumElems = Op.getNumOperands();
5294
5295   // Vectors containing all zeros can be matched by pxor and xorps later
5296   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5297     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5298     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5299     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5300       return Op;
5301
5302     return getZeroVector(VT, Subtarget, DAG, dl);
5303   }
5304
5305   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5306   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5307   // vpcmpeqd on 256-bit vectors.
5308   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5309     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5310       return Op;
5311
5312     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5313   }
5314
5315   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5316   if (Broadcast.getNode())
5317     return Broadcast;
5318
5319   unsigned EVTBits = ExtVT.getSizeInBits();
5320
5321   unsigned NumZero  = 0;
5322   unsigned NumNonZero = 0;
5323   unsigned NonZeros = 0;
5324   bool IsAllConstants = true;
5325   SmallSet<SDValue, 8> Values;
5326   for (unsigned i = 0; i < NumElems; ++i) {
5327     SDValue Elt = Op.getOperand(i);
5328     if (Elt.getOpcode() == ISD::UNDEF)
5329       continue;
5330     Values.insert(Elt);
5331     if (Elt.getOpcode() != ISD::Constant &&
5332         Elt.getOpcode() != ISD::ConstantFP)
5333       IsAllConstants = false;
5334     if (X86::isZeroNode(Elt))
5335       NumZero++;
5336     else {
5337       NonZeros |= (1 << i);
5338       NumNonZero++;
5339     }
5340   }
5341
5342   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5343   if (NumNonZero == 0)
5344     return DAG.getUNDEF(VT);
5345
5346   // Special case for single non-zero, non-undef, element.
5347   if (NumNonZero == 1) {
5348     unsigned Idx = CountTrailingZeros_32(NonZeros);
5349     SDValue Item = Op.getOperand(Idx);
5350
5351     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5352     // the value are obviously zero, truncate the value to i32 and do the
5353     // insertion that way.  Only do this if the value is non-constant or if the
5354     // value is a constant being inserted into element 0.  It is cheaper to do
5355     // a constant pool load than it is to do a movd + shuffle.
5356     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5357         (!IsAllConstants || Idx == 0)) {
5358       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5359         // Handle SSE only.
5360         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5361         EVT VecVT = MVT::v4i32;
5362         unsigned VecElts = 4;
5363
5364         // Truncate the value (which may itself be a constant) to i32, and
5365         // convert it to a vector with movd (S2V+shuffle to zero extend).
5366         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5367         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5368         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5369
5370         // Now we have our 32-bit value zero extended in the low element of
5371         // a vector.  If Idx != 0, swizzle it into place.
5372         if (Idx != 0) {
5373           SmallVector<int, 4> Mask;
5374           Mask.push_back(Idx);
5375           for (unsigned i = 1; i != VecElts; ++i)
5376             Mask.push_back(i);
5377           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5378                                       &Mask[0]);
5379         }
5380         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5381       }
5382     }
5383
5384     // If we have a constant or non-constant insertion into the low element of
5385     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5386     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5387     // depending on what the source datatype is.
5388     if (Idx == 0) {
5389       if (NumZero == 0)
5390         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5391
5392       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5393           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5394         if (VT.is256BitVector()) {
5395           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5396           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5397                              Item, DAG.getIntPtrConstant(0));
5398         }
5399         assert(VT.is128BitVector() && "Expected an SSE value type!");
5400         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5401         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5402         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5403       }
5404
5405       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5406         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5407         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5408         if (VT.is256BitVector()) {
5409           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5410           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5411         } else {
5412           assert(VT.is128BitVector() && "Expected an SSE value type!");
5413           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5414         }
5415         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5416       }
5417     }
5418
5419     // Is it a vector logical left shift?
5420     if (NumElems == 2 && Idx == 1 &&
5421         X86::isZeroNode(Op.getOperand(0)) &&
5422         !X86::isZeroNode(Op.getOperand(1))) {
5423       unsigned NumBits = VT.getSizeInBits();
5424       return getVShift(true, VT,
5425                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5426                                    VT, Op.getOperand(1)),
5427                        NumBits/2, DAG, *this, dl);
5428     }
5429
5430     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5431       return SDValue();
5432
5433     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5434     // is a non-constant being inserted into an element other than the low one,
5435     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5436     // movd/movss) to move this into the low element, then shuffle it into
5437     // place.
5438     if (EVTBits == 32) {
5439       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5440
5441       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5442       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5443       SmallVector<int, 8> MaskVec;
5444       for (unsigned i = 0; i != NumElems; ++i)
5445         MaskVec.push_back(i == Idx ? 0 : 1);
5446       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5447     }
5448   }
5449
5450   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5451   if (Values.size() == 1) {
5452     if (EVTBits == 32) {
5453       // Instead of a shuffle like this:
5454       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5455       // Check if it's possible to issue this instead.
5456       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5457       unsigned Idx = CountTrailingZeros_32(NonZeros);
5458       SDValue Item = Op.getOperand(Idx);
5459       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5460         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5461     }
5462     return SDValue();
5463   }
5464
5465   // A vector full of immediates; various special cases are already
5466   // handled, so this is best done with a single constant-pool load.
5467   if (IsAllConstants)
5468     return SDValue();
5469
5470   // For AVX-length vectors, build the individual 128-bit pieces and use
5471   // shuffles to put them in place.
5472   if (VT.is256BitVector()) {
5473     SmallVector<SDValue, 32> V;
5474     for (unsigned i = 0; i != NumElems; ++i)
5475       V.push_back(Op.getOperand(i));
5476
5477     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5478
5479     // Build both the lower and upper subvector.
5480     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5481     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5482                                 NumElems/2);
5483
5484     // Recreate the wider vector with the lower and upper part.
5485     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5486   }
5487
5488   // Let legalizer expand 2-wide build_vectors.
5489   if (EVTBits == 64) {
5490     if (NumNonZero == 1) {
5491       // One half is zero or undef.
5492       unsigned Idx = CountTrailingZeros_32(NonZeros);
5493       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5494                                  Op.getOperand(Idx));
5495       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5496     }
5497     return SDValue();
5498   }
5499
5500   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5501   if (EVTBits == 8 && NumElems == 16) {
5502     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5503                                         Subtarget, *this);
5504     if (V.getNode()) return V;
5505   }
5506
5507   if (EVTBits == 16 && NumElems == 8) {
5508     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5509                                       Subtarget, *this);
5510     if (V.getNode()) return V;
5511   }
5512
5513   // If element VT is == 32 bits, turn it into a number of shuffles.
5514   SmallVector<SDValue, 8> V(NumElems);
5515   if (NumElems == 4 && NumZero > 0) {
5516     for (unsigned i = 0; i < 4; ++i) {
5517       bool isZero = !(NonZeros & (1 << i));
5518       if (isZero)
5519         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5520       else
5521         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5522     }
5523
5524     for (unsigned i = 0; i < 2; ++i) {
5525       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5526         default: break;
5527         case 0:
5528           V[i] = V[i*2];  // Must be a zero vector.
5529           break;
5530         case 1:
5531           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5532           break;
5533         case 2:
5534           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5535           break;
5536         case 3:
5537           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5538           break;
5539       }
5540     }
5541
5542     bool Reverse1 = (NonZeros & 0x3) == 2;
5543     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5544     int MaskVec[] = {
5545       Reverse1 ? 1 : 0,
5546       Reverse1 ? 0 : 1,
5547       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5548       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5549     };
5550     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5551   }
5552
5553   if (Values.size() > 1 && VT.is128BitVector()) {
5554     // Check for a build vector of consecutive loads.
5555     for (unsigned i = 0; i < NumElems; ++i)
5556       V[i] = Op.getOperand(i);
5557
5558     // Check for elements which are consecutive loads.
5559     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5560     if (LD.getNode())
5561       return LD;
5562
5563     // Check for a build vector from mostly shuffle plus few inserting.
5564     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5565     if (Sh.getNode())
5566       return Sh;
5567
5568     // For SSE 4.1, use insertps to put the high elements into the low element.
5569     if (getSubtarget()->hasSSE41()) {
5570       SDValue Result;
5571       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5572         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5573       else
5574         Result = DAG.getUNDEF(VT);
5575
5576       for (unsigned i = 1; i < NumElems; ++i) {
5577         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5578         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5579                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5580       }
5581       return Result;
5582     }
5583
5584     // Otherwise, expand into a number of unpckl*, start by extending each of
5585     // our (non-undef) elements to the full vector width with the element in the
5586     // bottom slot of the vector (which generates no code for SSE).
5587     for (unsigned i = 0; i < NumElems; ++i) {
5588       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5589         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5590       else
5591         V[i] = DAG.getUNDEF(VT);
5592     }
5593
5594     // Next, we iteratively mix elements, e.g. for v4f32:
5595     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5596     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5597     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5598     unsigned EltStride = NumElems >> 1;
5599     while (EltStride != 0) {
5600       for (unsigned i = 0; i < EltStride; ++i) {
5601         // If V[i+EltStride] is undef and this is the first round of mixing,
5602         // then it is safe to just drop this shuffle: V[i] is already in the
5603         // right place, the one element (since it's the first round) being
5604         // inserted as undef can be dropped.  This isn't safe for successive
5605         // rounds because they will permute elements within both vectors.
5606         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5607             EltStride == NumElems/2)
5608           continue;
5609
5610         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5611       }
5612       EltStride >>= 1;
5613     }
5614     return V[0];
5615   }
5616   return SDValue();
5617 }
5618
5619 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5620 // to create 256-bit vectors from two other 128-bit ones.
5621 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5622   DebugLoc dl = Op.getDebugLoc();
5623   EVT ResVT = Op.getValueType();
5624
5625   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5626
5627   SDValue V1 = Op.getOperand(0);
5628   SDValue V2 = Op.getOperand(1);
5629   unsigned NumElems = ResVT.getVectorNumElements();
5630
5631   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5632 }
5633
5634 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5635   assert(Op.getNumOperands() == 2);
5636
5637   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5638   // from two other 128-bit ones.
5639   return LowerAVXCONCAT_VECTORS(Op, DAG);
5640 }
5641
5642 // Try to lower a shuffle node into a simple blend instruction.
5643 static SDValue
5644 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5645                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5646   SDValue V1 = SVOp->getOperand(0);
5647   SDValue V2 = SVOp->getOperand(1);
5648   DebugLoc dl = SVOp->getDebugLoc();
5649   EVT VT = SVOp->getValueType(0);
5650   EVT EltVT = VT.getVectorElementType();
5651   unsigned NumElems = VT.getVectorNumElements();
5652
5653   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5654     return SDValue();
5655   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5656     return SDValue();
5657
5658   // Check the mask for BLEND and build the value.
5659   unsigned MaskValue = 0;
5660   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5661   unsigned NumLanes = (NumElems-1)/8 + 1; 
5662   unsigned NumElemsInLane = NumElems / NumLanes;
5663
5664   // Blend for v16i16 should be symetric for the both lanes.
5665   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5666
5667     int SndLaneEltIdx = (NumLanes == 2) ? 
5668       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5669     int EltIdx = SVOp->getMaskElt(i);
5670
5671     if ((EltIdx == -1 || EltIdx == (int)i) && 
5672         (SndLaneEltIdx == -1 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5673       continue;
5674
5675     if (((unsigned)EltIdx == (i + NumElems)) && 
5676         (SndLaneEltIdx == -1 || 
5677          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5678       MaskValue |= (1<<i);
5679     else 
5680       return SDValue();
5681   }
5682
5683   // Convert i32 vectors to floating point if it is not AVX2.
5684   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5685   EVT BlendVT = VT;
5686   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5687     BlendVT = EVT::getVectorVT(*DAG.getContext(), 
5688                               EVT::getFloatingPointVT(EltVT.getSizeInBits()), 
5689                               NumElems);
5690     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5691     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5692   }
5693   
5694   SDValue Ret =  DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5695                              DAG.getConstant(MaskValue, MVT::i32));
5696   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5697 }
5698
5699 // v8i16 shuffles - Prefer shuffles in the following order:
5700 // 1. [all]   pshuflw, pshufhw, optional move
5701 // 2. [ssse3] 1 x pshufb
5702 // 3. [ssse3] 2 x pshufb + 1 x por
5703 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5704 static SDValue
5705 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5706                          SelectionDAG &DAG) {
5707   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5708   SDValue V1 = SVOp->getOperand(0);
5709   SDValue V2 = SVOp->getOperand(1);
5710   DebugLoc dl = SVOp->getDebugLoc();
5711   SmallVector<int, 8> MaskVals;
5712
5713   // Determine if more than 1 of the words in each of the low and high quadwords
5714   // of the result come from the same quadword of one of the two inputs.  Undef
5715   // mask values count as coming from any quadword, for better codegen.
5716   unsigned LoQuad[] = { 0, 0, 0, 0 };
5717   unsigned HiQuad[] = { 0, 0, 0, 0 };
5718   std::bitset<4> InputQuads;
5719   for (unsigned i = 0; i < 8; ++i) {
5720     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5721     int EltIdx = SVOp->getMaskElt(i);
5722     MaskVals.push_back(EltIdx);
5723     if (EltIdx < 0) {
5724       ++Quad[0];
5725       ++Quad[1];
5726       ++Quad[2];
5727       ++Quad[3];
5728       continue;
5729     }
5730     ++Quad[EltIdx / 4];
5731     InputQuads.set(EltIdx / 4);
5732   }
5733
5734   int BestLoQuad = -1;
5735   unsigned MaxQuad = 1;
5736   for (unsigned i = 0; i < 4; ++i) {
5737     if (LoQuad[i] > MaxQuad) {
5738       BestLoQuad = i;
5739       MaxQuad = LoQuad[i];
5740     }
5741   }
5742
5743   int BestHiQuad = -1;
5744   MaxQuad = 1;
5745   for (unsigned i = 0; i < 4; ++i) {
5746     if (HiQuad[i] > MaxQuad) {
5747       BestHiQuad = i;
5748       MaxQuad = HiQuad[i];
5749     }
5750   }
5751
5752   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5753   // of the two input vectors, shuffle them into one input vector so only a
5754   // single pshufb instruction is necessary. If There are more than 2 input
5755   // quads, disable the next transformation since it does not help SSSE3.
5756   bool V1Used = InputQuads[0] || InputQuads[1];
5757   bool V2Used = InputQuads[2] || InputQuads[3];
5758   if (Subtarget->hasSSSE3()) {
5759     if (InputQuads.count() == 2 && V1Used && V2Used) {
5760       BestLoQuad = InputQuads[0] ? 0 : 1;
5761       BestHiQuad = InputQuads[2] ? 2 : 3;
5762     }
5763     if (InputQuads.count() > 2) {
5764       BestLoQuad = -1;
5765       BestHiQuad = -1;
5766     }
5767   }
5768
5769   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5770   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5771   // words from all 4 input quadwords.
5772   SDValue NewV;
5773   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5774     int MaskV[] = {
5775       BestLoQuad < 0 ? 0 : BestLoQuad,
5776       BestHiQuad < 0 ? 1 : BestHiQuad
5777     };
5778     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5779                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5780                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5781     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5782
5783     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5784     // source words for the shuffle, to aid later transformations.
5785     bool AllWordsInNewV = true;
5786     bool InOrder[2] = { true, true };
5787     for (unsigned i = 0; i != 8; ++i) {
5788       int idx = MaskVals[i];
5789       if (idx != (int)i)
5790         InOrder[i/4] = false;
5791       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5792         continue;
5793       AllWordsInNewV = false;
5794       break;
5795     }
5796
5797     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5798     if (AllWordsInNewV) {
5799       for (int i = 0; i != 8; ++i) {
5800         int idx = MaskVals[i];
5801         if (idx < 0)
5802           continue;
5803         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5804         if ((idx != i) && idx < 4)
5805           pshufhw = false;
5806         if ((idx != i) && idx > 3)
5807           pshuflw = false;
5808       }
5809       V1 = NewV;
5810       V2Used = false;
5811       BestLoQuad = 0;
5812       BestHiQuad = 1;
5813     }
5814
5815     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5816     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5817     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5818       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5819       unsigned TargetMask = 0;
5820       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5821                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5822       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5823       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5824                              getShufflePSHUFLWImmediate(SVOp);
5825       V1 = NewV.getOperand(0);
5826       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5827     }
5828   }
5829
5830   // If we have SSSE3, and all words of the result are from 1 input vector,
5831   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5832   // is present, fall back to case 4.
5833   if (Subtarget->hasSSSE3()) {
5834     SmallVector<SDValue,16> pshufbMask;
5835
5836     // If we have elements from both input vectors, set the high bit of the
5837     // shuffle mask element to zero out elements that come from V2 in the V1
5838     // mask, and elements that come from V1 in the V2 mask, so that the two
5839     // results can be OR'd together.
5840     bool TwoInputs = V1Used && V2Used;
5841     for (unsigned i = 0; i != 8; ++i) {
5842       int EltIdx = MaskVals[i] * 2;
5843       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5844       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5845       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5846       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5847     }
5848     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5849     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5850                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5851                                  MVT::v16i8, &pshufbMask[0], 16));
5852     if (!TwoInputs)
5853       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5854
5855     // Calculate the shuffle mask for the second input, shuffle it, and
5856     // OR it with the first shuffled input.
5857     pshufbMask.clear();
5858     for (unsigned i = 0; i != 8; ++i) {
5859       int EltIdx = MaskVals[i] * 2;
5860       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5861       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5862       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5863       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5864     }
5865     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5866     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5867                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5868                                  MVT::v16i8, &pshufbMask[0], 16));
5869     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5870     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5871   }
5872
5873   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5874   // and update MaskVals with new element order.
5875   std::bitset<8> InOrder;
5876   if (BestLoQuad >= 0) {
5877     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5878     for (int i = 0; i != 4; ++i) {
5879       int idx = MaskVals[i];
5880       if (idx < 0) {
5881         InOrder.set(i);
5882       } else if ((idx / 4) == BestLoQuad) {
5883         MaskV[i] = idx & 3;
5884         InOrder.set(i);
5885       }
5886     }
5887     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5888                                 &MaskV[0]);
5889
5890     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5891       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5892       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5893                                   NewV.getOperand(0),
5894                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5895     }
5896   }
5897
5898   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5899   // and update MaskVals with the new element order.
5900   if (BestHiQuad >= 0) {
5901     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5902     for (unsigned i = 4; i != 8; ++i) {
5903       int idx = MaskVals[i];
5904       if (idx < 0) {
5905         InOrder.set(i);
5906       } else if ((idx / 4) == BestHiQuad) {
5907         MaskV[i] = (idx & 3) + 4;
5908         InOrder.set(i);
5909       }
5910     }
5911     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5912                                 &MaskV[0]);
5913
5914     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5915       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5916       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5917                                   NewV.getOperand(0),
5918                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5919     }
5920   }
5921
5922   // In case BestHi & BestLo were both -1, which means each quadword has a word
5923   // from each of the four input quadwords, calculate the InOrder bitvector now
5924   // before falling through to the insert/extract cleanup.
5925   if (BestLoQuad == -1 && BestHiQuad == -1) {
5926     NewV = V1;
5927     for (int i = 0; i != 8; ++i)
5928       if (MaskVals[i] < 0 || MaskVals[i] == i)
5929         InOrder.set(i);
5930   }
5931
5932   // The other elements are put in the right place using pextrw and pinsrw.
5933   for (unsigned i = 0; i != 8; ++i) {
5934     if (InOrder[i])
5935       continue;
5936     int EltIdx = MaskVals[i];
5937     if (EltIdx < 0)
5938       continue;
5939     SDValue ExtOp = (EltIdx < 8) ?
5940       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5941                   DAG.getIntPtrConstant(EltIdx)) :
5942       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5943                   DAG.getIntPtrConstant(EltIdx - 8));
5944     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5945                        DAG.getIntPtrConstant(i));
5946   }
5947   return NewV;
5948 }
5949
5950 // v16i8 shuffles - Prefer shuffles in the following order:
5951 // 1. [ssse3] 1 x pshufb
5952 // 2. [ssse3] 2 x pshufb + 1 x por
5953 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5954 static
5955 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5956                                  SelectionDAG &DAG,
5957                                  const X86TargetLowering &TLI) {
5958   SDValue V1 = SVOp->getOperand(0);
5959   SDValue V2 = SVOp->getOperand(1);
5960   DebugLoc dl = SVOp->getDebugLoc();
5961   ArrayRef<int> MaskVals = SVOp->getMask();
5962
5963   // If we have SSSE3, case 1 is generated when all result bytes come from
5964   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5965   // present, fall back to case 3.
5966
5967   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5968   if (TLI.getSubtarget()->hasSSSE3()) {
5969     SmallVector<SDValue,16> pshufbMask;
5970
5971     // If all result elements are from one input vector, then only translate
5972     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5973     //
5974     // Otherwise, we have elements from both input vectors, and must zero out
5975     // elements that come from V2 in the first mask, and V1 in the second mask
5976     // so that we can OR them together.
5977     for (unsigned i = 0; i != 16; ++i) {
5978       int EltIdx = MaskVals[i];
5979       if (EltIdx < 0 || EltIdx >= 16)
5980         EltIdx = 0x80;
5981       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5982     }
5983     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5984                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5985                                  MVT::v16i8, &pshufbMask[0], 16));
5986
5987     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5988     // the 2nd operand if it's undefined or zero.
5989     if (V2.getOpcode() == ISD::UNDEF ||
5990         ISD::isBuildVectorAllZeros(V2.getNode()))
5991       return V1;
5992
5993     // Calculate the shuffle mask for the second input, shuffle it, and
5994     // OR it with the first shuffled input.
5995     pshufbMask.clear();
5996     for (unsigned i = 0; i != 16; ++i) {
5997       int EltIdx = MaskVals[i];
5998       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5999       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6000     }
6001     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6002                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6003                                  MVT::v16i8, &pshufbMask[0], 16));
6004     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6005   }
6006
6007   // No SSSE3 - Calculate in place words and then fix all out of place words
6008   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6009   // the 16 different words that comprise the two doublequadword input vectors.
6010   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6011   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6012   SDValue NewV = V1;
6013   for (int i = 0; i != 8; ++i) {
6014     int Elt0 = MaskVals[i*2];
6015     int Elt1 = MaskVals[i*2+1];
6016
6017     // This word of the result is all undef, skip it.
6018     if (Elt0 < 0 && Elt1 < 0)
6019       continue;
6020
6021     // This word of the result is already in the correct place, skip it.
6022     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6023       continue;
6024
6025     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6026     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6027     SDValue InsElt;
6028
6029     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6030     // using a single extract together, load it and store it.
6031     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6032       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6033                            DAG.getIntPtrConstant(Elt1 / 2));
6034       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6035                         DAG.getIntPtrConstant(i));
6036       continue;
6037     }
6038
6039     // If Elt1 is defined, extract it from the appropriate source.  If the
6040     // source byte is not also odd, shift the extracted word left 8 bits
6041     // otherwise clear the bottom 8 bits if we need to do an or.
6042     if (Elt1 >= 0) {
6043       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6044                            DAG.getIntPtrConstant(Elt1 / 2));
6045       if ((Elt1 & 1) == 0)
6046         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6047                              DAG.getConstant(8,
6048                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6049       else if (Elt0 >= 0)
6050         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6051                              DAG.getConstant(0xFF00, MVT::i16));
6052     }
6053     // If Elt0 is defined, extract it from the appropriate source.  If the
6054     // source byte is not also even, shift the extracted word right 8 bits. If
6055     // Elt1 was also defined, OR the extracted values together before
6056     // inserting them in the result.
6057     if (Elt0 >= 0) {
6058       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6059                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6060       if ((Elt0 & 1) != 0)
6061         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6062                               DAG.getConstant(8,
6063                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6064       else if (Elt1 >= 0)
6065         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6066                              DAG.getConstant(0x00FF, MVT::i16));
6067       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6068                          : InsElt0;
6069     }
6070     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6071                        DAG.getIntPtrConstant(i));
6072   }
6073   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6074 }
6075
6076 // v32i8 shuffles - Translate to VPSHUFB if possible.
6077 static
6078 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6079                                  const X86Subtarget *Subtarget,
6080                                  SelectionDAG &DAG) {
6081   EVT VT = SVOp->getValueType(0);
6082   SDValue V1 = SVOp->getOperand(0);
6083   SDValue V2 = SVOp->getOperand(1);
6084   DebugLoc dl = SVOp->getDebugLoc();
6085   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6086
6087   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6088   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6089   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6090
6091   // VPSHUFB may be generated if
6092   // (1) one of input vector is undefined or zeroinitializer.
6093   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6094   // And (2) the mask indexes don't cross the 128-bit lane.
6095   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6096       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6097     return SDValue();
6098
6099   if (V1IsAllZero && !V2IsAllZero) {
6100     CommuteVectorShuffleMask(MaskVals, 32);
6101     V1 = V2;
6102   }
6103   SmallVector<SDValue, 32> pshufbMask;
6104   for (unsigned i = 0; i != 32; i++) {
6105     int EltIdx = MaskVals[i];
6106     if (EltIdx < 0 || EltIdx >= 32)
6107       EltIdx = 0x80;
6108     else {
6109       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6110         // Cross lane is not allowed.
6111         return SDValue();
6112       EltIdx &= 0xf;
6113     }
6114     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6115   }
6116   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6117                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6118                                   MVT::v32i8, &pshufbMask[0], 32));
6119 }
6120
6121 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6122 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6123 /// done when every pair / quad of shuffle mask elements point to elements in
6124 /// the right sequence. e.g.
6125 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6126 static
6127 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6128                                  SelectionDAG &DAG, DebugLoc dl) {
6129   MVT VT = SVOp->getValueType(0).getSimpleVT();
6130   unsigned NumElems = VT.getVectorNumElements();
6131   MVT NewVT;
6132   unsigned Scale;
6133   switch (VT.SimpleTy) {
6134   default: llvm_unreachable("Unexpected!");
6135   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6136   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6137   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6138   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6139   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6140   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6141   }
6142
6143   SmallVector<int, 8> MaskVec;
6144   for (unsigned i = 0; i != NumElems; i += Scale) {
6145     int StartIdx = -1;
6146     for (unsigned j = 0; j != Scale; ++j) {
6147       int EltIdx = SVOp->getMaskElt(i+j);
6148       if (EltIdx < 0)
6149         continue;
6150       if (StartIdx < 0)
6151         StartIdx = (EltIdx / Scale);
6152       if (EltIdx != (int)(StartIdx*Scale + j))
6153         return SDValue();
6154     }
6155     MaskVec.push_back(StartIdx);
6156   }
6157
6158   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6159   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6160   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6161 }
6162
6163 /// getVZextMovL - Return a zero-extending vector move low node.
6164 ///
6165 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6166                             SDValue SrcOp, SelectionDAG &DAG,
6167                             const X86Subtarget *Subtarget, DebugLoc dl) {
6168   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6169     LoadSDNode *LD = NULL;
6170     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6171       LD = dyn_cast<LoadSDNode>(SrcOp);
6172     if (!LD) {
6173       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6174       // instead.
6175       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6176       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6177           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6178           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6179           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6180         // PR2108
6181         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6182         return DAG.getNode(ISD::BITCAST, dl, VT,
6183                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6184                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6185                                                    OpVT,
6186                                                    SrcOp.getOperand(0)
6187                                                           .getOperand(0))));
6188       }
6189     }
6190   }
6191
6192   return DAG.getNode(ISD::BITCAST, dl, VT,
6193                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6194                                  DAG.getNode(ISD::BITCAST, dl,
6195                                              OpVT, SrcOp)));
6196 }
6197
6198 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6199 /// which could not be matched by any known target speficic shuffle
6200 static SDValue
6201 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6202
6203   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6204   if (NewOp.getNode())
6205     return NewOp;
6206
6207   EVT VT = SVOp->getValueType(0);
6208
6209   unsigned NumElems = VT.getVectorNumElements();
6210   unsigned NumLaneElems = NumElems / 2;
6211
6212   DebugLoc dl = SVOp->getDebugLoc();
6213   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6214   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6215   SDValue Output[2];
6216
6217   SmallVector<int, 16> Mask;
6218   for (unsigned l = 0; l < 2; ++l) {
6219     // Build a shuffle mask for the output, discovering on the fly which
6220     // input vectors to use as shuffle operands (recorded in InputUsed).
6221     // If building a suitable shuffle vector proves too hard, then bail
6222     // out with UseBuildVector set.
6223     bool UseBuildVector = false;
6224     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6225     unsigned LaneStart = l * NumLaneElems;
6226     for (unsigned i = 0; i != NumLaneElems; ++i) {
6227       // The mask element.  This indexes into the input.
6228       int Idx = SVOp->getMaskElt(i+LaneStart);
6229       if (Idx < 0) {
6230         // the mask element does not index into any input vector.
6231         Mask.push_back(-1);
6232         continue;
6233       }
6234
6235       // The input vector this mask element indexes into.
6236       int Input = Idx / NumLaneElems;
6237
6238       // Turn the index into an offset from the start of the input vector.
6239       Idx -= Input * NumLaneElems;
6240
6241       // Find or create a shuffle vector operand to hold this input.
6242       unsigned OpNo;
6243       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6244         if (InputUsed[OpNo] == Input)
6245           // This input vector is already an operand.
6246           break;
6247         if (InputUsed[OpNo] < 0) {
6248           // Create a new operand for this input vector.
6249           InputUsed[OpNo] = Input;
6250           break;
6251         }
6252       }
6253
6254       if (OpNo >= array_lengthof(InputUsed)) {
6255         // More than two input vectors used!  Give up on trying to create a
6256         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6257         UseBuildVector = true;
6258         break;
6259       }
6260
6261       // Add the mask index for the new shuffle vector.
6262       Mask.push_back(Idx + OpNo * NumLaneElems);
6263     }
6264
6265     if (UseBuildVector) {
6266       SmallVector<SDValue, 16> SVOps;
6267       for (unsigned i = 0; i != NumLaneElems; ++i) {
6268         // The mask element.  This indexes into the input.
6269         int Idx = SVOp->getMaskElt(i+LaneStart);
6270         if (Idx < 0) {
6271           SVOps.push_back(DAG.getUNDEF(EltVT));
6272           continue;
6273         }
6274
6275         // The input vector this mask element indexes into.
6276         int Input = Idx / NumElems;
6277
6278         // Turn the index into an offset from the start of the input vector.
6279         Idx -= Input * NumElems;
6280
6281         // Extract the vector element by hand.
6282         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6283                                     SVOp->getOperand(Input),
6284                                     DAG.getIntPtrConstant(Idx)));
6285       }
6286
6287       // Construct the output using a BUILD_VECTOR.
6288       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6289                               SVOps.size());
6290     } else if (InputUsed[0] < 0) {
6291       // No input vectors were used! The result is undefined.
6292       Output[l] = DAG.getUNDEF(NVT);
6293     } else {
6294       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6295                                         (InputUsed[0] % 2) * NumLaneElems,
6296                                         DAG, dl);
6297       // If only one input was used, use an undefined vector for the other.
6298       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6299         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6300                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6301       // At least one input vector was used. Create a new shuffle vector.
6302       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6303     }
6304
6305     Mask.clear();
6306   }
6307
6308   // Concatenate the result back
6309   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6310 }
6311
6312 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6313 /// 4 elements, and match them with several different shuffle types.
6314 static SDValue
6315 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6316   SDValue V1 = SVOp->getOperand(0);
6317   SDValue V2 = SVOp->getOperand(1);
6318   DebugLoc dl = SVOp->getDebugLoc();
6319   EVT VT = SVOp->getValueType(0);
6320
6321   assert(VT.is128BitVector() && "Unsupported vector size");
6322
6323   std::pair<int, int> Locs[4];
6324   int Mask1[] = { -1, -1, -1, -1 };
6325   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6326
6327   unsigned NumHi = 0;
6328   unsigned NumLo = 0;
6329   for (unsigned i = 0; i != 4; ++i) {
6330     int Idx = PermMask[i];
6331     if (Idx < 0) {
6332       Locs[i] = std::make_pair(-1, -1);
6333     } else {
6334       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6335       if (Idx < 4) {
6336         Locs[i] = std::make_pair(0, NumLo);
6337         Mask1[NumLo] = Idx;
6338         NumLo++;
6339       } else {
6340         Locs[i] = std::make_pair(1, NumHi);
6341         if (2+NumHi < 4)
6342           Mask1[2+NumHi] = Idx;
6343         NumHi++;
6344       }
6345     }
6346   }
6347
6348   if (NumLo <= 2 && NumHi <= 2) {
6349     // If no more than two elements come from either vector. This can be
6350     // implemented with two shuffles. First shuffle gather the elements.
6351     // The second shuffle, which takes the first shuffle as both of its
6352     // vector operands, put the elements into the right order.
6353     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6354
6355     int Mask2[] = { -1, -1, -1, -1 };
6356
6357     for (unsigned i = 0; i != 4; ++i)
6358       if (Locs[i].first != -1) {
6359         unsigned Idx = (i < 2) ? 0 : 4;
6360         Idx += Locs[i].first * 2 + Locs[i].second;
6361         Mask2[i] = Idx;
6362       }
6363
6364     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6365   }
6366
6367   if (NumLo == 3 || NumHi == 3) {
6368     // Otherwise, we must have three elements from one vector, call it X, and
6369     // one element from the other, call it Y.  First, use a shufps to build an
6370     // intermediate vector with the one element from Y and the element from X
6371     // that will be in the same half in the final destination (the indexes don't
6372     // matter). Then, use a shufps to build the final vector, taking the half
6373     // containing the element from Y from the intermediate, and the other half
6374     // from X.
6375     if (NumHi == 3) {
6376       // Normalize it so the 3 elements come from V1.
6377       CommuteVectorShuffleMask(PermMask, 4);
6378       std::swap(V1, V2);
6379     }
6380
6381     // Find the element from V2.
6382     unsigned HiIndex;
6383     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6384       int Val = PermMask[HiIndex];
6385       if (Val < 0)
6386         continue;
6387       if (Val >= 4)
6388         break;
6389     }
6390
6391     Mask1[0] = PermMask[HiIndex];
6392     Mask1[1] = -1;
6393     Mask1[2] = PermMask[HiIndex^1];
6394     Mask1[3] = -1;
6395     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6396
6397     if (HiIndex >= 2) {
6398       Mask1[0] = PermMask[0];
6399       Mask1[1] = PermMask[1];
6400       Mask1[2] = HiIndex & 1 ? 6 : 4;
6401       Mask1[3] = HiIndex & 1 ? 4 : 6;
6402       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6403     }
6404
6405     Mask1[0] = HiIndex & 1 ? 2 : 0;
6406     Mask1[1] = HiIndex & 1 ? 0 : 2;
6407     Mask1[2] = PermMask[2];
6408     Mask1[3] = PermMask[3];
6409     if (Mask1[2] >= 0)
6410       Mask1[2] += 4;
6411     if (Mask1[3] >= 0)
6412       Mask1[3] += 4;
6413     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6414   }
6415
6416   // Break it into (shuffle shuffle_hi, shuffle_lo).
6417   int LoMask[] = { -1, -1, -1, -1 };
6418   int HiMask[] = { -1, -1, -1, -1 };
6419
6420   int *MaskPtr = LoMask;
6421   unsigned MaskIdx = 0;
6422   unsigned LoIdx = 0;
6423   unsigned HiIdx = 2;
6424   for (unsigned i = 0; i != 4; ++i) {
6425     if (i == 2) {
6426       MaskPtr = HiMask;
6427       MaskIdx = 1;
6428       LoIdx = 0;
6429       HiIdx = 2;
6430     }
6431     int Idx = PermMask[i];
6432     if (Idx < 0) {
6433       Locs[i] = std::make_pair(-1, -1);
6434     } else if (Idx < 4) {
6435       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6436       MaskPtr[LoIdx] = Idx;
6437       LoIdx++;
6438     } else {
6439       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6440       MaskPtr[HiIdx] = Idx;
6441       HiIdx++;
6442     }
6443   }
6444
6445   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6446   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6447   int MaskOps[] = { -1, -1, -1, -1 };
6448   for (unsigned i = 0; i != 4; ++i)
6449     if (Locs[i].first != -1)
6450       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6451   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6452 }
6453
6454 static bool MayFoldVectorLoad(SDValue V) {
6455   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6456     V = V.getOperand(0);
6457
6458   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6459     V = V.getOperand(0);
6460   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6461       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6462     // BUILD_VECTOR (load), undef
6463     V = V.getOperand(0);
6464
6465   return MayFoldLoad(V);
6466 }
6467
6468 static
6469 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6470   EVT VT = Op.getValueType();
6471
6472   // Canonizalize to v2f64.
6473   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6474   return DAG.getNode(ISD::BITCAST, dl, VT,
6475                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6476                                           V1, DAG));
6477 }
6478
6479 static
6480 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6481                         bool HasSSE2) {
6482   SDValue V1 = Op.getOperand(0);
6483   SDValue V2 = Op.getOperand(1);
6484   EVT VT = Op.getValueType();
6485
6486   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6487
6488   if (HasSSE2 && VT == MVT::v2f64)
6489     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6490
6491   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6492   return DAG.getNode(ISD::BITCAST, dl, VT,
6493                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6494                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6495                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6496 }
6497
6498 static
6499 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6500   SDValue V1 = Op.getOperand(0);
6501   SDValue V2 = Op.getOperand(1);
6502   EVT VT = Op.getValueType();
6503
6504   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6505          "unsupported shuffle type");
6506
6507   if (V2.getOpcode() == ISD::UNDEF)
6508     V2 = V1;
6509
6510   // v4i32 or v4f32
6511   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6512 }
6513
6514 static
6515 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6516   SDValue V1 = Op.getOperand(0);
6517   SDValue V2 = Op.getOperand(1);
6518   EVT VT = Op.getValueType();
6519   unsigned NumElems = VT.getVectorNumElements();
6520
6521   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6522   // operand of these instructions is only memory, so check if there's a
6523   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6524   // same masks.
6525   bool CanFoldLoad = false;
6526
6527   // Trivial case, when V2 comes from a load.
6528   if (MayFoldVectorLoad(V2))
6529     CanFoldLoad = true;
6530
6531   // When V1 is a load, it can be folded later into a store in isel, example:
6532   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6533   //    turns into:
6534   //  (MOVLPSmr addr:$src1, VR128:$src2)
6535   // So, recognize this potential and also use MOVLPS or MOVLPD
6536   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6537     CanFoldLoad = true;
6538
6539   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6540   if (CanFoldLoad) {
6541     if (HasSSE2 && NumElems == 2)
6542       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6543
6544     if (NumElems == 4)
6545       // If we don't care about the second element, proceed to use movss.
6546       if (SVOp->getMaskElt(1) != -1)
6547         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6548   }
6549
6550   // movl and movlp will both match v2i64, but v2i64 is never matched by
6551   // movl earlier because we make it strict to avoid messing with the movlp load
6552   // folding logic (see the code above getMOVLP call). Match it here then,
6553   // this is horrible, but will stay like this until we move all shuffle
6554   // matching to x86 specific nodes. Note that for the 1st condition all
6555   // types are matched with movsd.
6556   if (HasSSE2) {
6557     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6558     // as to remove this logic from here, as much as possible
6559     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6560       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6561     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6562   }
6563
6564   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6565
6566   // Invert the operand order and use SHUFPS to match it.
6567   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6568                               getShuffleSHUFImmediate(SVOp), DAG);
6569 }
6570
6571 // Reduce a vector shuffle to zext.
6572 SDValue
6573 X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6574   // PMOVZX is only available from SSE41.
6575   if (!Subtarget->hasSSE41())
6576     return SDValue();
6577
6578   EVT VT = Op.getValueType();
6579
6580   // Only AVX2 support 256-bit vector integer extending.
6581   if (!Subtarget->hasInt256() && VT.is256BitVector())
6582     return SDValue();
6583
6584   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6585   DebugLoc DL = Op.getDebugLoc();
6586   SDValue V1 = Op.getOperand(0);
6587   SDValue V2 = Op.getOperand(1);
6588   unsigned NumElems = VT.getVectorNumElements();
6589
6590   // Extending is an unary operation and the element type of the source vector
6591   // won't be equal to or larger than i64.
6592   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6593       VT.getVectorElementType() == MVT::i64)
6594     return SDValue();
6595
6596   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6597   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6598   while ((1U << Shift) < NumElems) {
6599     if (SVOp->getMaskElt(1U << Shift) == 1)
6600       break;
6601     Shift += 1;
6602     // The maximal ratio is 8, i.e. from i8 to i64.
6603     if (Shift > 3)
6604       return SDValue();
6605   }
6606
6607   // Check the shuffle mask.
6608   unsigned Mask = (1U << Shift) - 1;
6609   for (unsigned i = 0; i != NumElems; ++i) {
6610     int EltIdx = SVOp->getMaskElt(i);
6611     if ((i & Mask) != 0 && EltIdx != -1)
6612       return SDValue();
6613     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6614       return SDValue();
6615   }
6616
6617   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6618   EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6619   EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6620
6621   if (!isTypeLegal(NVT))
6622     return SDValue();
6623
6624   // Simplify the operand as it's prepared to be fed into shuffle.
6625   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6626   if (V1.getOpcode() == ISD::BITCAST &&
6627       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6628       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6629       V1.getOperand(0)
6630         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6631     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6632     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6633     ConstantSDNode *CIdx =
6634       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6635     // If it's foldable, i.e. normal load with single use, we will let code
6636     // selection to fold it. Otherwise, we will short the conversion sequence.
6637     if (CIdx && CIdx->getZExtValue() == 0 &&
6638         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6639       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6640   }
6641
6642   return DAG.getNode(ISD::BITCAST, DL, VT,
6643                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6644 }
6645
6646 SDValue
6647 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6648   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6649   EVT VT = Op.getValueType();
6650   DebugLoc dl = Op.getDebugLoc();
6651   SDValue V1 = Op.getOperand(0);
6652   SDValue V2 = Op.getOperand(1);
6653
6654   if (isZeroShuffle(SVOp))
6655     return getZeroVector(VT, Subtarget, DAG, dl);
6656
6657   // Handle splat operations
6658   if (SVOp->isSplat()) {
6659     unsigned NumElem = VT.getVectorNumElements();
6660     int Size = VT.getSizeInBits();
6661
6662     // Use vbroadcast whenever the splat comes from a foldable load
6663     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6664     if (Broadcast.getNode())
6665       return Broadcast;
6666
6667     // Handle splats by matching through known shuffle masks
6668     if ((Size == 128 && NumElem <= 4) ||
6669         (Size == 256 && NumElem <= 8))
6670       return SDValue();
6671
6672     // All remaning splats are promoted to target supported vector shuffles.
6673     return PromoteSplat(SVOp, DAG);
6674   }
6675
6676   // Check integer expanding shuffles.
6677   SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6678   if (NewOp.getNode())
6679     return NewOp;
6680
6681   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6682   // do it!
6683   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6684       VT == MVT::v16i16 || VT == MVT::v32i8) {
6685     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6686     if (NewOp.getNode())
6687       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6688   } else if ((VT == MVT::v4i32 ||
6689              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6690     // FIXME: Figure out a cleaner way to do this.
6691     // Try to make use of movq to zero out the top part.
6692     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6693       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6694       if (NewOp.getNode()) {
6695         EVT NewVT = NewOp.getValueType();
6696         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6697                                NewVT, true, false))
6698           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6699                               DAG, Subtarget, dl);
6700       }
6701     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6702       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6703       if (NewOp.getNode()) {
6704         EVT NewVT = NewOp.getValueType();
6705         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6706           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6707                               DAG, Subtarget, dl);
6708       }
6709     }
6710   }
6711   return SDValue();
6712 }
6713
6714 SDValue
6715 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6716   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6717   SDValue V1 = Op.getOperand(0);
6718   SDValue V2 = Op.getOperand(1);
6719   EVT VT = Op.getValueType();
6720   DebugLoc dl = Op.getDebugLoc();
6721   unsigned NumElems = VT.getVectorNumElements();
6722   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6723   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6724   bool V1IsSplat = false;
6725   bool V2IsSplat = false;
6726   bool HasSSE2 = Subtarget->hasSSE2();
6727   bool HasFp256    = Subtarget->hasFp256();
6728   bool HasInt256   = Subtarget->hasInt256();
6729   MachineFunction &MF = DAG.getMachineFunction();
6730   bool OptForSize = MF.getFunction()->getFnAttributes().
6731     hasAttribute(Attribute::OptimizeForSize);
6732
6733   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6734
6735   if (V1IsUndef && V2IsUndef)
6736     return DAG.getUNDEF(VT);
6737
6738   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6739
6740   // Vector shuffle lowering takes 3 steps:
6741   //
6742   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6743   //    narrowing and commutation of operands should be handled.
6744   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6745   //    shuffle nodes.
6746   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6747   //    so the shuffle can be broken into other shuffles and the legalizer can
6748   //    try the lowering again.
6749   //
6750   // The general idea is that no vector_shuffle operation should be left to
6751   // be matched during isel, all of them must be converted to a target specific
6752   // node here.
6753
6754   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6755   // narrowing and commutation of operands should be handled. The actual code
6756   // doesn't include all of those, work in progress...
6757   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6758   if (NewOp.getNode())
6759     return NewOp;
6760
6761   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6762
6763   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6764   // unpckh_undef). Only use pshufd if speed is more important than size.
6765   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6766     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6767   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6768     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6769
6770   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6771       V2IsUndef && MayFoldVectorLoad(V1))
6772     return getMOVDDup(Op, dl, V1, DAG);
6773
6774   if (isMOVHLPS_v_undef_Mask(M, VT))
6775     return getMOVHighToLow(Op, dl, DAG);
6776
6777   // Use to match splats
6778   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6779       (VT == MVT::v2f64 || VT == MVT::v2i64))
6780     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6781
6782   if (isPSHUFDMask(M, VT)) {
6783     // The actual implementation will match the mask in the if above and then
6784     // during isel it can match several different instructions, not only pshufd
6785     // as its name says, sad but true, emulate the behavior for now...
6786     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6787       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6788
6789     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6790
6791     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6792       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6793
6794     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6795       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6796                                   DAG);
6797
6798     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6799                                 TargetMask, DAG);
6800   }
6801
6802   // Check if this can be converted into a logical shift.
6803   bool isLeft = false;
6804   unsigned ShAmt = 0;
6805   SDValue ShVal;
6806   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6807   if (isShift && ShVal.hasOneUse()) {
6808     // If the shifted value has multiple uses, it may be cheaper to use
6809     // v_set0 + movlhps or movhlps, etc.
6810     EVT EltVT = VT.getVectorElementType();
6811     ShAmt *= EltVT.getSizeInBits();
6812     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6813   }
6814
6815   if (isMOVLMask(M, VT)) {
6816     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6817       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6818     if (!isMOVLPMask(M, VT)) {
6819       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6820         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6821
6822       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6823         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6824     }
6825   }
6826
6827   // FIXME: fold these into legal mask.
6828   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6829     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6830
6831   if (isMOVHLPSMask(M, VT))
6832     return getMOVHighToLow(Op, dl, DAG);
6833
6834   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6835     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6836
6837   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6838     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6839
6840   if (isMOVLPMask(M, VT))
6841     return getMOVLP(Op, dl, DAG, HasSSE2);
6842
6843   if (ShouldXformToMOVHLPS(M, VT) ||
6844       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6845     return CommuteVectorShuffle(SVOp, DAG);
6846
6847   if (isShift) {
6848     // No better options. Use a vshldq / vsrldq.
6849     EVT EltVT = VT.getVectorElementType();
6850     ShAmt *= EltVT.getSizeInBits();
6851     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6852   }
6853
6854   bool Commuted = false;
6855   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6856   // 1,1,1,1 -> v8i16 though.
6857   V1IsSplat = isSplatVector(V1.getNode());
6858   V2IsSplat = isSplatVector(V2.getNode());
6859
6860   // Canonicalize the splat or undef, if present, to be on the RHS.
6861   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6862     CommuteVectorShuffleMask(M, NumElems);
6863     std::swap(V1, V2);
6864     std::swap(V1IsSplat, V2IsSplat);
6865     Commuted = true;
6866   }
6867
6868   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6869     // Shuffling low element of v1 into undef, just return v1.
6870     if (V2IsUndef)
6871       return V1;
6872     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6873     // the instruction selector will not match, so get a canonical MOVL with
6874     // swapped operands to undo the commute.
6875     return getMOVL(DAG, dl, VT, V2, V1);
6876   }
6877
6878   if (isUNPCKLMask(M, VT, HasInt256))
6879     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6880
6881   if (isUNPCKHMask(M, VT, HasInt256))
6882     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6883
6884   if (V2IsSplat) {
6885     // Normalize mask so all entries that point to V2 points to its first
6886     // element then try to match unpck{h|l} again. If match, return a
6887     // new vector_shuffle with the corrected mask.p
6888     SmallVector<int, 8> NewMask(M.begin(), M.end());
6889     NormalizeMask(NewMask, NumElems);
6890     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6891       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6892     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6893       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6894   }
6895
6896   if (Commuted) {
6897     // Commute is back and try unpck* again.
6898     // FIXME: this seems wrong.
6899     CommuteVectorShuffleMask(M, NumElems);
6900     std::swap(V1, V2);
6901     std::swap(V1IsSplat, V2IsSplat);
6902     Commuted = false;
6903
6904     if (isUNPCKLMask(M, VT, HasInt256))
6905       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6906
6907     if (isUNPCKHMask(M, VT, HasInt256))
6908       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6909   }
6910
6911   // Normalize the node to match x86 shuffle ops if needed
6912   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6913     return CommuteVectorShuffle(SVOp, DAG);
6914
6915   // The checks below are all present in isShuffleMaskLegal, but they are
6916   // inlined here right now to enable us to directly emit target specific
6917   // nodes, and remove one by one until they don't return Op anymore.
6918
6919   if (isPALIGNRMask(M, VT, Subtarget))
6920     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6921                                 getShufflePALIGNRImmediate(SVOp),
6922                                 DAG);
6923
6924   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6925       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6926     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6927       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6928   }
6929
6930   if (isPSHUFHWMask(M, VT, HasInt256))
6931     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6932                                 getShufflePSHUFHWImmediate(SVOp),
6933                                 DAG);
6934
6935   if (isPSHUFLWMask(M, VT, HasInt256))
6936     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6937                                 getShufflePSHUFLWImmediate(SVOp),
6938                                 DAG);
6939
6940   if (isSHUFPMask(M, VT, HasFp256))
6941     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6942                                 getShuffleSHUFImmediate(SVOp), DAG);
6943
6944   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6945     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6946   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6947     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6948
6949   //===--------------------------------------------------------------------===//
6950   // Generate target specific nodes for 128 or 256-bit shuffles only
6951   // supported in the AVX instruction set.
6952   //
6953
6954   // Handle VMOVDDUPY permutations
6955   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
6956     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6957
6958   // Handle VPERMILPS/D* permutations
6959   if (isVPERMILPMask(M, VT, HasFp256)) {
6960     if (HasInt256 && VT == MVT::v8i32)
6961       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6962                                   getShuffleSHUFImmediate(SVOp), DAG);
6963     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6964                                 getShuffleSHUFImmediate(SVOp), DAG);
6965   }
6966
6967   // Handle VPERM2F128/VPERM2I128 permutations
6968   if (isVPERM2X128Mask(M, VT, HasFp256))
6969     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6970                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6971
6972   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6973   if (BlendOp.getNode())
6974     return BlendOp;
6975
6976   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6977     SmallVector<SDValue, 8> permclMask;
6978     for (unsigned i = 0; i != 8; ++i) {
6979       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6980     }
6981     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6982                                &permclMask[0], 8);
6983     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6984     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6985                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6986   }
6987
6988   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6989     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6990                                 getShuffleCLImmediate(SVOp), DAG);
6991
6992   //===--------------------------------------------------------------------===//
6993   // Since no target specific shuffle was selected for this generic one,
6994   // lower it into other known shuffles. FIXME: this isn't true yet, but
6995   // this is the plan.
6996   //
6997
6998   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6999   if (VT == MVT::v8i16) {
7000     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7001     if (NewOp.getNode())
7002       return NewOp;
7003   }
7004
7005   if (VT == MVT::v16i8) {
7006     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7007     if (NewOp.getNode())
7008       return NewOp;
7009   }
7010
7011   if (VT == MVT::v32i8) {
7012     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7013     if (NewOp.getNode())
7014       return NewOp;
7015   }
7016
7017   // Handle all 128-bit wide vectors with 4 elements, and match them with
7018   // several different shuffle types.
7019   if (NumElems == 4 && VT.is128BitVector())
7020     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7021
7022   // Handle general 256-bit shuffles
7023   if (VT.is256BitVector())
7024     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7025
7026   return SDValue();
7027 }
7028
7029 SDValue
7030 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7031                                                 SelectionDAG &DAG) const {
7032   EVT VT = Op.getValueType();
7033   DebugLoc dl = Op.getDebugLoc();
7034
7035   if (!Op.getOperand(0).getValueType().is128BitVector())
7036     return SDValue();
7037
7038   if (VT.getSizeInBits() == 8) {
7039     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7040                                   Op.getOperand(0), Op.getOperand(1));
7041     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7042                                   DAG.getValueType(VT));
7043     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7044   }
7045
7046   if (VT.getSizeInBits() == 16) {
7047     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7048     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7049     if (Idx == 0)
7050       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7051                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7052                                      DAG.getNode(ISD::BITCAST, dl,
7053                                                  MVT::v4i32,
7054                                                  Op.getOperand(0)),
7055                                      Op.getOperand(1)));
7056     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7057                                   Op.getOperand(0), Op.getOperand(1));
7058     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7059                                   DAG.getValueType(VT));
7060     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7061   }
7062
7063   if (VT == MVT::f32) {
7064     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7065     // the result back to FR32 register. It's only worth matching if the
7066     // result has a single use which is a store or a bitcast to i32.  And in
7067     // the case of a store, it's not worth it if the index is a constant 0,
7068     // because a MOVSSmr can be used instead, which is smaller and faster.
7069     if (!Op.hasOneUse())
7070       return SDValue();
7071     SDNode *User = *Op.getNode()->use_begin();
7072     if ((User->getOpcode() != ISD::STORE ||
7073          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7074           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7075         (User->getOpcode() != ISD::BITCAST ||
7076          User->getValueType(0) != MVT::i32))
7077       return SDValue();
7078     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7079                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7080                                               Op.getOperand(0)),
7081                                               Op.getOperand(1));
7082     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7083   }
7084
7085   if (VT == MVT::i32 || VT == MVT::i64) {
7086     // ExtractPS/pextrq works with constant index.
7087     if (isa<ConstantSDNode>(Op.getOperand(1)))
7088       return Op;
7089   }
7090   return SDValue();
7091 }
7092
7093 SDValue
7094 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7095                                            SelectionDAG &DAG) const {
7096   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7097     return SDValue();
7098
7099   SDValue Vec = Op.getOperand(0);
7100   EVT VecVT = Vec.getValueType();
7101
7102   // If this is a 256-bit vector result, first extract the 128-bit vector and
7103   // then extract the element from the 128-bit vector.
7104   if (VecVT.is256BitVector()) {
7105     DebugLoc dl = Op.getNode()->getDebugLoc();
7106     unsigned NumElems = VecVT.getVectorNumElements();
7107     SDValue Idx = Op.getOperand(1);
7108     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7109
7110     // Get the 128-bit vector.
7111     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7112
7113     if (IdxVal >= NumElems/2)
7114       IdxVal -= NumElems/2;
7115     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7116                        DAG.getConstant(IdxVal, MVT::i32));
7117   }
7118
7119   assert(VecVT.is128BitVector() && "Unexpected vector length");
7120
7121   if (Subtarget->hasSSE41()) {
7122     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7123     if (Res.getNode())
7124       return Res;
7125   }
7126
7127   EVT VT = Op.getValueType();
7128   DebugLoc dl = Op.getDebugLoc();
7129   // TODO: handle v16i8.
7130   if (VT.getSizeInBits() == 16) {
7131     SDValue Vec = Op.getOperand(0);
7132     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7133     if (Idx == 0)
7134       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7135                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7136                                      DAG.getNode(ISD::BITCAST, dl,
7137                                                  MVT::v4i32, Vec),
7138                                      Op.getOperand(1)));
7139     // Transform it so it match pextrw which produces a 32-bit result.
7140     EVT EltVT = MVT::i32;
7141     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7142                                   Op.getOperand(0), Op.getOperand(1));
7143     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7144                                   DAG.getValueType(VT));
7145     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7146   }
7147
7148   if (VT.getSizeInBits() == 32) {
7149     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7150     if (Idx == 0)
7151       return Op;
7152
7153     // SHUFPS the element to the lowest double word, then movss.
7154     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7155     EVT VVT = Op.getOperand(0).getValueType();
7156     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7157                                        DAG.getUNDEF(VVT), Mask);
7158     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7159                        DAG.getIntPtrConstant(0));
7160   }
7161
7162   if (VT.getSizeInBits() == 64) {
7163     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7164     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7165     //        to match extract_elt for f64.
7166     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7167     if (Idx == 0)
7168       return Op;
7169
7170     // UNPCKHPD the element to the lowest double word, then movsd.
7171     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7172     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7173     int Mask[2] = { 1, -1 };
7174     EVT VVT = Op.getOperand(0).getValueType();
7175     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7176                                        DAG.getUNDEF(VVT), Mask);
7177     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7178                        DAG.getIntPtrConstant(0));
7179   }
7180
7181   return SDValue();
7182 }
7183
7184 SDValue
7185 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7186                                                SelectionDAG &DAG) const {
7187   EVT VT = Op.getValueType();
7188   EVT EltVT = VT.getVectorElementType();
7189   DebugLoc dl = Op.getDebugLoc();
7190
7191   SDValue N0 = Op.getOperand(0);
7192   SDValue N1 = Op.getOperand(1);
7193   SDValue N2 = Op.getOperand(2);
7194
7195   if (!VT.is128BitVector())
7196     return SDValue();
7197
7198   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7199       isa<ConstantSDNode>(N2)) {
7200     unsigned Opc;
7201     if (VT == MVT::v8i16)
7202       Opc = X86ISD::PINSRW;
7203     else if (VT == MVT::v16i8)
7204       Opc = X86ISD::PINSRB;
7205     else
7206       Opc = X86ISD::PINSRB;
7207
7208     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7209     // argument.
7210     if (N1.getValueType() != MVT::i32)
7211       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7212     if (N2.getValueType() != MVT::i32)
7213       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7214     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7215   }
7216
7217   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7218     // Bits [7:6] of the constant are the source select.  This will always be
7219     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7220     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7221     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7222     // Bits [5:4] of the constant are the destination select.  This is the
7223     //  value of the incoming immediate.
7224     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7225     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7226     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7227     // Create this as a scalar to vector..
7228     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7229     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7230   }
7231
7232   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7233     // PINSR* works with constant index.
7234     return Op;
7235   }
7236   return SDValue();
7237 }
7238
7239 SDValue
7240 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7241   EVT VT = Op.getValueType();
7242   EVT EltVT = VT.getVectorElementType();
7243
7244   DebugLoc dl = Op.getDebugLoc();
7245   SDValue N0 = Op.getOperand(0);
7246   SDValue N1 = Op.getOperand(1);
7247   SDValue N2 = Op.getOperand(2);
7248
7249   // If this is a 256-bit vector result, first extract the 128-bit vector,
7250   // insert the element into the extracted half and then place it back.
7251   if (VT.is256BitVector()) {
7252     if (!isa<ConstantSDNode>(N2))
7253       return SDValue();
7254
7255     // Get the desired 128-bit vector half.
7256     unsigned NumElems = VT.getVectorNumElements();
7257     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7258     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7259
7260     // Insert the element into the desired half.
7261     bool Upper = IdxVal >= NumElems/2;
7262     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7263                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7264
7265     // Insert the changed part back to the 256-bit vector
7266     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7267   }
7268
7269   if (Subtarget->hasSSE41())
7270     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7271
7272   if (EltVT == MVT::i8)
7273     return SDValue();
7274
7275   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7276     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7277     // as its second argument.
7278     if (N1.getValueType() != MVT::i32)
7279       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7280     if (N2.getValueType() != MVT::i32)
7281       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7282     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7283   }
7284   return SDValue();
7285 }
7286
7287 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7288   LLVMContext *Context = DAG.getContext();
7289   DebugLoc dl = Op.getDebugLoc();
7290   EVT OpVT = Op.getValueType();
7291
7292   // If this is a 256-bit vector result, first insert into a 128-bit
7293   // vector and then insert into the 256-bit vector.
7294   if (!OpVT.is128BitVector()) {
7295     // Insert into a 128-bit vector.
7296     EVT VT128 = EVT::getVectorVT(*Context,
7297                                  OpVT.getVectorElementType(),
7298                                  OpVT.getVectorNumElements() / 2);
7299
7300     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7301
7302     // Insert the 128-bit vector.
7303     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7304   }
7305
7306   if (OpVT == MVT::v1i64 &&
7307       Op.getOperand(0).getValueType() == MVT::i64)
7308     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7309
7310   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7311   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7312   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7313                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7314 }
7315
7316 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7317 // a simple subregister reference or explicit instructions to grab
7318 // upper bits of a vector.
7319 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7320                                       SelectionDAG &DAG) {
7321   if (Subtarget->hasFp256()) {
7322     DebugLoc dl = Op.getNode()->getDebugLoc();
7323     SDValue Vec = Op.getNode()->getOperand(0);
7324     SDValue Idx = Op.getNode()->getOperand(1);
7325
7326     if (Op.getNode()->getValueType(0).is128BitVector() &&
7327         Vec.getNode()->getValueType(0).is256BitVector() &&
7328         isa<ConstantSDNode>(Idx)) {
7329       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7330       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7331     }
7332   }
7333   return SDValue();
7334 }
7335
7336 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7337 // simple superregister reference or explicit instructions to insert
7338 // the upper bits of a vector.
7339 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7340                                      SelectionDAG &DAG) {
7341   if (Subtarget->hasFp256()) {
7342     DebugLoc dl = Op.getNode()->getDebugLoc();
7343     SDValue Vec = Op.getNode()->getOperand(0);
7344     SDValue SubVec = Op.getNode()->getOperand(1);
7345     SDValue Idx = Op.getNode()->getOperand(2);
7346
7347     if (Op.getNode()->getValueType(0).is256BitVector() &&
7348         SubVec.getNode()->getValueType(0).is128BitVector() &&
7349         isa<ConstantSDNode>(Idx)) {
7350       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7351       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7352     }
7353   }
7354   return SDValue();
7355 }
7356
7357 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7358 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7359 // one of the above mentioned nodes. It has to be wrapped because otherwise
7360 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7361 // be used to form addressing mode. These wrapped nodes will be selected
7362 // into MOV32ri.
7363 SDValue
7364 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7365   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7366
7367   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7368   // global base reg.
7369   unsigned char OpFlag = 0;
7370   unsigned WrapperKind = X86ISD::Wrapper;
7371   CodeModel::Model M = getTargetMachine().getCodeModel();
7372
7373   if (Subtarget->isPICStyleRIPRel() &&
7374       (M == CodeModel::Small || M == CodeModel::Kernel))
7375     WrapperKind = X86ISD::WrapperRIP;
7376   else if (Subtarget->isPICStyleGOT())
7377     OpFlag = X86II::MO_GOTOFF;
7378   else if (Subtarget->isPICStyleStubPIC())
7379     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7380
7381   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7382                                              CP->getAlignment(),
7383                                              CP->getOffset(), OpFlag);
7384   DebugLoc DL = CP->getDebugLoc();
7385   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7386   // With PIC, the address is actually $g + Offset.
7387   if (OpFlag) {
7388     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7389                          DAG.getNode(X86ISD::GlobalBaseReg,
7390                                      DebugLoc(), getPointerTy()),
7391                          Result);
7392   }
7393
7394   return Result;
7395 }
7396
7397 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7398   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7399
7400   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7401   // global base reg.
7402   unsigned char OpFlag = 0;
7403   unsigned WrapperKind = X86ISD::Wrapper;
7404   CodeModel::Model M = getTargetMachine().getCodeModel();
7405
7406   if (Subtarget->isPICStyleRIPRel() &&
7407       (M == CodeModel::Small || M == CodeModel::Kernel))
7408     WrapperKind = X86ISD::WrapperRIP;
7409   else if (Subtarget->isPICStyleGOT())
7410     OpFlag = X86II::MO_GOTOFF;
7411   else if (Subtarget->isPICStyleStubPIC())
7412     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7413
7414   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7415                                           OpFlag);
7416   DebugLoc DL = JT->getDebugLoc();
7417   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7418
7419   // With PIC, the address is actually $g + Offset.
7420   if (OpFlag)
7421     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7422                          DAG.getNode(X86ISD::GlobalBaseReg,
7423                                      DebugLoc(), getPointerTy()),
7424                          Result);
7425
7426   return Result;
7427 }
7428
7429 SDValue
7430 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7431   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7432
7433   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7434   // global base reg.
7435   unsigned char OpFlag = 0;
7436   unsigned WrapperKind = X86ISD::Wrapper;
7437   CodeModel::Model M = getTargetMachine().getCodeModel();
7438
7439   if (Subtarget->isPICStyleRIPRel() &&
7440       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7441     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7442       OpFlag = X86II::MO_GOTPCREL;
7443     WrapperKind = X86ISD::WrapperRIP;
7444   } else if (Subtarget->isPICStyleGOT()) {
7445     OpFlag = X86II::MO_GOT;
7446   } else if (Subtarget->isPICStyleStubPIC()) {
7447     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7448   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7449     OpFlag = X86II::MO_DARWIN_NONLAZY;
7450   }
7451
7452   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7453
7454   DebugLoc DL = Op.getDebugLoc();
7455   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7456
7457   // With PIC, the address is actually $g + Offset.
7458   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7459       !Subtarget->is64Bit()) {
7460     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7461                          DAG.getNode(X86ISD::GlobalBaseReg,
7462                                      DebugLoc(), getPointerTy()),
7463                          Result);
7464   }
7465
7466   // For symbols that require a load from a stub to get the address, emit the
7467   // load.
7468   if (isGlobalStubReference(OpFlag))
7469     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7470                          MachinePointerInfo::getGOT(), false, false, false, 0);
7471
7472   return Result;
7473 }
7474
7475 SDValue
7476 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7477   // Create the TargetBlockAddressAddress node.
7478   unsigned char OpFlags =
7479     Subtarget->ClassifyBlockAddressReference();
7480   CodeModel::Model M = getTargetMachine().getCodeModel();
7481   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7482   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7483   DebugLoc dl = Op.getDebugLoc();
7484   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7485                                              OpFlags);
7486
7487   if (Subtarget->isPICStyleRIPRel() &&
7488       (M == CodeModel::Small || M == CodeModel::Kernel))
7489     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7490   else
7491     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7492
7493   // With PIC, the address is actually $g + Offset.
7494   if (isGlobalRelativeToPICBase(OpFlags)) {
7495     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7496                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7497                          Result);
7498   }
7499
7500   return Result;
7501 }
7502
7503 SDValue
7504 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7505                                       int64_t Offset,
7506                                       SelectionDAG &DAG) const {
7507   // Create the TargetGlobalAddress node, folding in the constant
7508   // offset if it is legal.
7509   unsigned char OpFlags =
7510     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7511   CodeModel::Model M = getTargetMachine().getCodeModel();
7512   SDValue Result;
7513   if (OpFlags == X86II::MO_NO_FLAG &&
7514       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7515     // A direct static reference to a global.
7516     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7517     Offset = 0;
7518   } else {
7519     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7520   }
7521
7522   if (Subtarget->isPICStyleRIPRel() &&
7523       (M == CodeModel::Small || M == CodeModel::Kernel))
7524     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7525   else
7526     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7527
7528   // With PIC, the address is actually $g + Offset.
7529   if (isGlobalRelativeToPICBase(OpFlags)) {
7530     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7531                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7532                          Result);
7533   }
7534
7535   // For globals that require a load from a stub to get the address, emit the
7536   // load.
7537   if (isGlobalStubReference(OpFlags))
7538     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7539                          MachinePointerInfo::getGOT(), false, false, false, 0);
7540
7541   // If there was a non-zero offset that we didn't fold, create an explicit
7542   // addition for it.
7543   if (Offset != 0)
7544     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7545                          DAG.getConstant(Offset, getPointerTy()));
7546
7547   return Result;
7548 }
7549
7550 SDValue
7551 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7552   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7553   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7554   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7555 }
7556
7557 static SDValue
7558 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7559            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7560            unsigned char OperandFlags, bool LocalDynamic = false) {
7561   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7562   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7563   DebugLoc dl = GA->getDebugLoc();
7564   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7565                                            GA->getValueType(0),
7566                                            GA->getOffset(),
7567                                            OperandFlags);
7568
7569   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7570                                            : X86ISD::TLSADDR;
7571
7572   if (InFlag) {
7573     SDValue Ops[] = { Chain,  TGA, *InFlag };
7574     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7575   } else {
7576     SDValue Ops[]  = { Chain, TGA };
7577     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7578   }
7579
7580   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7581   MFI->setAdjustsStack(true);
7582
7583   SDValue Flag = Chain.getValue(1);
7584   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7585 }
7586
7587 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7588 static SDValue
7589 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7590                                 const EVT PtrVT) {
7591   SDValue InFlag;
7592   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7593   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7594                                    DAG.getNode(X86ISD::GlobalBaseReg,
7595                                                DebugLoc(), PtrVT), InFlag);
7596   InFlag = Chain.getValue(1);
7597
7598   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7599 }
7600
7601 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7602 static SDValue
7603 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7604                                 const EVT PtrVT) {
7605   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7606                     X86::RAX, X86II::MO_TLSGD);
7607 }
7608
7609 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7610                                            SelectionDAG &DAG,
7611                                            const EVT PtrVT,
7612                                            bool is64Bit) {
7613   DebugLoc dl = GA->getDebugLoc();
7614
7615   // Get the start address of the TLS block for this module.
7616   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7617       .getInfo<X86MachineFunctionInfo>();
7618   MFI->incNumLocalDynamicTLSAccesses();
7619
7620   SDValue Base;
7621   if (is64Bit) {
7622     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7623                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7624   } else {
7625     SDValue InFlag;
7626     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7627         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7628     InFlag = Chain.getValue(1);
7629     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7630                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7631   }
7632
7633   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7634   // of Base.
7635
7636   // Build x@dtpoff.
7637   unsigned char OperandFlags = X86II::MO_DTPOFF;
7638   unsigned WrapperKind = X86ISD::Wrapper;
7639   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7640                                            GA->getValueType(0),
7641                                            GA->getOffset(), OperandFlags);
7642   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7643
7644   // Add x@dtpoff with the base.
7645   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7646 }
7647
7648 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7649 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7650                                    const EVT PtrVT, TLSModel::Model model,
7651                                    bool is64Bit, bool isPIC) {
7652   DebugLoc dl = GA->getDebugLoc();
7653
7654   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7655   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7656                                                          is64Bit ? 257 : 256));
7657
7658   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7659                                       DAG.getIntPtrConstant(0),
7660                                       MachinePointerInfo(Ptr),
7661                                       false, false, false, 0);
7662
7663   unsigned char OperandFlags = 0;
7664   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7665   // initialexec.
7666   unsigned WrapperKind = X86ISD::Wrapper;
7667   if (model == TLSModel::LocalExec) {
7668     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7669   } else if (model == TLSModel::InitialExec) {
7670     if (is64Bit) {
7671       OperandFlags = X86II::MO_GOTTPOFF;
7672       WrapperKind = X86ISD::WrapperRIP;
7673     } else {
7674       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7675     }
7676   } else {
7677     llvm_unreachable("Unexpected model");
7678   }
7679
7680   // emit "addl x@ntpoff,%eax" (local exec)
7681   // or "addl x@indntpoff,%eax" (initial exec)
7682   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7683   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7684                                            GA->getValueType(0),
7685                                            GA->getOffset(), OperandFlags);
7686   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7687
7688   if (model == TLSModel::InitialExec) {
7689     if (isPIC && !is64Bit) {
7690       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7691                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7692                            Offset);
7693     }
7694
7695     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7696                          MachinePointerInfo::getGOT(), false, false, false,
7697                          0);
7698   }
7699
7700   // The address of the thread local variable is the add of the thread
7701   // pointer with the offset of the variable.
7702   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7703 }
7704
7705 SDValue
7706 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7707
7708   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7709   const GlobalValue *GV = GA->getGlobal();
7710
7711   if (Subtarget->isTargetELF()) {
7712     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7713
7714     switch (model) {
7715       case TLSModel::GeneralDynamic:
7716         if (Subtarget->is64Bit())
7717           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7718         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7719       case TLSModel::LocalDynamic:
7720         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7721                                            Subtarget->is64Bit());
7722       case TLSModel::InitialExec:
7723       case TLSModel::LocalExec:
7724         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7725                                    Subtarget->is64Bit(),
7726                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7727     }
7728     llvm_unreachable("Unknown TLS model.");
7729   }
7730
7731   if (Subtarget->isTargetDarwin()) {
7732     // Darwin only has one model of TLS.  Lower to that.
7733     unsigned char OpFlag = 0;
7734     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7735                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7736
7737     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7738     // global base reg.
7739     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7740                   !Subtarget->is64Bit();
7741     if (PIC32)
7742       OpFlag = X86II::MO_TLVP_PIC_BASE;
7743     else
7744       OpFlag = X86II::MO_TLVP;
7745     DebugLoc DL = Op.getDebugLoc();
7746     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7747                                                 GA->getValueType(0),
7748                                                 GA->getOffset(), OpFlag);
7749     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7750
7751     // With PIC32, the address is actually $g + Offset.
7752     if (PIC32)
7753       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7754                            DAG.getNode(X86ISD::GlobalBaseReg,
7755                                        DebugLoc(), getPointerTy()),
7756                            Offset);
7757
7758     // Lowering the machine isd will make sure everything is in the right
7759     // location.
7760     SDValue Chain = DAG.getEntryNode();
7761     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7762     SDValue Args[] = { Chain, Offset };
7763     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7764
7765     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7766     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7767     MFI->setAdjustsStack(true);
7768
7769     // And our return value (tls address) is in the standard call return value
7770     // location.
7771     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7772     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7773                               Chain.getValue(1));
7774   }
7775
7776   if (Subtarget->isTargetWindows()) {
7777     // Just use the implicit TLS architecture
7778     // Need to generate someting similar to:
7779     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7780     //                                  ; from TEB
7781     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7782     //   mov     rcx, qword [rdx+rcx*8]
7783     //   mov     eax, .tls$:tlsvar
7784     //   [rax+rcx] contains the address
7785     // Windows 64bit: gs:0x58
7786     // Windows 32bit: fs:__tls_array
7787
7788     // If GV is an alias then use the aliasee for determining
7789     // thread-localness.
7790     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7791       GV = GA->resolveAliasedGlobal(false);
7792     DebugLoc dl = GA->getDebugLoc();
7793     SDValue Chain = DAG.getEntryNode();
7794
7795     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7796     // %gs:0x58 (64-bit).
7797     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7798                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7799                                                              256)
7800                                         : Type::getInt32PtrTy(*DAG.getContext(),
7801                                                               257));
7802
7803     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7804                                         Subtarget->is64Bit()
7805                                         ? DAG.getIntPtrConstant(0x58)
7806                                         : DAG.getExternalSymbol("_tls_array",
7807                                                                 getPointerTy()),
7808                                         MachinePointerInfo(Ptr),
7809                                         false, false, false, 0);
7810
7811     // Load the _tls_index variable
7812     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7813     if (Subtarget->is64Bit())
7814       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7815                            IDX, MachinePointerInfo(), MVT::i32,
7816                            false, false, 0);
7817     else
7818       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7819                         false, false, false, 0);
7820
7821     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7822                                     getPointerTy());
7823     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7824
7825     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7826     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7827                       false, false, false, 0);
7828
7829     // Get the offset of start of .tls section
7830     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7831                                              GA->getValueType(0),
7832                                              GA->getOffset(), X86II::MO_SECREL);
7833     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7834
7835     // The address of the thread local variable is the add of the thread
7836     // pointer with the offset of the variable.
7837     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7838   }
7839
7840   llvm_unreachable("TLS not implemented for this target.");
7841 }
7842
7843 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7844 /// and take a 2 x i32 value to shift plus a shift amount.
7845 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7846   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7847   EVT VT = Op.getValueType();
7848   unsigned VTBits = VT.getSizeInBits();
7849   DebugLoc dl = Op.getDebugLoc();
7850   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7851   SDValue ShOpLo = Op.getOperand(0);
7852   SDValue ShOpHi = Op.getOperand(1);
7853   SDValue ShAmt  = Op.getOperand(2);
7854   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7855                                      DAG.getConstant(VTBits - 1, MVT::i8))
7856                        : DAG.getConstant(0, VT);
7857
7858   SDValue Tmp2, Tmp3;
7859   if (Op.getOpcode() == ISD::SHL_PARTS) {
7860     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7861     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7862   } else {
7863     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7864     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7865   }
7866
7867   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7868                                 DAG.getConstant(VTBits, MVT::i8));
7869   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7870                              AndNode, DAG.getConstant(0, MVT::i8));
7871
7872   SDValue Hi, Lo;
7873   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7874   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7875   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7876
7877   if (Op.getOpcode() == ISD::SHL_PARTS) {
7878     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7879     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7880   } else {
7881     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7882     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7883   }
7884
7885   SDValue Ops[2] = { Lo, Hi };
7886   return DAG.getMergeValues(Ops, 2, dl);
7887 }
7888
7889 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7890                                            SelectionDAG &DAG) const {
7891   EVT SrcVT = Op.getOperand(0).getValueType();
7892
7893   if (SrcVT.isVector())
7894     return SDValue();
7895
7896   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7897          "Unknown SINT_TO_FP to lower!");
7898
7899   // These are really Legal; return the operand so the caller accepts it as
7900   // Legal.
7901   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7902     return Op;
7903   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7904       Subtarget->is64Bit()) {
7905     return Op;
7906   }
7907
7908   DebugLoc dl = Op.getDebugLoc();
7909   unsigned Size = SrcVT.getSizeInBits()/8;
7910   MachineFunction &MF = DAG.getMachineFunction();
7911   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7912   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7913   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7914                                StackSlot,
7915                                MachinePointerInfo::getFixedStack(SSFI),
7916                                false, false, 0);
7917   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7918 }
7919
7920 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7921                                      SDValue StackSlot,
7922                                      SelectionDAG &DAG) const {
7923   // Build the FILD
7924   DebugLoc DL = Op.getDebugLoc();
7925   SDVTList Tys;
7926   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7927   if (useSSE)
7928     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7929   else
7930     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7931
7932   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7933
7934   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7935   MachineMemOperand *MMO;
7936   if (FI) {
7937     int SSFI = FI->getIndex();
7938     MMO =
7939       DAG.getMachineFunction()
7940       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7941                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7942   } else {
7943     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7944     StackSlot = StackSlot.getOperand(1);
7945   }
7946   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7947   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7948                                            X86ISD::FILD, DL,
7949                                            Tys, Ops, array_lengthof(Ops),
7950                                            SrcVT, MMO);
7951
7952   if (useSSE) {
7953     Chain = Result.getValue(1);
7954     SDValue InFlag = Result.getValue(2);
7955
7956     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7957     // shouldn't be necessary except that RFP cannot be live across
7958     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7959     MachineFunction &MF = DAG.getMachineFunction();
7960     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7961     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7962     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7963     Tys = DAG.getVTList(MVT::Other);
7964     SDValue Ops[] = {
7965       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7966     };
7967     MachineMemOperand *MMO =
7968       DAG.getMachineFunction()
7969       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7970                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7971
7972     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7973                                     Ops, array_lengthof(Ops),
7974                                     Op.getValueType(), MMO);
7975     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7976                          MachinePointerInfo::getFixedStack(SSFI),
7977                          false, false, false, 0);
7978   }
7979
7980   return Result;
7981 }
7982
7983 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7984 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7985                                                SelectionDAG &DAG) const {
7986   // This algorithm is not obvious. Here it is what we're trying to output:
7987   /*
7988      movq       %rax,  %xmm0
7989      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7990      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7991      #ifdef __SSE3__
7992        haddpd   %xmm0, %xmm0
7993      #else
7994        pshufd   $0x4e, %xmm0, %xmm1
7995        addpd    %xmm1, %xmm0
7996      #endif
7997   */
7998
7999   DebugLoc dl = Op.getDebugLoc();
8000   LLVMContext *Context = DAG.getContext();
8001
8002   // Build some magic constants.
8003   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8004   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8005   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8006
8007   SmallVector<Constant*,2> CV1;
8008   CV1.push_back(
8009         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8010   CV1.push_back(
8011         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8012   Constant *C1 = ConstantVector::get(CV1);
8013   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8014
8015   // Load the 64-bit value into an XMM register.
8016   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8017                             Op.getOperand(0));
8018   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8019                               MachinePointerInfo::getConstantPool(),
8020                               false, false, false, 16);
8021   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8022                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8023                               CLod0);
8024
8025   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8026                               MachinePointerInfo::getConstantPool(),
8027                               false, false, false, 16);
8028   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8029   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8030   SDValue Result;
8031
8032   if (Subtarget->hasSSE3()) {
8033     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8034     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8035   } else {
8036     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8037     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8038                                            S2F, 0x4E, DAG);
8039     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8040                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8041                          Sub);
8042   }
8043
8044   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8045                      DAG.getIntPtrConstant(0));
8046 }
8047
8048 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8049 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8050                                                SelectionDAG &DAG) const {
8051   DebugLoc dl = Op.getDebugLoc();
8052   // FP constant to bias correct the final result.
8053   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8054                                    MVT::f64);
8055
8056   // Load the 32-bit value into an XMM register.
8057   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8058                              Op.getOperand(0));
8059
8060   // Zero out the upper parts of the register.
8061   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8062
8063   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8064                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8065                      DAG.getIntPtrConstant(0));
8066
8067   // Or the load with the bias.
8068   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8069                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8070                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8071                                                    MVT::v2f64, Load)),
8072                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8073                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8074                                                    MVT::v2f64, Bias)));
8075   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8076                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8077                    DAG.getIntPtrConstant(0));
8078
8079   // Subtract the bias.
8080   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8081
8082   // Handle final rounding.
8083   EVT DestVT = Op.getValueType();
8084
8085   if (DestVT.bitsLT(MVT::f64))
8086     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8087                        DAG.getIntPtrConstant(0));
8088   if (DestVT.bitsGT(MVT::f64))
8089     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8090
8091   // Handle final rounding.
8092   return Sub;
8093 }
8094
8095 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8096                                                SelectionDAG &DAG) const {
8097   SDValue N0 = Op.getOperand(0);
8098   EVT SVT = N0.getValueType();
8099   DebugLoc dl = Op.getDebugLoc();
8100
8101   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8102           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8103          "Custom UINT_TO_FP is not supported!");
8104
8105   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements());
8106   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8107                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8108 }
8109
8110 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8111                                            SelectionDAG &DAG) const {
8112   SDValue N0 = Op.getOperand(0);
8113   DebugLoc dl = Op.getDebugLoc();
8114
8115   if (Op.getValueType().isVector())
8116     return lowerUINT_TO_FP_vec(Op, DAG);
8117
8118   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8119   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8120   // the optimization here.
8121   if (DAG.SignBitIsZero(N0))
8122     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8123
8124   EVT SrcVT = N0.getValueType();
8125   EVT DstVT = Op.getValueType();
8126   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8127     return LowerUINT_TO_FP_i64(Op, DAG);
8128   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8129     return LowerUINT_TO_FP_i32(Op, DAG);
8130   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8131     return SDValue();
8132
8133   // Make a 64-bit buffer, and use it to build an FILD.
8134   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8135   if (SrcVT == MVT::i32) {
8136     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8137     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8138                                      getPointerTy(), StackSlot, WordOff);
8139     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8140                                   StackSlot, MachinePointerInfo(),
8141                                   false, false, 0);
8142     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8143                                   OffsetSlot, MachinePointerInfo(),
8144                                   false, false, 0);
8145     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8146     return Fild;
8147   }
8148
8149   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8150   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8151                                StackSlot, MachinePointerInfo(),
8152                                false, false, 0);
8153   // For i64 source, we need to add the appropriate power of 2 if the input
8154   // was negative.  This is the same as the optimization in
8155   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8156   // we must be careful to do the computation in x87 extended precision, not
8157   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8158   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8159   MachineMemOperand *MMO =
8160     DAG.getMachineFunction()
8161     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8162                           MachineMemOperand::MOLoad, 8, 8);
8163
8164   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8165   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8166   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8167                                          MVT::i64, MMO);
8168
8169   APInt FF(32, 0x5F800000ULL);
8170
8171   // Check whether the sign bit is set.
8172   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8173                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8174                                  ISD::SETLT);
8175
8176   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8177   SDValue FudgePtr = DAG.getConstantPool(
8178                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8179                                          getPointerTy());
8180
8181   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8182   SDValue Zero = DAG.getIntPtrConstant(0);
8183   SDValue Four = DAG.getIntPtrConstant(4);
8184   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8185                                Zero, Four);
8186   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8187
8188   // Load the value out, extending it from f32 to f80.
8189   // FIXME: Avoid the extend by constructing the right constant pool?
8190   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8191                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8192                                  MVT::f32, false, false, 4);
8193   // Extend everything to 80 bits to force it to be done on x87.
8194   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8195   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8196 }
8197
8198 std::pair<SDValue,SDValue> X86TargetLowering::
8199 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8200   DebugLoc DL = Op.getDebugLoc();
8201
8202   EVT DstTy = Op.getValueType();
8203
8204   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8205     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8206     DstTy = MVT::i64;
8207   }
8208
8209   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8210          DstTy.getSimpleVT() >= MVT::i16 &&
8211          "Unknown FP_TO_INT to lower!");
8212
8213   // These are really Legal.
8214   if (DstTy == MVT::i32 &&
8215       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8216     return std::make_pair(SDValue(), SDValue());
8217   if (Subtarget->is64Bit() &&
8218       DstTy == MVT::i64 &&
8219       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8220     return std::make_pair(SDValue(), SDValue());
8221
8222   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8223   // stack slot, or into the FTOL runtime function.
8224   MachineFunction &MF = DAG.getMachineFunction();
8225   unsigned MemSize = DstTy.getSizeInBits()/8;
8226   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8227   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8228
8229   unsigned Opc;
8230   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8231     Opc = X86ISD::WIN_FTOL;
8232   else
8233     switch (DstTy.getSimpleVT().SimpleTy) {
8234     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8235     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8236     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8237     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8238     }
8239
8240   SDValue Chain = DAG.getEntryNode();
8241   SDValue Value = Op.getOperand(0);
8242   EVT TheVT = Op.getOperand(0).getValueType();
8243   // FIXME This causes a redundant load/store if the SSE-class value is already
8244   // in memory, such as if it is on the callstack.
8245   if (isScalarFPTypeInSSEReg(TheVT)) {
8246     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8247     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8248                          MachinePointerInfo::getFixedStack(SSFI),
8249                          false, false, 0);
8250     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8251     SDValue Ops[] = {
8252       Chain, StackSlot, DAG.getValueType(TheVT)
8253     };
8254
8255     MachineMemOperand *MMO =
8256       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8257                               MachineMemOperand::MOLoad, MemSize, MemSize);
8258     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8259                                     DstTy, MMO);
8260     Chain = Value.getValue(1);
8261     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8262     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8263   }
8264
8265   MachineMemOperand *MMO =
8266     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8267                             MachineMemOperand::MOStore, MemSize, MemSize);
8268
8269   if (Opc != X86ISD::WIN_FTOL) {
8270     // Build the FP_TO_INT*_IN_MEM
8271     SDValue Ops[] = { Chain, Value, StackSlot };
8272     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8273                                            Ops, 3, DstTy, MMO);
8274     return std::make_pair(FIST, StackSlot);
8275   } else {
8276     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8277       DAG.getVTList(MVT::Other, MVT::Glue),
8278       Chain, Value);
8279     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8280       MVT::i32, ftol.getValue(1));
8281     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8282       MVT::i32, eax.getValue(2));
8283     SDValue Ops[] = { eax, edx };
8284     SDValue pair = IsReplace
8285       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8286       : DAG.getMergeValues(Ops, 2, DL);
8287     return std::make_pair(pair, SDValue());
8288   }
8289 }
8290
8291 SDValue X86TargetLowering::lowerZERO_EXTEND(SDValue Op, SelectionDAG &DAG) const {
8292   DebugLoc DL = Op.getDebugLoc();
8293   EVT VT = Op.getValueType();
8294   SDValue In = Op.getOperand(0);
8295   EVT SVT = In.getValueType();
8296
8297   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8298       VT.getVectorNumElements() != SVT.getVectorNumElements())
8299     return SDValue();
8300
8301   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8302
8303   // AVX2 has better support of integer extending.
8304   if (Subtarget->hasInt256())
8305     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8306
8307   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8308   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8309   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8310                            DAG.getVectorShuffle(MVT::v8i16, DL, In, DAG.getUNDEF(MVT::v8i16), &Mask[0]));
8311
8312   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8313 }
8314
8315 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8316   DebugLoc DL = Op.getDebugLoc();
8317   EVT VT = Op.getValueType();
8318   EVT SVT = Op.getOperand(0).getValueType();
8319
8320   if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8321       VT.getVectorNumElements() != SVT.getVectorNumElements())
8322     return SDValue();
8323
8324   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8325
8326   unsigned NumElems = VT.getVectorNumElements();
8327   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8328                              NumElems * 2);
8329
8330   SDValue In = Op.getOperand(0);
8331   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8332   // Prepare truncation shuffle mask
8333   for (unsigned i = 0; i != NumElems; ++i)
8334     MaskVec[i] = i * 2;
8335   SDValue V = DAG.getVectorShuffle(NVT, DL,
8336                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8337                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8338   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8339                      DAG.getIntPtrConstant(0));
8340 }
8341
8342 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8343                                            SelectionDAG &DAG) const {
8344   if (Op.getValueType().isVector()) {
8345     if (Op.getValueType() == MVT::v8i16)
8346       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8347                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8348                                      MVT::v8i32, Op.getOperand(0)));
8349     return SDValue();
8350   }
8351
8352   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8353     /*IsSigned=*/ true, /*IsReplace=*/ false);
8354   SDValue FIST = Vals.first, StackSlot = Vals.second;
8355   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8356   if (FIST.getNode() == 0) return Op;
8357
8358   if (StackSlot.getNode())
8359     // Load the result.
8360     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8361                        FIST, StackSlot, MachinePointerInfo(),
8362                        false, false, false, 0);
8363
8364   // The node is the result.
8365   return FIST;
8366 }
8367
8368 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8369                                            SelectionDAG &DAG) const {
8370   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8371     /*IsSigned=*/ false, /*IsReplace=*/ false);
8372   SDValue FIST = Vals.first, StackSlot = Vals.second;
8373   assert(FIST.getNode() && "Unexpected failure");
8374
8375   if (StackSlot.getNode())
8376     // Load the result.
8377     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8378                        FIST, StackSlot, MachinePointerInfo(),
8379                        false, false, false, 0);
8380
8381   // The node is the result.
8382   return FIST;
8383 }
8384
8385 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8386                                           SelectionDAG &DAG) const {
8387   DebugLoc DL = Op.getDebugLoc();
8388   EVT VT = Op.getValueType();
8389   SDValue In = Op.getOperand(0);
8390   EVT SVT = In.getValueType();
8391
8392   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8393
8394   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8395                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8396                                  In, DAG.getUNDEF(SVT)));
8397 }
8398
8399 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8400   LLVMContext *Context = DAG.getContext();
8401   DebugLoc dl = Op.getDebugLoc();
8402   EVT VT = Op.getValueType();
8403   EVT EltVT = VT;
8404   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8405   if (VT.isVector()) {
8406     EltVT = VT.getVectorElementType();
8407     NumElts = VT.getVectorNumElements();
8408   }
8409   Constant *C;
8410   if (EltVT == MVT::f64)
8411     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8412   else
8413     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8414   C = ConstantVector::getSplat(NumElts, C);
8415   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8416   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8417   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8418                              MachinePointerInfo::getConstantPool(),
8419                              false, false, false, Alignment);
8420   if (VT.isVector()) {
8421     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8422     return DAG.getNode(ISD::BITCAST, dl, VT,
8423                        DAG.getNode(ISD::AND, dl, ANDVT,
8424                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8425                                                Op.getOperand(0)),
8426                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8427   }
8428   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8429 }
8430
8431 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8432   LLVMContext *Context = DAG.getContext();
8433   DebugLoc dl = Op.getDebugLoc();
8434   EVT VT = Op.getValueType();
8435   EVT EltVT = VT;
8436   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8437   if (VT.isVector()) {
8438     EltVT = VT.getVectorElementType();
8439     NumElts = VT.getVectorNumElements();
8440   }
8441   Constant *C;
8442   if (EltVT == MVT::f64)
8443     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8444   else
8445     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8446   C = ConstantVector::getSplat(NumElts, C);
8447   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8448   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8449   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8450                              MachinePointerInfo::getConstantPool(),
8451                              false, false, false, Alignment);
8452   if (VT.isVector()) {
8453     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8454     return DAG.getNode(ISD::BITCAST, dl, VT,
8455                        DAG.getNode(ISD::XOR, dl, XORVT,
8456                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8457                                                Op.getOperand(0)),
8458                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8459   }
8460
8461   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8462 }
8463
8464 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8465   LLVMContext *Context = DAG.getContext();
8466   SDValue Op0 = Op.getOperand(0);
8467   SDValue Op1 = Op.getOperand(1);
8468   DebugLoc dl = Op.getDebugLoc();
8469   EVT VT = Op.getValueType();
8470   EVT SrcVT = Op1.getValueType();
8471
8472   // If second operand is smaller, extend it first.
8473   if (SrcVT.bitsLT(VT)) {
8474     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8475     SrcVT = VT;
8476   }
8477   // And if it is bigger, shrink it first.
8478   if (SrcVT.bitsGT(VT)) {
8479     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8480     SrcVT = VT;
8481   }
8482
8483   // At this point the operands and the result should have the same
8484   // type, and that won't be f80 since that is not custom lowered.
8485
8486   // First get the sign bit of second operand.
8487   SmallVector<Constant*,4> CV;
8488   if (SrcVT == MVT::f64) {
8489     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8490     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8491   } else {
8492     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8493     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8494     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8495     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8496   }
8497   Constant *C = ConstantVector::get(CV);
8498   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8499   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8500                               MachinePointerInfo::getConstantPool(),
8501                               false, false, false, 16);
8502   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8503
8504   // Shift sign bit right or left if the two operands have different types.
8505   if (SrcVT.bitsGT(VT)) {
8506     // Op0 is MVT::f32, Op1 is MVT::f64.
8507     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8508     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8509                           DAG.getConstant(32, MVT::i32));
8510     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8511     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8512                           DAG.getIntPtrConstant(0));
8513   }
8514
8515   // Clear first operand sign bit.
8516   CV.clear();
8517   if (VT == MVT::f64) {
8518     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8519     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8520   } else {
8521     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8522     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8523     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8524     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8525   }
8526   C = ConstantVector::get(CV);
8527   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8528   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8529                               MachinePointerInfo::getConstantPool(),
8530                               false, false, false, 16);
8531   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8532
8533   // Or the value with the sign bit.
8534   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8535 }
8536
8537 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8538   SDValue N0 = Op.getOperand(0);
8539   DebugLoc dl = Op.getDebugLoc();
8540   EVT VT = Op.getValueType();
8541
8542   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8543   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8544                                   DAG.getConstant(1, VT));
8545   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8546 }
8547
8548 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8549 //
8550 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8551   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8552
8553   if (!Subtarget->hasSSE41())
8554     return SDValue();
8555
8556   if (!Op->hasOneUse())
8557     return SDValue();
8558
8559   SDNode *N = Op.getNode();
8560   DebugLoc DL = N->getDebugLoc();
8561
8562   SmallVector<SDValue, 8> Opnds;
8563   DenseMap<SDValue, unsigned> VecInMap;
8564   EVT VT = MVT::Other;
8565
8566   // Recognize a special case where a vector is casted into wide integer to
8567   // test all 0s.
8568   Opnds.push_back(N->getOperand(0));
8569   Opnds.push_back(N->getOperand(1));
8570
8571   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8572     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8573     // BFS traverse all OR'd operands.
8574     if (I->getOpcode() == ISD::OR) {
8575       Opnds.push_back(I->getOperand(0));
8576       Opnds.push_back(I->getOperand(1));
8577       // Re-evaluate the number of nodes to be traversed.
8578       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8579       continue;
8580     }
8581
8582     // Quit if a non-EXTRACT_VECTOR_ELT
8583     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8584       return SDValue();
8585
8586     // Quit if without a constant index.
8587     SDValue Idx = I->getOperand(1);
8588     if (!isa<ConstantSDNode>(Idx))
8589       return SDValue();
8590
8591     SDValue ExtractedFromVec = I->getOperand(0);
8592     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8593     if (M == VecInMap.end()) {
8594       VT = ExtractedFromVec.getValueType();
8595       // Quit if not 128/256-bit vector.
8596       if (!VT.is128BitVector() && !VT.is256BitVector())
8597         return SDValue();
8598       // Quit if not the same type.
8599       if (VecInMap.begin() != VecInMap.end() &&
8600           VT != VecInMap.begin()->first.getValueType())
8601         return SDValue();
8602       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8603     }
8604     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8605   }
8606
8607   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8608          "Not extracted from 128-/256-bit vector.");
8609
8610   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8611   SmallVector<SDValue, 8> VecIns;
8612
8613   for (DenseMap<SDValue, unsigned>::const_iterator
8614         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8615     // Quit if not all elements are used.
8616     if (I->second != FullMask)
8617       return SDValue();
8618     VecIns.push_back(I->first);
8619   }
8620
8621   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8622
8623   // Cast all vectors into TestVT for PTEST.
8624   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8625     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8626
8627   // If more than one full vectors are evaluated, OR them first before PTEST.
8628   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8629     // Each iteration will OR 2 nodes and append the result until there is only
8630     // 1 node left, i.e. the final OR'd value of all vectors.
8631     SDValue LHS = VecIns[Slot];
8632     SDValue RHS = VecIns[Slot + 1];
8633     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8634   }
8635
8636   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8637                      VecIns.back(), VecIns.back());
8638 }
8639
8640 /// Emit nodes that will be selected as "test Op0,Op0", or something
8641 /// equivalent.
8642 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8643                                     SelectionDAG &DAG) const {
8644   DebugLoc dl = Op.getDebugLoc();
8645
8646   // CF and OF aren't always set the way we want. Determine which
8647   // of these we need.
8648   bool NeedCF = false;
8649   bool NeedOF = false;
8650   switch (X86CC) {
8651   default: break;
8652   case X86::COND_A: case X86::COND_AE:
8653   case X86::COND_B: case X86::COND_BE:
8654     NeedCF = true;
8655     break;
8656   case X86::COND_G: case X86::COND_GE:
8657   case X86::COND_L: case X86::COND_LE:
8658   case X86::COND_O: case X86::COND_NO:
8659     NeedOF = true;
8660     break;
8661   }
8662
8663   // See if we can use the EFLAGS value from the operand instead of
8664   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8665   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8666   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8667     // Emit a CMP with 0, which is the TEST pattern.
8668     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8669                        DAG.getConstant(0, Op.getValueType()));
8670
8671   unsigned Opcode = 0;
8672   unsigned NumOperands = 0;
8673
8674   // Truncate operations may prevent the merge of the SETCC instruction
8675   // and the arithmetic intruction before it. Attempt to truncate the operands
8676   // of the arithmetic instruction and use a reduced bit-width instruction.
8677   bool NeedTruncation = false;
8678   SDValue ArithOp = Op;
8679   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8680     SDValue Arith = Op->getOperand(0);
8681     // Both the trunc and the arithmetic op need to have one user each.
8682     if (Arith->hasOneUse())
8683       switch (Arith.getOpcode()) {
8684         default: break;
8685         case ISD::ADD:
8686         case ISD::SUB:
8687         case ISD::AND:
8688         case ISD::OR:
8689         case ISD::XOR: {
8690           NeedTruncation = true;
8691           ArithOp = Arith;
8692         }
8693       }
8694   }
8695
8696   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8697   // which may be the result of a CAST.  We use the variable 'Op', which is the
8698   // non-casted variable when we check for possible users.
8699   switch (ArithOp.getOpcode()) {
8700   case ISD::ADD:
8701     // Due to an isel shortcoming, be conservative if this add is likely to be
8702     // selected as part of a load-modify-store instruction. When the root node
8703     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8704     // uses of other nodes in the match, such as the ADD in this case. This
8705     // leads to the ADD being left around and reselected, with the result being
8706     // two adds in the output.  Alas, even if none our users are stores, that
8707     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8708     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8709     // climbing the DAG back to the root, and it doesn't seem to be worth the
8710     // effort.
8711     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8712          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8713       if (UI->getOpcode() != ISD::CopyToReg &&
8714           UI->getOpcode() != ISD::SETCC &&
8715           UI->getOpcode() != ISD::STORE)
8716         goto default_case;
8717
8718     if (ConstantSDNode *C =
8719         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8720       // An add of one will be selected as an INC.
8721       if (C->getAPIntValue() == 1) {
8722         Opcode = X86ISD::INC;
8723         NumOperands = 1;
8724         break;
8725       }
8726
8727       // An add of negative one (subtract of one) will be selected as a DEC.
8728       if (C->getAPIntValue().isAllOnesValue()) {
8729         Opcode = X86ISD::DEC;
8730         NumOperands = 1;
8731         break;
8732       }
8733     }
8734
8735     // Otherwise use a regular EFLAGS-setting add.
8736     Opcode = X86ISD::ADD;
8737     NumOperands = 2;
8738     break;
8739   case ISD::AND: {
8740     // If the primary and result isn't used, don't bother using X86ISD::AND,
8741     // because a TEST instruction will be better.
8742     bool NonFlagUse = false;
8743     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8744            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8745       SDNode *User = *UI;
8746       unsigned UOpNo = UI.getOperandNo();
8747       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8748         // Look pass truncate.
8749         UOpNo = User->use_begin().getOperandNo();
8750         User = *User->use_begin();
8751       }
8752
8753       if (User->getOpcode() != ISD::BRCOND &&
8754           User->getOpcode() != ISD::SETCC &&
8755           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8756         NonFlagUse = true;
8757         break;
8758       }
8759     }
8760
8761     if (!NonFlagUse)
8762       break;
8763   }
8764     // FALL THROUGH
8765   case ISD::SUB:
8766   case ISD::OR:
8767   case ISD::XOR:
8768     // Due to the ISEL shortcoming noted above, be conservative if this op is
8769     // likely to be selected as part of a load-modify-store instruction.
8770     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8771            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8772       if (UI->getOpcode() == ISD::STORE)
8773         goto default_case;
8774
8775     // Otherwise use a regular EFLAGS-setting instruction.
8776     switch (ArithOp.getOpcode()) {
8777     default: llvm_unreachable("unexpected operator!");
8778     case ISD::SUB: Opcode = X86ISD::SUB; break;
8779     case ISD::XOR: Opcode = X86ISD::XOR; break;
8780     case ISD::AND: Opcode = X86ISD::AND; break;
8781     case ISD::OR: {
8782       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8783         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8784         if (EFLAGS.getNode())
8785           return EFLAGS;
8786       }
8787       Opcode = X86ISD::OR;
8788       break;
8789     }
8790     }
8791
8792     NumOperands = 2;
8793     break;
8794   case X86ISD::ADD:
8795   case X86ISD::SUB:
8796   case X86ISD::INC:
8797   case X86ISD::DEC:
8798   case X86ISD::OR:
8799   case X86ISD::XOR:
8800   case X86ISD::AND:
8801     return SDValue(Op.getNode(), 1);
8802   default:
8803   default_case:
8804     break;
8805   }
8806
8807   // If we found that truncation is beneficial, perform the truncation and
8808   // update 'Op'.
8809   if (NeedTruncation) {
8810     EVT VT = Op.getValueType();
8811     SDValue WideVal = Op->getOperand(0);
8812     EVT WideVT = WideVal.getValueType();
8813     unsigned ConvertedOp = 0;
8814     // Use a target machine opcode to prevent further DAGCombine
8815     // optimizations that may separate the arithmetic operations
8816     // from the setcc node.
8817     switch (WideVal.getOpcode()) {
8818       default: break;
8819       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8820       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8821       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8822       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8823       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8824     }
8825
8826     if (ConvertedOp) {
8827       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8828       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8829         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8830         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8831         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8832       }
8833     }
8834   }
8835
8836   if (Opcode == 0)
8837     // Emit a CMP with 0, which is the TEST pattern.
8838     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8839                        DAG.getConstant(0, Op.getValueType()));
8840
8841   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8842   SmallVector<SDValue, 4> Ops;
8843   for (unsigned i = 0; i != NumOperands; ++i)
8844     Ops.push_back(Op.getOperand(i));
8845
8846   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8847   DAG.ReplaceAllUsesWith(Op, New);
8848   return SDValue(New.getNode(), 1);
8849 }
8850
8851 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8852 /// equivalent.
8853 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8854                                    SelectionDAG &DAG) const {
8855   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8856     if (C->getAPIntValue() == 0)
8857       return EmitTest(Op0, X86CC, DAG);
8858
8859   DebugLoc dl = Op0.getDebugLoc();
8860   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8861        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8862     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8863     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8864     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8865                               Op0, Op1);
8866     return SDValue(Sub.getNode(), 1);
8867   }
8868   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8869 }
8870
8871 /// Convert a comparison if required by the subtarget.
8872 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8873                                                  SelectionDAG &DAG) const {
8874   // If the subtarget does not support the FUCOMI instruction, floating-point
8875   // comparisons have to be converted.
8876   if (Subtarget->hasCMov() ||
8877       Cmp.getOpcode() != X86ISD::CMP ||
8878       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8879       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8880     return Cmp;
8881
8882   // The instruction selector will select an FUCOM instruction instead of
8883   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8884   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8885   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8886   DebugLoc dl = Cmp.getDebugLoc();
8887   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8888   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8889   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8890                             DAG.getConstant(8, MVT::i8));
8891   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8892   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8893 }
8894
8895 static bool isAllOnes(SDValue V) {
8896   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8897   return C && C->isAllOnesValue();
8898 }
8899
8900 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8901 /// if it's possible.
8902 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8903                                      DebugLoc dl, SelectionDAG &DAG) const {
8904   SDValue Op0 = And.getOperand(0);
8905   SDValue Op1 = And.getOperand(1);
8906   if (Op0.getOpcode() == ISD::TRUNCATE)
8907     Op0 = Op0.getOperand(0);
8908   if (Op1.getOpcode() == ISD::TRUNCATE)
8909     Op1 = Op1.getOperand(0);
8910
8911   SDValue LHS, RHS;
8912   if (Op1.getOpcode() == ISD::SHL)
8913     std::swap(Op0, Op1);
8914   if (Op0.getOpcode() == ISD::SHL) {
8915     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8916       if (And00C->getZExtValue() == 1) {
8917         // If we looked past a truncate, check that it's only truncating away
8918         // known zeros.
8919         unsigned BitWidth = Op0.getValueSizeInBits();
8920         unsigned AndBitWidth = And.getValueSizeInBits();
8921         if (BitWidth > AndBitWidth) {
8922           APInt Zeros, Ones;
8923           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8924           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8925             return SDValue();
8926         }
8927         LHS = Op1;
8928         RHS = Op0.getOperand(1);
8929       }
8930   } else if (Op1.getOpcode() == ISD::Constant) {
8931     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8932     uint64_t AndRHSVal = AndRHS->getZExtValue();
8933     SDValue AndLHS = Op0;
8934
8935     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8936       LHS = AndLHS.getOperand(0);
8937       RHS = AndLHS.getOperand(1);
8938     }
8939
8940     // Use BT if the immediate can't be encoded in a TEST instruction.
8941     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8942       LHS = AndLHS;
8943       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8944     }
8945   }
8946
8947   if (LHS.getNode()) {
8948     // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
8949     // the condition code later.
8950     bool Invert = false;
8951     if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
8952       Invert = true;
8953       LHS = LHS.getOperand(0);
8954     }
8955
8956     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8957     // instruction.  Since the shift amount is in-range-or-undefined, we know
8958     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8959     // the encoding for the i16 version is larger than the i32 version.
8960     // Also promote i16 to i32 for performance / code size reason.
8961     if (LHS.getValueType() == MVT::i8 ||
8962         LHS.getValueType() == MVT::i16)
8963       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8964
8965     // If the operand types disagree, extend the shift amount to match.  Since
8966     // BT ignores high bits (like shifts) we can use anyextend.
8967     if (LHS.getValueType() != RHS.getValueType())
8968       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8969
8970     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8971     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8972     // Flip the condition if the LHS was a not instruction
8973     if (Invert)
8974       Cond = X86::GetOppositeBranchCondition(Cond);
8975     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8976                        DAG.getConstant(Cond, MVT::i8), BT);
8977   }
8978
8979   return SDValue();
8980 }
8981
8982 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8983
8984   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8985
8986   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8987   SDValue Op0 = Op.getOperand(0);
8988   SDValue Op1 = Op.getOperand(1);
8989   DebugLoc dl = Op.getDebugLoc();
8990   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8991
8992   // Optimize to BT if possible.
8993   // Lower (X & (1 << N)) == 0 to BT(X, N).
8994   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8995   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8996   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8997       Op1.getOpcode() == ISD::Constant &&
8998       cast<ConstantSDNode>(Op1)->isNullValue() &&
8999       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9000     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9001     if (NewSetCC.getNode())
9002       return NewSetCC;
9003   }
9004
9005   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9006   // these.
9007   if (Op1.getOpcode() == ISD::Constant &&
9008       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9009        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9010       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9011
9012     // If the input is a setcc, then reuse the input setcc or use a new one with
9013     // the inverted condition.
9014     if (Op0.getOpcode() == X86ISD::SETCC) {
9015       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9016       bool Invert = (CC == ISD::SETNE) ^
9017         cast<ConstantSDNode>(Op1)->isNullValue();
9018       if (!Invert) return Op0;
9019
9020       CCode = X86::GetOppositeBranchCondition(CCode);
9021       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9022                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9023     }
9024   }
9025
9026   bool isFP = Op1.getValueType().isFloatingPoint();
9027   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9028   if (X86CC == X86::COND_INVALID)
9029     return SDValue();
9030
9031   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9032   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9033   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9034                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9035 }
9036
9037 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9038 // ones, and then concatenate the result back.
9039 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9040   EVT VT = Op.getValueType();
9041
9042   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9043          "Unsupported value type for operation");
9044
9045   unsigned NumElems = VT.getVectorNumElements();
9046   DebugLoc dl = Op.getDebugLoc();
9047   SDValue CC = Op.getOperand(2);
9048
9049   // Extract the LHS vectors
9050   SDValue LHS = Op.getOperand(0);
9051   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9052   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9053
9054   // Extract the RHS vectors
9055   SDValue RHS = Op.getOperand(1);
9056   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9057   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9058
9059   // Issue the operation on the smaller types and concatenate the result back
9060   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9061   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9062   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9063                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9064                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9065 }
9066
9067 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9068   SDValue Cond;
9069   SDValue Op0 = Op.getOperand(0);
9070   SDValue Op1 = Op.getOperand(1);
9071   SDValue CC = Op.getOperand(2);
9072   EVT VT = Op.getValueType();
9073   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9074   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9075   DebugLoc dl = Op.getDebugLoc();
9076
9077   if (isFP) {
9078 #ifndef NDEBUG
9079     EVT EltVT = Op0.getValueType().getVectorElementType();
9080     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9081 #endif
9082
9083     unsigned SSECC;
9084     bool Swap = false;
9085
9086     // SSE Condition code mapping:
9087     //  0 - EQ
9088     //  1 - LT
9089     //  2 - LE
9090     //  3 - UNORD
9091     //  4 - NEQ
9092     //  5 - NLT
9093     //  6 - NLE
9094     //  7 - ORD
9095     switch (SetCCOpcode) {
9096     default: llvm_unreachable("Unexpected SETCC condition");
9097     case ISD::SETOEQ:
9098     case ISD::SETEQ:  SSECC = 0; break;
9099     case ISD::SETOGT:
9100     case ISD::SETGT: Swap = true; // Fallthrough
9101     case ISD::SETLT:
9102     case ISD::SETOLT: SSECC = 1; break;
9103     case ISD::SETOGE:
9104     case ISD::SETGE: Swap = true; // Fallthrough
9105     case ISD::SETLE:
9106     case ISD::SETOLE: SSECC = 2; break;
9107     case ISD::SETUO:  SSECC = 3; break;
9108     case ISD::SETUNE:
9109     case ISD::SETNE:  SSECC = 4; break;
9110     case ISD::SETULE: Swap = true; // Fallthrough
9111     case ISD::SETUGE: SSECC = 5; break;
9112     case ISD::SETULT: Swap = true; // Fallthrough
9113     case ISD::SETUGT: SSECC = 6; break;
9114     case ISD::SETO:   SSECC = 7; break;
9115     case ISD::SETUEQ:
9116     case ISD::SETONE: SSECC = 8; break;
9117     }
9118     if (Swap)
9119       std::swap(Op0, Op1);
9120
9121     // In the two special cases we can't handle, emit two comparisons.
9122     if (SSECC == 8) {
9123       unsigned CC0, CC1;
9124       unsigned CombineOpc;
9125       if (SetCCOpcode == ISD::SETUEQ) {
9126         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9127       } else {
9128         assert(SetCCOpcode == ISD::SETONE);
9129         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9130       }
9131
9132       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9133                                  DAG.getConstant(CC0, MVT::i8));
9134       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9135                                  DAG.getConstant(CC1, MVT::i8));
9136       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9137     }
9138     // Handle all other FP comparisons here.
9139     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9140                        DAG.getConstant(SSECC, MVT::i8));
9141   }
9142
9143   // Break 256-bit integer vector compare into smaller ones.
9144   if (VT.is256BitVector() && !Subtarget->hasInt256())
9145     return Lower256IntVSETCC(Op, DAG);
9146
9147   // We are handling one of the integer comparisons here.  Since SSE only has
9148   // GT and EQ comparisons for integer, swapping operands and multiple
9149   // operations may be required for some comparisons.
9150   unsigned Opc;
9151   bool Swap = false, Invert = false, FlipSigns = false;
9152
9153   switch (SetCCOpcode) {
9154   default: llvm_unreachable("Unexpected SETCC condition");
9155   case ISD::SETNE:  Invert = true;
9156   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9157   case ISD::SETLT:  Swap = true;
9158   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9159   case ISD::SETGE:  Swap = true;
9160   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9161   case ISD::SETULT: Swap = true;
9162   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9163   case ISD::SETUGE: Swap = true;
9164   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9165   }
9166   if (Swap)
9167     std::swap(Op0, Op1);
9168
9169   // Check that the operation in question is available (most are plain SSE2,
9170   // but PCMPGTQ and PCMPEQQ have different requirements).
9171   if (VT == MVT::v2i64) {
9172     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9173       return SDValue();
9174     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9175       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9176       // pcmpeqd + pshufd + pand.
9177       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9178
9179       // First cast everything to the right type,
9180       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9181       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9182
9183       // Do the compare.
9184       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9185
9186       // Make sure the lower and upper halves are both all-ones.
9187       const int Mask[] = { 1, 0, 3, 2 };
9188       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9189       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9190
9191       if (Invert)
9192         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9193
9194       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9195     }
9196   }
9197
9198   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9199   // bits of the inputs before performing those operations.
9200   if (FlipSigns) {
9201     EVT EltVT = VT.getVectorElementType();
9202     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9203                                       EltVT);
9204     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9205     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9206                                     SignBits.size());
9207     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9208     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9209   }
9210
9211   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9212
9213   // If the logical-not of the result is required, perform that now.
9214   if (Invert)
9215     Result = DAG.getNOT(dl, Result, VT);
9216
9217   return Result;
9218 }
9219
9220 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9221 static bool isX86LogicalCmp(SDValue Op) {
9222   unsigned Opc = Op.getNode()->getOpcode();
9223   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9224       Opc == X86ISD::SAHF)
9225     return true;
9226   if (Op.getResNo() == 1 &&
9227       (Opc == X86ISD::ADD ||
9228        Opc == X86ISD::SUB ||
9229        Opc == X86ISD::ADC ||
9230        Opc == X86ISD::SBB ||
9231        Opc == X86ISD::SMUL ||
9232        Opc == X86ISD::UMUL ||
9233        Opc == X86ISD::INC ||
9234        Opc == X86ISD::DEC ||
9235        Opc == X86ISD::OR ||
9236        Opc == X86ISD::XOR ||
9237        Opc == X86ISD::AND))
9238     return true;
9239
9240   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9241     return true;
9242
9243   return false;
9244 }
9245
9246 static bool isZero(SDValue V) {
9247   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9248   return C && C->isNullValue();
9249 }
9250
9251 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9252   if (V.getOpcode() != ISD::TRUNCATE)
9253     return false;
9254
9255   SDValue VOp0 = V.getOperand(0);
9256   unsigned InBits = VOp0.getValueSizeInBits();
9257   unsigned Bits = V.getValueSizeInBits();
9258   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9259 }
9260
9261 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9262   bool addTest = true;
9263   SDValue Cond  = Op.getOperand(0);
9264   SDValue Op1 = Op.getOperand(1);
9265   SDValue Op2 = Op.getOperand(2);
9266   DebugLoc DL = Op.getDebugLoc();
9267   SDValue CC;
9268
9269   if (Cond.getOpcode() == ISD::SETCC) {
9270     SDValue NewCond = LowerSETCC(Cond, DAG);
9271     if (NewCond.getNode())
9272       Cond = NewCond;
9273   }
9274
9275   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9276   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9277   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9278   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9279   if (Cond.getOpcode() == X86ISD::SETCC &&
9280       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9281       isZero(Cond.getOperand(1).getOperand(1))) {
9282     SDValue Cmp = Cond.getOperand(1);
9283
9284     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9285
9286     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9287         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9288       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9289
9290       SDValue CmpOp0 = Cmp.getOperand(0);
9291       // Apply further optimizations for special cases
9292       // (select (x != 0), -1, 0) -> neg & sbb
9293       // (select (x == 0), 0, -1) -> neg & sbb
9294       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9295         if (YC->isNullValue() &&
9296             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9297           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9298           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9299                                     DAG.getConstant(0, CmpOp0.getValueType()),
9300                                     CmpOp0);
9301           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9302                                     DAG.getConstant(X86::COND_B, MVT::i8),
9303                                     SDValue(Neg.getNode(), 1));
9304           return Res;
9305         }
9306
9307       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9308                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9309       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9310
9311       SDValue Res =   // Res = 0 or -1.
9312         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9313                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9314
9315       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9316         Res = DAG.getNOT(DL, Res, Res.getValueType());
9317
9318       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9319       if (N2C == 0 || !N2C->isNullValue())
9320         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9321       return Res;
9322     }
9323   }
9324
9325   // Look past (and (setcc_carry (cmp ...)), 1).
9326   if (Cond.getOpcode() == ISD::AND &&
9327       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9328     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9329     if (C && C->getAPIntValue() == 1)
9330       Cond = Cond.getOperand(0);
9331   }
9332
9333   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9334   // setting operand in place of the X86ISD::SETCC.
9335   unsigned CondOpcode = Cond.getOpcode();
9336   if (CondOpcode == X86ISD::SETCC ||
9337       CondOpcode == X86ISD::SETCC_CARRY) {
9338     CC = Cond.getOperand(0);
9339
9340     SDValue Cmp = Cond.getOperand(1);
9341     unsigned Opc = Cmp.getOpcode();
9342     EVT VT = Op.getValueType();
9343
9344     bool IllegalFPCMov = false;
9345     if (VT.isFloatingPoint() && !VT.isVector() &&
9346         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9347       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9348
9349     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9350         Opc == X86ISD::BT) { // FIXME
9351       Cond = Cmp;
9352       addTest = false;
9353     }
9354   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9355              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9356              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9357               Cond.getOperand(0).getValueType() != MVT::i8)) {
9358     SDValue LHS = Cond.getOperand(0);
9359     SDValue RHS = Cond.getOperand(1);
9360     unsigned X86Opcode;
9361     unsigned X86Cond;
9362     SDVTList VTs;
9363     switch (CondOpcode) {
9364     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9365     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9366     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9367     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9368     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9369     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9370     default: llvm_unreachable("unexpected overflowing operator");
9371     }
9372     if (CondOpcode == ISD::UMULO)
9373       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9374                           MVT::i32);
9375     else
9376       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9377
9378     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9379
9380     if (CondOpcode == ISD::UMULO)
9381       Cond = X86Op.getValue(2);
9382     else
9383       Cond = X86Op.getValue(1);
9384
9385     CC = DAG.getConstant(X86Cond, MVT::i8);
9386     addTest = false;
9387   }
9388
9389   if (addTest) {
9390     // Look pass the truncate if the high bits are known zero.
9391     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9392         Cond = Cond.getOperand(0);
9393
9394     // We know the result of AND is compared against zero. Try to match
9395     // it to BT.
9396     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9397       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9398       if (NewSetCC.getNode()) {
9399         CC = NewSetCC.getOperand(0);
9400         Cond = NewSetCC.getOperand(1);
9401         addTest = false;
9402       }
9403     }
9404   }
9405
9406   if (addTest) {
9407     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9408     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9409   }
9410
9411   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9412   // a <  b ?  0 : -1 -> RES = setcc_carry
9413   // a >= b ? -1 :  0 -> RES = setcc_carry
9414   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9415   if (Cond.getOpcode() == X86ISD::SUB) {
9416     Cond = ConvertCmpIfNecessary(Cond, DAG);
9417     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9418
9419     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9420         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9421       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9422                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9423       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9424         return DAG.getNOT(DL, Res, Res.getValueType());
9425       return Res;
9426     }
9427   }
9428
9429   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9430   // widen the cmov and push the truncate through. This avoids introducing a new
9431   // branch during isel and doesn't add any extensions.
9432   if (Op.getValueType() == MVT::i8 &&
9433       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9434     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9435     if (T1.getValueType() == T2.getValueType() &&
9436         // Blacklist CopyFromReg to avoid partial register stalls.
9437         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9438       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9439       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9440       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9441     }
9442   }
9443
9444   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9445   // condition is true.
9446   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9447   SDValue Ops[] = { Op2, Op1, CC, Cond };
9448   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9449 }
9450
9451 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9452 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9453 // from the AND / OR.
9454 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9455   Opc = Op.getOpcode();
9456   if (Opc != ISD::OR && Opc != ISD::AND)
9457     return false;
9458   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9459           Op.getOperand(0).hasOneUse() &&
9460           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9461           Op.getOperand(1).hasOneUse());
9462 }
9463
9464 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9465 // 1 and that the SETCC node has a single use.
9466 static bool isXor1OfSetCC(SDValue Op) {
9467   if (Op.getOpcode() != ISD::XOR)
9468     return false;
9469   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9470   if (N1C && N1C->getAPIntValue() == 1) {
9471     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9472       Op.getOperand(0).hasOneUse();
9473   }
9474   return false;
9475 }
9476
9477 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9478   bool addTest = true;
9479   SDValue Chain = Op.getOperand(0);
9480   SDValue Cond  = Op.getOperand(1);
9481   SDValue Dest  = Op.getOperand(2);
9482   DebugLoc dl = Op.getDebugLoc();
9483   SDValue CC;
9484   bool Inverted = false;
9485
9486   if (Cond.getOpcode() == ISD::SETCC) {
9487     // Check for setcc([su]{add,sub,mul}o == 0).
9488     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9489         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9490         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9491         Cond.getOperand(0).getResNo() == 1 &&
9492         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9493          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9494          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9495          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9496          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9497          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9498       Inverted = true;
9499       Cond = Cond.getOperand(0);
9500     } else {
9501       SDValue NewCond = LowerSETCC(Cond, DAG);
9502       if (NewCond.getNode())
9503         Cond = NewCond;
9504     }
9505   }
9506 #if 0
9507   // FIXME: LowerXALUO doesn't handle these!!
9508   else if (Cond.getOpcode() == X86ISD::ADD  ||
9509            Cond.getOpcode() == X86ISD::SUB  ||
9510            Cond.getOpcode() == X86ISD::SMUL ||
9511            Cond.getOpcode() == X86ISD::UMUL)
9512     Cond = LowerXALUO(Cond, DAG);
9513 #endif
9514
9515   // Look pass (and (setcc_carry (cmp ...)), 1).
9516   if (Cond.getOpcode() == ISD::AND &&
9517       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9518     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9519     if (C && C->getAPIntValue() == 1)
9520       Cond = Cond.getOperand(0);
9521   }
9522
9523   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9524   // setting operand in place of the X86ISD::SETCC.
9525   unsigned CondOpcode = Cond.getOpcode();
9526   if (CondOpcode == X86ISD::SETCC ||
9527       CondOpcode == X86ISD::SETCC_CARRY) {
9528     CC = Cond.getOperand(0);
9529
9530     SDValue Cmp = Cond.getOperand(1);
9531     unsigned Opc = Cmp.getOpcode();
9532     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9533     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9534       Cond = Cmp;
9535       addTest = false;
9536     } else {
9537       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9538       default: break;
9539       case X86::COND_O:
9540       case X86::COND_B:
9541         // These can only come from an arithmetic instruction with overflow,
9542         // e.g. SADDO, UADDO.
9543         Cond = Cond.getNode()->getOperand(1);
9544         addTest = false;
9545         break;
9546       }
9547     }
9548   }
9549   CondOpcode = Cond.getOpcode();
9550   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9551       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9552       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9553        Cond.getOperand(0).getValueType() != MVT::i8)) {
9554     SDValue LHS = Cond.getOperand(0);
9555     SDValue RHS = Cond.getOperand(1);
9556     unsigned X86Opcode;
9557     unsigned X86Cond;
9558     SDVTList VTs;
9559     switch (CondOpcode) {
9560     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9561     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9562     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9563     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9564     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9565     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9566     default: llvm_unreachable("unexpected overflowing operator");
9567     }
9568     if (Inverted)
9569       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9570     if (CondOpcode == ISD::UMULO)
9571       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9572                           MVT::i32);
9573     else
9574       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9575
9576     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9577
9578     if (CondOpcode == ISD::UMULO)
9579       Cond = X86Op.getValue(2);
9580     else
9581       Cond = X86Op.getValue(1);
9582
9583     CC = DAG.getConstant(X86Cond, MVT::i8);
9584     addTest = false;
9585   } else {
9586     unsigned CondOpc;
9587     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9588       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9589       if (CondOpc == ISD::OR) {
9590         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9591         // two branches instead of an explicit OR instruction with a
9592         // separate test.
9593         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9594             isX86LogicalCmp(Cmp)) {
9595           CC = Cond.getOperand(0).getOperand(0);
9596           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9597                               Chain, Dest, CC, Cmp);
9598           CC = Cond.getOperand(1).getOperand(0);
9599           Cond = Cmp;
9600           addTest = false;
9601         }
9602       } else { // ISD::AND
9603         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9604         // two branches instead of an explicit AND instruction with a
9605         // separate test. However, we only do this if this block doesn't
9606         // have a fall-through edge, because this requires an explicit
9607         // jmp when the condition is false.
9608         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9609             isX86LogicalCmp(Cmp) &&
9610             Op.getNode()->hasOneUse()) {
9611           X86::CondCode CCode =
9612             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9613           CCode = X86::GetOppositeBranchCondition(CCode);
9614           CC = DAG.getConstant(CCode, MVT::i8);
9615           SDNode *User = *Op.getNode()->use_begin();
9616           // Look for an unconditional branch following this conditional branch.
9617           // We need this because we need to reverse the successors in order
9618           // to implement FCMP_OEQ.
9619           if (User->getOpcode() == ISD::BR) {
9620             SDValue FalseBB = User->getOperand(1);
9621             SDNode *NewBR =
9622               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9623             assert(NewBR == User);
9624             (void)NewBR;
9625             Dest = FalseBB;
9626
9627             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9628                                 Chain, Dest, CC, Cmp);
9629             X86::CondCode CCode =
9630               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9631             CCode = X86::GetOppositeBranchCondition(CCode);
9632             CC = DAG.getConstant(CCode, MVT::i8);
9633             Cond = Cmp;
9634             addTest = false;
9635           }
9636         }
9637       }
9638     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9639       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9640       // It should be transformed during dag combiner except when the condition
9641       // is set by a arithmetics with overflow node.
9642       X86::CondCode CCode =
9643         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9644       CCode = X86::GetOppositeBranchCondition(CCode);
9645       CC = DAG.getConstant(CCode, MVT::i8);
9646       Cond = Cond.getOperand(0).getOperand(1);
9647       addTest = false;
9648     } else if (Cond.getOpcode() == ISD::SETCC &&
9649                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9650       // For FCMP_OEQ, we can emit
9651       // two branches instead of an explicit AND instruction with a
9652       // separate test. However, we only do this if this block doesn't
9653       // have a fall-through edge, because this requires an explicit
9654       // jmp when the condition is false.
9655       if (Op.getNode()->hasOneUse()) {
9656         SDNode *User = *Op.getNode()->use_begin();
9657         // Look for an unconditional branch following this conditional branch.
9658         // We need this because we need to reverse the successors in order
9659         // to implement FCMP_OEQ.
9660         if (User->getOpcode() == ISD::BR) {
9661           SDValue FalseBB = User->getOperand(1);
9662           SDNode *NewBR =
9663             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9664           assert(NewBR == User);
9665           (void)NewBR;
9666           Dest = FalseBB;
9667
9668           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9669                                     Cond.getOperand(0), Cond.getOperand(1));
9670           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9671           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9672           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9673                               Chain, Dest, CC, Cmp);
9674           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9675           Cond = Cmp;
9676           addTest = false;
9677         }
9678       }
9679     } else if (Cond.getOpcode() == ISD::SETCC &&
9680                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9681       // For FCMP_UNE, we can emit
9682       // two branches instead of an explicit AND instruction with a
9683       // separate test. However, we only do this if this block doesn't
9684       // have a fall-through edge, because this requires an explicit
9685       // jmp when the condition is false.
9686       if (Op.getNode()->hasOneUse()) {
9687         SDNode *User = *Op.getNode()->use_begin();
9688         // Look for an unconditional branch following this conditional branch.
9689         // We need this because we need to reverse the successors in order
9690         // to implement FCMP_UNE.
9691         if (User->getOpcode() == ISD::BR) {
9692           SDValue FalseBB = User->getOperand(1);
9693           SDNode *NewBR =
9694             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9695           assert(NewBR == User);
9696           (void)NewBR;
9697
9698           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9699                                     Cond.getOperand(0), Cond.getOperand(1));
9700           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9701           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9702           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9703                               Chain, Dest, CC, Cmp);
9704           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9705           Cond = Cmp;
9706           addTest = false;
9707           Dest = FalseBB;
9708         }
9709       }
9710     }
9711   }
9712
9713   if (addTest) {
9714     // Look pass the truncate if the high bits are known zero.
9715     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9716         Cond = Cond.getOperand(0);
9717
9718     // We know the result of AND is compared against zero. Try to match
9719     // it to BT.
9720     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9721       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9722       if (NewSetCC.getNode()) {
9723         CC = NewSetCC.getOperand(0);
9724         Cond = NewSetCC.getOperand(1);
9725         addTest = false;
9726       }
9727     }
9728   }
9729
9730   if (addTest) {
9731     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9732     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9733   }
9734   Cond = ConvertCmpIfNecessary(Cond, DAG);
9735   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9736                      Chain, Dest, CC, Cond);
9737 }
9738
9739 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9740 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9741 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9742 // that the guard pages used by the OS virtual memory manager are allocated in
9743 // correct sequence.
9744 SDValue
9745 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9746                                            SelectionDAG &DAG) const {
9747   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9748           getTargetMachine().Options.EnableSegmentedStacks) &&
9749          "This should be used only on Windows targets or when segmented stacks "
9750          "are being used");
9751   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9752   DebugLoc dl = Op.getDebugLoc();
9753
9754   // Get the inputs.
9755   SDValue Chain = Op.getOperand(0);
9756   SDValue Size  = Op.getOperand(1);
9757   // FIXME: Ensure alignment here
9758
9759   bool Is64Bit = Subtarget->is64Bit();
9760   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9761
9762   if (getTargetMachine().Options.EnableSegmentedStacks) {
9763     MachineFunction &MF = DAG.getMachineFunction();
9764     MachineRegisterInfo &MRI = MF.getRegInfo();
9765
9766     if (Is64Bit) {
9767       // The 64 bit implementation of segmented stacks needs to clobber both r10
9768       // r11. This makes it impossible to use it along with nested parameters.
9769       const Function *F = MF.getFunction();
9770
9771       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9772            I != E; ++I)
9773         if (I->hasNestAttr())
9774           report_fatal_error("Cannot use segmented stacks with functions that "
9775                              "have nested arguments.");
9776     }
9777
9778     const TargetRegisterClass *AddrRegClass =
9779       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9780     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9781     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9782     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9783                                 DAG.getRegister(Vreg, SPTy));
9784     SDValue Ops1[2] = { Value, Chain };
9785     return DAG.getMergeValues(Ops1, 2, dl);
9786   } else {
9787     SDValue Flag;
9788     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9789
9790     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9791     Flag = Chain.getValue(1);
9792     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9793
9794     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9795     Flag = Chain.getValue(1);
9796
9797     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
9798                                SPTy).getValue(1);
9799
9800     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9801     return DAG.getMergeValues(Ops1, 2, dl);
9802   }
9803 }
9804
9805 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9806   MachineFunction &MF = DAG.getMachineFunction();
9807   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9808
9809   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9810   DebugLoc DL = Op.getDebugLoc();
9811
9812   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9813     // vastart just stores the address of the VarArgsFrameIndex slot into the
9814     // memory location argument.
9815     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9816                                    getPointerTy());
9817     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9818                         MachinePointerInfo(SV), false, false, 0);
9819   }
9820
9821   // __va_list_tag:
9822   //   gp_offset         (0 - 6 * 8)
9823   //   fp_offset         (48 - 48 + 8 * 16)
9824   //   overflow_arg_area (point to parameters coming in memory).
9825   //   reg_save_area
9826   SmallVector<SDValue, 8> MemOps;
9827   SDValue FIN = Op.getOperand(1);
9828   // Store gp_offset
9829   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9830                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9831                                                MVT::i32),
9832                                FIN, MachinePointerInfo(SV), false, false, 0);
9833   MemOps.push_back(Store);
9834
9835   // Store fp_offset
9836   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9837                     FIN, DAG.getIntPtrConstant(4));
9838   Store = DAG.getStore(Op.getOperand(0), DL,
9839                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9840                                        MVT::i32),
9841                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9842   MemOps.push_back(Store);
9843
9844   // Store ptr to overflow_arg_area
9845   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9846                     FIN, DAG.getIntPtrConstant(4));
9847   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9848                                     getPointerTy());
9849   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9850                        MachinePointerInfo(SV, 8),
9851                        false, false, 0);
9852   MemOps.push_back(Store);
9853
9854   // Store ptr to reg_save_area.
9855   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9856                     FIN, DAG.getIntPtrConstant(8));
9857   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9858                                     getPointerTy());
9859   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9860                        MachinePointerInfo(SV, 16), false, false, 0);
9861   MemOps.push_back(Store);
9862   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9863                      &MemOps[0], MemOps.size());
9864 }
9865
9866 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9867   assert(Subtarget->is64Bit() &&
9868          "LowerVAARG only handles 64-bit va_arg!");
9869   assert((Subtarget->isTargetLinux() ||
9870           Subtarget->isTargetDarwin()) &&
9871           "Unhandled target in LowerVAARG");
9872   assert(Op.getNode()->getNumOperands() == 4);
9873   SDValue Chain = Op.getOperand(0);
9874   SDValue SrcPtr = Op.getOperand(1);
9875   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9876   unsigned Align = Op.getConstantOperandVal(3);
9877   DebugLoc dl = Op.getDebugLoc();
9878
9879   EVT ArgVT = Op.getNode()->getValueType(0);
9880   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9881   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9882   uint8_t ArgMode;
9883
9884   // Decide which area this value should be read from.
9885   // TODO: Implement the AMD64 ABI in its entirety. This simple
9886   // selection mechanism works only for the basic types.
9887   if (ArgVT == MVT::f80) {
9888     llvm_unreachable("va_arg for f80 not yet implemented");
9889   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9890     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9891   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9892     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9893   } else {
9894     llvm_unreachable("Unhandled argument type in LowerVAARG");
9895   }
9896
9897   if (ArgMode == 2) {
9898     // Sanity Check: Make sure using fp_offset makes sense.
9899     assert(!getTargetMachine().Options.UseSoftFloat &&
9900            !(DAG.getMachineFunction()
9901                 .getFunction()->getFnAttributes()
9902                 .hasAttribute(Attribute::NoImplicitFloat)) &&
9903            Subtarget->hasSSE1());
9904   }
9905
9906   // Insert VAARG_64 node into the DAG
9907   // VAARG_64 returns two values: Variable Argument Address, Chain
9908   SmallVector<SDValue, 11> InstOps;
9909   InstOps.push_back(Chain);
9910   InstOps.push_back(SrcPtr);
9911   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9912   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9913   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9914   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9915   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9916                                           VTs, &InstOps[0], InstOps.size(),
9917                                           MVT::i64,
9918                                           MachinePointerInfo(SV),
9919                                           /*Align=*/0,
9920                                           /*Volatile=*/false,
9921                                           /*ReadMem=*/true,
9922                                           /*WriteMem=*/true);
9923   Chain = VAARG.getValue(1);
9924
9925   // Load the next argument and return it
9926   return DAG.getLoad(ArgVT, dl,
9927                      Chain,
9928                      VAARG,
9929                      MachinePointerInfo(),
9930                      false, false, false, 0);
9931 }
9932
9933 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9934                            SelectionDAG &DAG) {
9935   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9936   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9937   SDValue Chain = Op.getOperand(0);
9938   SDValue DstPtr = Op.getOperand(1);
9939   SDValue SrcPtr = Op.getOperand(2);
9940   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9941   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9942   DebugLoc DL = Op.getDebugLoc();
9943
9944   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9945                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9946                        false,
9947                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9948 }
9949
9950 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9951 // may or may not be a constant. Takes immediate version of shift as input.
9952 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9953                                    SDValue SrcOp, SDValue ShAmt,
9954                                    SelectionDAG &DAG) {
9955   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9956
9957   if (isa<ConstantSDNode>(ShAmt)) {
9958     // Constant may be a TargetConstant. Use a regular constant.
9959     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9960     switch (Opc) {
9961       default: llvm_unreachable("Unknown target vector shift node");
9962       case X86ISD::VSHLI:
9963       case X86ISD::VSRLI:
9964       case X86ISD::VSRAI:
9965         return DAG.getNode(Opc, dl, VT, SrcOp,
9966                            DAG.getConstant(ShiftAmt, MVT::i32));
9967     }
9968   }
9969
9970   // Change opcode to non-immediate version
9971   switch (Opc) {
9972     default: llvm_unreachable("Unknown target vector shift node");
9973     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9974     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9975     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9976   }
9977
9978   // Need to build a vector containing shift amount
9979   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9980   SDValue ShOps[4];
9981   ShOps[0] = ShAmt;
9982   ShOps[1] = DAG.getConstant(0, MVT::i32);
9983   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9984   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9985
9986   // The return type has to be a 128-bit type with the same element
9987   // type as the input type.
9988   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9989   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9990
9991   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9992   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9993 }
9994
9995 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9996   DebugLoc dl = Op.getDebugLoc();
9997   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9998   switch (IntNo) {
9999   default: return SDValue();    // Don't custom lower most intrinsics.
10000   // Comparison intrinsics.
10001   case Intrinsic::x86_sse_comieq_ss:
10002   case Intrinsic::x86_sse_comilt_ss:
10003   case Intrinsic::x86_sse_comile_ss:
10004   case Intrinsic::x86_sse_comigt_ss:
10005   case Intrinsic::x86_sse_comige_ss:
10006   case Intrinsic::x86_sse_comineq_ss:
10007   case Intrinsic::x86_sse_ucomieq_ss:
10008   case Intrinsic::x86_sse_ucomilt_ss:
10009   case Intrinsic::x86_sse_ucomile_ss:
10010   case Intrinsic::x86_sse_ucomigt_ss:
10011   case Intrinsic::x86_sse_ucomige_ss:
10012   case Intrinsic::x86_sse_ucomineq_ss:
10013   case Intrinsic::x86_sse2_comieq_sd:
10014   case Intrinsic::x86_sse2_comilt_sd:
10015   case Intrinsic::x86_sse2_comile_sd:
10016   case Intrinsic::x86_sse2_comigt_sd:
10017   case Intrinsic::x86_sse2_comige_sd:
10018   case Intrinsic::x86_sse2_comineq_sd:
10019   case Intrinsic::x86_sse2_ucomieq_sd:
10020   case Intrinsic::x86_sse2_ucomilt_sd:
10021   case Intrinsic::x86_sse2_ucomile_sd:
10022   case Intrinsic::x86_sse2_ucomigt_sd:
10023   case Intrinsic::x86_sse2_ucomige_sd:
10024   case Intrinsic::x86_sse2_ucomineq_sd: {
10025     unsigned Opc;
10026     ISD::CondCode CC;
10027     switch (IntNo) {
10028     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10029     case Intrinsic::x86_sse_comieq_ss:
10030     case Intrinsic::x86_sse2_comieq_sd:
10031       Opc = X86ISD::COMI;
10032       CC = ISD::SETEQ;
10033       break;
10034     case Intrinsic::x86_sse_comilt_ss:
10035     case Intrinsic::x86_sse2_comilt_sd:
10036       Opc = X86ISD::COMI;
10037       CC = ISD::SETLT;
10038       break;
10039     case Intrinsic::x86_sse_comile_ss:
10040     case Intrinsic::x86_sse2_comile_sd:
10041       Opc = X86ISD::COMI;
10042       CC = ISD::SETLE;
10043       break;
10044     case Intrinsic::x86_sse_comigt_ss:
10045     case Intrinsic::x86_sse2_comigt_sd:
10046       Opc = X86ISD::COMI;
10047       CC = ISD::SETGT;
10048       break;
10049     case Intrinsic::x86_sse_comige_ss:
10050     case Intrinsic::x86_sse2_comige_sd:
10051       Opc = X86ISD::COMI;
10052       CC = ISD::SETGE;
10053       break;
10054     case Intrinsic::x86_sse_comineq_ss:
10055     case Intrinsic::x86_sse2_comineq_sd:
10056       Opc = X86ISD::COMI;
10057       CC = ISD::SETNE;
10058       break;
10059     case Intrinsic::x86_sse_ucomieq_ss:
10060     case Intrinsic::x86_sse2_ucomieq_sd:
10061       Opc = X86ISD::UCOMI;
10062       CC = ISD::SETEQ;
10063       break;
10064     case Intrinsic::x86_sse_ucomilt_ss:
10065     case Intrinsic::x86_sse2_ucomilt_sd:
10066       Opc = X86ISD::UCOMI;
10067       CC = ISD::SETLT;
10068       break;
10069     case Intrinsic::x86_sse_ucomile_ss:
10070     case Intrinsic::x86_sse2_ucomile_sd:
10071       Opc = X86ISD::UCOMI;
10072       CC = ISD::SETLE;
10073       break;
10074     case Intrinsic::x86_sse_ucomigt_ss:
10075     case Intrinsic::x86_sse2_ucomigt_sd:
10076       Opc = X86ISD::UCOMI;
10077       CC = ISD::SETGT;
10078       break;
10079     case Intrinsic::x86_sse_ucomige_ss:
10080     case Intrinsic::x86_sse2_ucomige_sd:
10081       Opc = X86ISD::UCOMI;
10082       CC = ISD::SETGE;
10083       break;
10084     case Intrinsic::x86_sse_ucomineq_ss:
10085     case Intrinsic::x86_sse2_ucomineq_sd:
10086       Opc = X86ISD::UCOMI;
10087       CC = ISD::SETNE;
10088       break;
10089     }
10090
10091     SDValue LHS = Op.getOperand(1);
10092     SDValue RHS = Op.getOperand(2);
10093     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10094     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10095     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10096     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10097                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10098     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10099   }
10100
10101   // Arithmetic intrinsics.
10102   case Intrinsic::x86_sse2_pmulu_dq:
10103   case Intrinsic::x86_avx2_pmulu_dq:
10104     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10105                        Op.getOperand(1), Op.getOperand(2));
10106
10107   // SSE2/AVX2 sub with unsigned saturation intrinsics
10108   case Intrinsic::x86_sse2_psubus_b:
10109   case Intrinsic::x86_sse2_psubus_w:
10110   case Intrinsic::x86_avx2_psubus_b:
10111   case Intrinsic::x86_avx2_psubus_w:
10112     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10113                        Op.getOperand(1), Op.getOperand(2));
10114
10115   // SSE3/AVX horizontal add/sub intrinsics
10116   case Intrinsic::x86_sse3_hadd_ps:
10117   case Intrinsic::x86_sse3_hadd_pd:
10118   case Intrinsic::x86_avx_hadd_ps_256:
10119   case Intrinsic::x86_avx_hadd_pd_256:
10120   case Intrinsic::x86_sse3_hsub_ps:
10121   case Intrinsic::x86_sse3_hsub_pd:
10122   case Intrinsic::x86_avx_hsub_ps_256:
10123   case Intrinsic::x86_avx_hsub_pd_256:
10124   case Intrinsic::x86_ssse3_phadd_w_128:
10125   case Intrinsic::x86_ssse3_phadd_d_128:
10126   case Intrinsic::x86_avx2_phadd_w:
10127   case Intrinsic::x86_avx2_phadd_d:
10128   case Intrinsic::x86_ssse3_phsub_w_128:
10129   case Intrinsic::x86_ssse3_phsub_d_128:
10130   case Intrinsic::x86_avx2_phsub_w:
10131   case Intrinsic::x86_avx2_phsub_d: {
10132     unsigned Opcode;
10133     switch (IntNo) {
10134     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10135     case Intrinsic::x86_sse3_hadd_ps:
10136     case Intrinsic::x86_sse3_hadd_pd:
10137     case Intrinsic::x86_avx_hadd_ps_256:
10138     case Intrinsic::x86_avx_hadd_pd_256:
10139       Opcode = X86ISD::FHADD;
10140       break;
10141     case Intrinsic::x86_sse3_hsub_ps:
10142     case Intrinsic::x86_sse3_hsub_pd:
10143     case Intrinsic::x86_avx_hsub_ps_256:
10144     case Intrinsic::x86_avx_hsub_pd_256:
10145       Opcode = X86ISD::FHSUB;
10146       break;
10147     case Intrinsic::x86_ssse3_phadd_w_128:
10148     case Intrinsic::x86_ssse3_phadd_d_128:
10149     case Intrinsic::x86_avx2_phadd_w:
10150     case Intrinsic::x86_avx2_phadd_d:
10151       Opcode = X86ISD::HADD;
10152       break;
10153     case Intrinsic::x86_ssse3_phsub_w_128:
10154     case Intrinsic::x86_ssse3_phsub_d_128:
10155     case Intrinsic::x86_avx2_phsub_w:
10156     case Intrinsic::x86_avx2_phsub_d:
10157       Opcode = X86ISD::HSUB;
10158       break;
10159     }
10160     return DAG.getNode(Opcode, dl, Op.getValueType(),
10161                        Op.getOperand(1), Op.getOperand(2));
10162   }
10163
10164   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10165   case Intrinsic::x86_sse2_pmaxu_b:
10166   case Intrinsic::x86_sse41_pmaxuw:
10167   case Intrinsic::x86_sse41_pmaxud:
10168   case Intrinsic::x86_avx2_pmaxu_b:
10169   case Intrinsic::x86_avx2_pmaxu_w:
10170   case Intrinsic::x86_avx2_pmaxu_d:
10171     return DAG.getNode(X86ISD::UMAX, dl, Op.getValueType(),
10172                        Op.getOperand(1), Op.getOperand(2));
10173   case Intrinsic::x86_sse2_pminu_b:
10174   case Intrinsic::x86_sse41_pminuw:
10175   case Intrinsic::x86_sse41_pminud:
10176   case Intrinsic::x86_avx2_pminu_b:
10177   case Intrinsic::x86_avx2_pminu_w:
10178   case Intrinsic::x86_avx2_pminu_d:
10179     return DAG.getNode(X86ISD::UMIN, dl, Op.getValueType(),
10180                        Op.getOperand(1), Op.getOperand(2));
10181   case Intrinsic::x86_sse41_pmaxsb:
10182   case Intrinsic::x86_sse2_pmaxs_w:
10183   case Intrinsic::x86_sse41_pmaxsd:
10184   case Intrinsic::x86_avx2_pmaxs_b:
10185   case Intrinsic::x86_avx2_pmaxs_w:
10186   case Intrinsic::x86_avx2_pmaxs_d:
10187     return DAG.getNode(X86ISD::SMAX, dl, Op.getValueType(),
10188                        Op.getOperand(1), Op.getOperand(2));
10189   case Intrinsic::x86_sse41_pminsb:
10190   case Intrinsic::x86_sse2_pmins_w:
10191   case Intrinsic::x86_sse41_pminsd:
10192   case Intrinsic::x86_avx2_pmins_b:
10193   case Intrinsic::x86_avx2_pmins_w:
10194   case Intrinsic::x86_avx2_pmins_d:
10195     return DAG.getNode(X86ISD::SMIN, dl, Op.getValueType(),
10196                        Op.getOperand(1), Op.getOperand(2));
10197
10198   // AVX2 variable shift intrinsics
10199   case Intrinsic::x86_avx2_psllv_d:
10200   case Intrinsic::x86_avx2_psllv_q:
10201   case Intrinsic::x86_avx2_psllv_d_256:
10202   case Intrinsic::x86_avx2_psllv_q_256:
10203   case Intrinsic::x86_avx2_psrlv_d:
10204   case Intrinsic::x86_avx2_psrlv_q:
10205   case Intrinsic::x86_avx2_psrlv_d_256:
10206   case Intrinsic::x86_avx2_psrlv_q_256:
10207   case Intrinsic::x86_avx2_psrav_d:
10208   case Intrinsic::x86_avx2_psrav_d_256: {
10209     unsigned Opcode;
10210     switch (IntNo) {
10211     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10212     case Intrinsic::x86_avx2_psllv_d:
10213     case Intrinsic::x86_avx2_psllv_q:
10214     case Intrinsic::x86_avx2_psllv_d_256:
10215     case Intrinsic::x86_avx2_psllv_q_256:
10216       Opcode = ISD::SHL;
10217       break;
10218     case Intrinsic::x86_avx2_psrlv_d:
10219     case Intrinsic::x86_avx2_psrlv_q:
10220     case Intrinsic::x86_avx2_psrlv_d_256:
10221     case Intrinsic::x86_avx2_psrlv_q_256:
10222       Opcode = ISD::SRL;
10223       break;
10224     case Intrinsic::x86_avx2_psrav_d:
10225     case Intrinsic::x86_avx2_psrav_d_256:
10226       Opcode = ISD::SRA;
10227       break;
10228     }
10229     return DAG.getNode(Opcode, dl, Op.getValueType(),
10230                        Op.getOperand(1), Op.getOperand(2));
10231   }
10232
10233   case Intrinsic::x86_ssse3_pshuf_b_128:
10234   case Intrinsic::x86_avx2_pshuf_b:
10235     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10236                        Op.getOperand(1), Op.getOperand(2));
10237
10238   case Intrinsic::x86_ssse3_psign_b_128:
10239   case Intrinsic::x86_ssse3_psign_w_128:
10240   case Intrinsic::x86_ssse3_psign_d_128:
10241   case Intrinsic::x86_avx2_psign_b:
10242   case Intrinsic::x86_avx2_psign_w:
10243   case Intrinsic::x86_avx2_psign_d:
10244     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10245                        Op.getOperand(1), Op.getOperand(2));
10246
10247   case Intrinsic::x86_sse41_insertps:
10248     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10249                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10250
10251   case Intrinsic::x86_avx_vperm2f128_ps_256:
10252   case Intrinsic::x86_avx_vperm2f128_pd_256:
10253   case Intrinsic::x86_avx_vperm2f128_si_256:
10254   case Intrinsic::x86_avx2_vperm2i128:
10255     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10256                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10257
10258   case Intrinsic::x86_avx2_permd:
10259   case Intrinsic::x86_avx2_permps:
10260     // Operands intentionally swapped. Mask is last operand to intrinsic,
10261     // but second operand for node/intruction.
10262     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10263                        Op.getOperand(2), Op.getOperand(1));
10264
10265   // ptest and testp intrinsics. The intrinsic these come from are designed to
10266   // return an integer value, not just an instruction so lower it to the ptest
10267   // or testp pattern and a setcc for the result.
10268   case Intrinsic::x86_sse41_ptestz:
10269   case Intrinsic::x86_sse41_ptestc:
10270   case Intrinsic::x86_sse41_ptestnzc:
10271   case Intrinsic::x86_avx_ptestz_256:
10272   case Intrinsic::x86_avx_ptestc_256:
10273   case Intrinsic::x86_avx_ptestnzc_256:
10274   case Intrinsic::x86_avx_vtestz_ps:
10275   case Intrinsic::x86_avx_vtestc_ps:
10276   case Intrinsic::x86_avx_vtestnzc_ps:
10277   case Intrinsic::x86_avx_vtestz_pd:
10278   case Intrinsic::x86_avx_vtestc_pd:
10279   case Intrinsic::x86_avx_vtestnzc_pd:
10280   case Intrinsic::x86_avx_vtestz_ps_256:
10281   case Intrinsic::x86_avx_vtestc_ps_256:
10282   case Intrinsic::x86_avx_vtestnzc_ps_256:
10283   case Intrinsic::x86_avx_vtestz_pd_256:
10284   case Intrinsic::x86_avx_vtestc_pd_256:
10285   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10286     bool IsTestPacked = false;
10287     unsigned X86CC;
10288     switch (IntNo) {
10289     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10290     case Intrinsic::x86_avx_vtestz_ps:
10291     case Intrinsic::x86_avx_vtestz_pd:
10292     case Intrinsic::x86_avx_vtestz_ps_256:
10293     case Intrinsic::x86_avx_vtestz_pd_256:
10294       IsTestPacked = true; // Fallthrough
10295     case Intrinsic::x86_sse41_ptestz:
10296     case Intrinsic::x86_avx_ptestz_256:
10297       // ZF = 1
10298       X86CC = X86::COND_E;
10299       break;
10300     case Intrinsic::x86_avx_vtestc_ps:
10301     case Intrinsic::x86_avx_vtestc_pd:
10302     case Intrinsic::x86_avx_vtestc_ps_256:
10303     case Intrinsic::x86_avx_vtestc_pd_256:
10304       IsTestPacked = true; // Fallthrough
10305     case Intrinsic::x86_sse41_ptestc:
10306     case Intrinsic::x86_avx_ptestc_256:
10307       // CF = 1
10308       X86CC = X86::COND_B;
10309       break;
10310     case Intrinsic::x86_avx_vtestnzc_ps:
10311     case Intrinsic::x86_avx_vtestnzc_pd:
10312     case Intrinsic::x86_avx_vtestnzc_ps_256:
10313     case Intrinsic::x86_avx_vtestnzc_pd_256:
10314       IsTestPacked = true; // Fallthrough
10315     case Intrinsic::x86_sse41_ptestnzc:
10316     case Intrinsic::x86_avx_ptestnzc_256:
10317       // ZF and CF = 0
10318       X86CC = X86::COND_A;
10319       break;
10320     }
10321
10322     SDValue LHS = Op.getOperand(1);
10323     SDValue RHS = Op.getOperand(2);
10324     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10325     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10326     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10327     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10328     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10329   }
10330
10331   // SSE/AVX shift intrinsics
10332   case Intrinsic::x86_sse2_psll_w:
10333   case Intrinsic::x86_sse2_psll_d:
10334   case Intrinsic::x86_sse2_psll_q:
10335   case Intrinsic::x86_avx2_psll_w:
10336   case Intrinsic::x86_avx2_psll_d:
10337   case Intrinsic::x86_avx2_psll_q:
10338   case Intrinsic::x86_sse2_psrl_w:
10339   case Intrinsic::x86_sse2_psrl_d:
10340   case Intrinsic::x86_sse2_psrl_q:
10341   case Intrinsic::x86_avx2_psrl_w:
10342   case Intrinsic::x86_avx2_psrl_d:
10343   case Intrinsic::x86_avx2_psrl_q:
10344   case Intrinsic::x86_sse2_psra_w:
10345   case Intrinsic::x86_sse2_psra_d:
10346   case Intrinsic::x86_avx2_psra_w:
10347   case Intrinsic::x86_avx2_psra_d: {
10348     unsigned Opcode;
10349     switch (IntNo) {
10350     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10351     case Intrinsic::x86_sse2_psll_w:
10352     case Intrinsic::x86_sse2_psll_d:
10353     case Intrinsic::x86_sse2_psll_q:
10354     case Intrinsic::x86_avx2_psll_w:
10355     case Intrinsic::x86_avx2_psll_d:
10356     case Intrinsic::x86_avx2_psll_q:
10357       Opcode = X86ISD::VSHL;
10358       break;
10359     case Intrinsic::x86_sse2_psrl_w:
10360     case Intrinsic::x86_sse2_psrl_d:
10361     case Intrinsic::x86_sse2_psrl_q:
10362     case Intrinsic::x86_avx2_psrl_w:
10363     case Intrinsic::x86_avx2_psrl_d:
10364     case Intrinsic::x86_avx2_psrl_q:
10365       Opcode = X86ISD::VSRL;
10366       break;
10367     case Intrinsic::x86_sse2_psra_w:
10368     case Intrinsic::x86_sse2_psra_d:
10369     case Intrinsic::x86_avx2_psra_w:
10370     case Intrinsic::x86_avx2_psra_d:
10371       Opcode = X86ISD::VSRA;
10372       break;
10373     }
10374     return DAG.getNode(Opcode, dl, Op.getValueType(),
10375                        Op.getOperand(1), Op.getOperand(2));
10376   }
10377
10378   // SSE/AVX immediate shift intrinsics
10379   case Intrinsic::x86_sse2_pslli_w:
10380   case Intrinsic::x86_sse2_pslli_d:
10381   case Intrinsic::x86_sse2_pslli_q:
10382   case Intrinsic::x86_avx2_pslli_w:
10383   case Intrinsic::x86_avx2_pslli_d:
10384   case Intrinsic::x86_avx2_pslli_q:
10385   case Intrinsic::x86_sse2_psrli_w:
10386   case Intrinsic::x86_sse2_psrli_d:
10387   case Intrinsic::x86_sse2_psrli_q:
10388   case Intrinsic::x86_avx2_psrli_w:
10389   case Intrinsic::x86_avx2_psrli_d:
10390   case Intrinsic::x86_avx2_psrli_q:
10391   case Intrinsic::x86_sse2_psrai_w:
10392   case Intrinsic::x86_sse2_psrai_d:
10393   case Intrinsic::x86_avx2_psrai_w:
10394   case Intrinsic::x86_avx2_psrai_d: {
10395     unsigned Opcode;
10396     switch (IntNo) {
10397     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10398     case Intrinsic::x86_sse2_pslli_w:
10399     case Intrinsic::x86_sse2_pslli_d:
10400     case Intrinsic::x86_sse2_pslli_q:
10401     case Intrinsic::x86_avx2_pslli_w:
10402     case Intrinsic::x86_avx2_pslli_d:
10403     case Intrinsic::x86_avx2_pslli_q:
10404       Opcode = X86ISD::VSHLI;
10405       break;
10406     case Intrinsic::x86_sse2_psrli_w:
10407     case Intrinsic::x86_sse2_psrli_d:
10408     case Intrinsic::x86_sse2_psrli_q:
10409     case Intrinsic::x86_avx2_psrli_w:
10410     case Intrinsic::x86_avx2_psrli_d:
10411     case Intrinsic::x86_avx2_psrli_q:
10412       Opcode = X86ISD::VSRLI;
10413       break;
10414     case Intrinsic::x86_sse2_psrai_w:
10415     case Intrinsic::x86_sse2_psrai_d:
10416     case Intrinsic::x86_avx2_psrai_w:
10417     case Intrinsic::x86_avx2_psrai_d:
10418       Opcode = X86ISD::VSRAI;
10419       break;
10420     }
10421     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10422                                Op.getOperand(1), Op.getOperand(2), DAG);
10423   }
10424
10425   case Intrinsic::x86_sse42_pcmpistria128:
10426   case Intrinsic::x86_sse42_pcmpestria128:
10427   case Intrinsic::x86_sse42_pcmpistric128:
10428   case Intrinsic::x86_sse42_pcmpestric128:
10429   case Intrinsic::x86_sse42_pcmpistrio128:
10430   case Intrinsic::x86_sse42_pcmpestrio128:
10431   case Intrinsic::x86_sse42_pcmpistris128:
10432   case Intrinsic::x86_sse42_pcmpestris128:
10433   case Intrinsic::x86_sse42_pcmpistriz128:
10434   case Intrinsic::x86_sse42_pcmpestriz128: {
10435     unsigned Opcode;
10436     unsigned X86CC;
10437     switch (IntNo) {
10438     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10439     case Intrinsic::x86_sse42_pcmpistria128:
10440       Opcode = X86ISD::PCMPISTRI;
10441       X86CC = X86::COND_A;
10442       break;
10443     case Intrinsic::x86_sse42_pcmpestria128:
10444       Opcode = X86ISD::PCMPESTRI;
10445       X86CC = X86::COND_A;
10446       break;
10447     case Intrinsic::x86_sse42_pcmpistric128:
10448       Opcode = X86ISD::PCMPISTRI;
10449       X86CC = X86::COND_B;
10450       break;
10451     case Intrinsic::x86_sse42_pcmpestric128:
10452       Opcode = X86ISD::PCMPESTRI;
10453       X86CC = X86::COND_B;
10454       break;
10455     case Intrinsic::x86_sse42_pcmpistrio128:
10456       Opcode = X86ISD::PCMPISTRI;
10457       X86CC = X86::COND_O;
10458       break;
10459     case Intrinsic::x86_sse42_pcmpestrio128:
10460       Opcode = X86ISD::PCMPESTRI;
10461       X86CC = X86::COND_O;
10462       break;
10463     case Intrinsic::x86_sse42_pcmpistris128:
10464       Opcode = X86ISD::PCMPISTRI;
10465       X86CC = X86::COND_S;
10466       break;
10467     case Intrinsic::x86_sse42_pcmpestris128:
10468       Opcode = X86ISD::PCMPESTRI;
10469       X86CC = X86::COND_S;
10470       break;
10471     case Intrinsic::x86_sse42_pcmpistriz128:
10472       Opcode = X86ISD::PCMPISTRI;
10473       X86CC = X86::COND_E;
10474       break;
10475     case Intrinsic::x86_sse42_pcmpestriz128:
10476       Opcode = X86ISD::PCMPESTRI;
10477       X86CC = X86::COND_E;
10478       break;
10479     }
10480     SmallVector<SDValue, 5> NewOps;
10481     NewOps.append(Op->op_begin()+1, Op->op_end());
10482     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10483     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10484     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10485                                 DAG.getConstant(X86CC, MVT::i8),
10486                                 SDValue(PCMP.getNode(), 1));
10487     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10488   }
10489
10490   case Intrinsic::x86_sse42_pcmpistri128:
10491   case Intrinsic::x86_sse42_pcmpestri128: {
10492     unsigned Opcode;
10493     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10494       Opcode = X86ISD::PCMPISTRI;
10495     else
10496       Opcode = X86ISD::PCMPESTRI;
10497
10498     SmallVector<SDValue, 5> NewOps;
10499     NewOps.append(Op->op_begin()+1, Op->op_end());
10500     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10501     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10502   }
10503   case Intrinsic::x86_fma_vfmadd_ps:
10504   case Intrinsic::x86_fma_vfmadd_pd:
10505   case Intrinsic::x86_fma_vfmsub_ps:
10506   case Intrinsic::x86_fma_vfmsub_pd:
10507   case Intrinsic::x86_fma_vfnmadd_ps:
10508   case Intrinsic::x86_fma_vfnmadd_pd:
10509   case Intrinsic::x86_fma_vfnmsub_ps:
10510   case Intrinsic::x86_fma_vfnmsub_pd:
10511   case Intrinsic::x86_fma_vfmaddsub_ps:
10512   case Intrinsic::x86_fma_vfmaddsub_pd:
10513   case Intrinsic::x86_fma_vfmsubadd_ps:
10514   case Intrinsic::x86_fma_vfmsubadd_pd:
10515   case Intrinsic::x86_fma_vfmadd_ps_256:
10516   case Intrinsic::x86_fma_vfmadd_pd_256:
10517   case Intrinsic::x86_fma_vfmsub_ps_256:
10518   case Intrinsic::x86_fma_vfmsub_pd_256:
10519   case Intrinsic::x86_fma_vfnmadd_ps_256:
10520   case Intrinsic::x86_fma_vfnmadd_pd_256:
10521   case Intrinsic::x86_fma_vfnmsub_ps_256:
10522   case Intrinsic::x86_fma_vfnmsub_pd_256:
10523   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10524   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10525   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10526   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10527     unsigned Opc;
10528     switch (IntNo) {
10529     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10530     case Intrinsic::x86_fma_vfmadd_ps:
10531     case Intrinsic::x86_fma_vfmadd_pd:
10532     case Intrinsic::x86_fma_vfmadd_ps_256:
10533     case Intrinsic::x86_fma_vfmadd_pd_256:
10534       Opc = X86ISD::FMADD;
10535       break;
10536     case Intrinsic::x86_fma_vfmsub_ps:
10537     case Intrinsic::x86_fma_vfmsub_pd:
10538     case Intrinsic::x86_fma_vfmsub_ps_256:
10539     case Intrinsic::x86_fma_vfmsub_pd_256:
10540       Opc = X86ISD::FMSUB;
10541       break;
10542     case Intrinsic::x86_fma_vfnmadd_ps:
10543     case Intrinsic::x86_fma_vfnmadd_pd:
10544     case Intrinsic::x86_fma_vfnmadd_ps_256:
10545     case Intrinsic::x86_fma_vfnmadd_pd_256:
10546       Opc = X86ISD::FNMADD;
10547       break;
10548     case Intrinsic::x86_fma_vfnmsub_ps:
10549     case Intrinsic::x86_fma_vfnmsub_pd:
10550     case Intrinsic::x86_fma_vfnmsub_ps_256:
10551     case Intrinsic::x86_fma_vfnmsub_pd_256:
10552       Opc = X86ISD::FNMSUB;
10553       break;
10554     case Intrinsic::x86_fma_vfmaddsub_ps:
10555     case Intrinsic::x86_fma_vfmaddsub_pd:
10556     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10557     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10558       Opc = X86ISD::FMADDSUB;
10559       break;
10560     case Intrinsic::x86_fma_vfmsubadd_ps:
10561     case Intrinsic::x86_fma_vfmsubadd_pd:
10562     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10563     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10564       Opc = X86ISD::FMSUBADD;
10565       break;
10566     }
10567
10568     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10569                        Op.getOperand(2), Op.getOperand(3));
10570   }
10571   }
10572 }
10573
10574 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10575   DebugLoc dl = Op.getDebugLoc();
10576   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10577   switch (IntNo) {
10578   default: return SDValue();    // Don't custom lower most intrinsics.
10579
10580   // RDRAND intrinsics.
10581   case Intrinsic::x86_rdrand_16:
10582   case Intrinsic::x86_rdrand_32:
10583   case Intrinsic::x86_rdrand_64: {
10584     // Emit the node with the right value type.
10585     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10586     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10587
10588     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10589     // return the value from Rand, which is always 0, casted to i32.
10590     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10591                       DAG.getConstant(1, Op->getValueType(1)),
10592                       DAG.getConstant(X86::COND_B, MVT::i32),
10593                       SDValue(Result.getNode(), 1) };
10594     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10595                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10596                                   Ops, 4);
10597
10598     // Return { result, isValid, chain }.
10599     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10600                        SDValue(Result.getNode(), 2));
10601   }
10602   }
10603 }
10604
10605 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10606                                            SelectionDAG &DAG) const {
10607   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10608   MFI->setReturnAddressIsTaken(true);
10609
10610   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10611   DebugLoc dl = Op.getDebugLoc();
10612   EVT PtrVT = getPointerTy();
10613
10614   if (Depth > 0) {
10615     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10616     SDValue Offset =
10617       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10618     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10619                        DAG.getNode(ISD::ADD, dl, PtrVT,
10620                                    FrameAddr, Offset),
10621                        MachinePointerInfo(), false, false, false, 0);
10622   }
10623
10624   // Just load the return address.
10625   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10626   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10627                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10628 }
10629
10630 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10631   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10632   MFI->setFrameAddressIsTaken(true);
10633
10634   EVT VT = Op.getValueType();
10635   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10636   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10637   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10638   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10639   while (Depth--)
10640     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10641                             MachinePointerInfo(),
10642                             false, false, false, 0);
10643   return FrameAddr;
10644 }
10645
10646 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10647                                                      SelectionDAG &DAG) const {
10648   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10649 }
10650
10651 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10652   SDValue Chain     = Op.getOperand(0);
10653   SDValue Offset    = Op.getOperand(1);
10654   SDValue Handler   = Op.getOperand(2);
10655   DebugLoc dl       = Op.getDebugLoc();
10656
10657   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10658                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10659                                      getPointerTy());
10660   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10661
10662   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10663                                   DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10664   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10665   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10666                        false, false, 0);
10667   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10668
10669   return DAG.getNode(X86ISD::EH_RETURN, dl,
10670                      MVT::Other,
10671                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10672 }
10673
10674 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10675                                                SelectionDAG &DAG) const {
10676   DebugLoc DL = Op.getDebugLoc();
10677   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10678                      DAG.getVTList(MVT::i32, MVT::Other),
10679                      Op.getOperand(0), Op.getOperand(1));
10680 }
10681
10682 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10683                                                 SelectionDAG &DAG) const {
10684   DebugLoc DL = Op.getDebugLoc();
10685   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10686                      Op.getOperand(0), Op.getOperand(1));
10687 }
10688
10689 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10690   return Op.getOperand(0);
10691 }
10692
10693 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10694                                                 SelectionDAG &DAG) const {
10695   SDValue Root = Op.getOperand(0);
10696   SDValue Trmp = Op.getOperand(1); // trampoline
10697   SDValue FPtr = Op.getOperand(2); // nested function
10698   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10699   DebugLoc dl  = Op.getDebugLoc();
10700
10701   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10702   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10703
10704   if (Subtarget->is64Bit()) {
10705     SDValue OutChains[6];
10706
10707     // Large code-model.
10708     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10709     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10710
10711     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10712     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10713
10714     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10715
10716     // Load the pointer to the nested function into R11.
10717     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10718     SDValue Addr = Trmp;
10719     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10720                                 Addr, MachinePointerInfo(TrmpAddr),
10721                                 false, false, 0);
10722
10723     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10724                        DAG.getConstant(2, MVT::i64));
10725     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10726                                 MachinePointerInfo(TrmpAddr, 2),
10727                                 false, false, 2);
10728
10729     // Load the 'nest' parameter value into R10.
10730     // R10 is specified in X86CallingConv.td
10731     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10732     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10733                        DAG.getConstant(10, MVT::i64));
10734     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10735                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10736                                 false, false, 0);
10737
10738     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10739                        DAG.getConstant(12, MVT::i64));
10740     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10741                                 MachinePointerInfo(TrmpAddr, 12),
10742                                 false, false, 2);
10743
10744     // Jump to the nested function.
10745     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10746     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10747                        DAG.getConstant(20, MVT::i64));
10748     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10749                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10750                                 false, false, 0);
10751
10752     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10753     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10754                        DAG.getConstant(22, MVT::i64));
10755     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10756                                 MachinePointerInfo(TrmpAddr, 22),
10757                                 false, false, 0);
10758
10759     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10760   } else {
10761     const Function *Func =
10762       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10763     CallingConv::ID CC = Func->getCallingConv();
10764     unsigned NestReg;
10765
10766     switch (CC) {
10767     default:
10768       llvm_unreachable("Unsupported calling convention");
10769     case CallingConv::C:
10770     case CallingConv::X86_StdCall: {
10771       // Pass 'nest' parameter in ECX.
10772       // Must be kept in sync with X86CallingConv.td
10773       NestReg = X86::ECX;
10774
10775       // Check that ECX wasn't needed by an 'inreg' parameter.
10776       FunctionType *FTy = Func->getFunctionType();
10777       const AttributeSet &Attrs = Func->getAttributes();
10778
10779       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10780         unsigned InRegCount = 0;
10781         unsigned Idx = 1;
10782
10783         for (FunctionType::param_iterator I = FTy->param_begin(),
10784              E = FTy->param_end(); I != E; ++I, ++Idx)
10785           if (Attrs.getParamAttributes(Idx).hasAttribute(Attribute::InReg))
10786             // FIXME: should only count parameters that are lowered to integers.
10787             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10788
10789         if (InRegCount > 2) {
10790           report_fatal_error("Nest register in use - reduce number of inreg"
10791                              " parameters!");
10792         }
10793       }
10794       break;
10795     }
10796     case CallingConv::X86_FastCall:
10797     case CallingConv::X86_ThisCall:
10798     case CallingConv::Fast:
10799       // Pass 'nest' parameter in EAX.
10800       // Must be kept in sync with X86CallingConv.td
10801       NestReg = X86::EAX;
10802       break;
10803     }
10804
10805     SDValue OutChains[4];
10806     SDValue Addr, Disp;
10807
10808     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10809                        DAG.getConstant(10, MVT::i32));
10810     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10811
10812     // This is storing the opcode for MOV32ri.
10813     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10814     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10815     OutChains[0] = DAG.getStore(Root, dl,
10816                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10817                                 Trmp, MachinePointerInfo(TrmpAddr),
10818                                 false, false, 0);
10819
10820     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10821                        DAG.getConstant(1, MVT::i32));
10822     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10823                                 MachinePointerInfo(TrmpAddr, 1),
10824                                 false, false, 1);
10825
10826     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10827     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10828                        DAG.getConstant(5, MVT::i32));
10829     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10830                                 MachinePointerInfo(TrmpAddr, 5),
10831                                 false, false, 1);
10832
10833     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10834                        DAG.getConstant(6, MVT::i32));
10835     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10836                                 MachinePointerInfo(TrmpAddr, 6),
10837                                 false, false, 1);
10838
10839     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10840   }
10841 }
10842
10843 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10844                                             SelectionDAG &DAG) const {
10845   /*
10846    The rounding mode is in bits 11:10 of FPSR, and has the following
10847    settings:
10848      00 Round to nearest
10849      01 Round to -inf
10850      10 Round to +inf
10851      11 Round to 0
10852
10853   FLT_ROUNDS, on the other hand, expects the following:
10854     -1 Undefined
10855      0 Round to 0
10856      1 Round to nearest
10857      2 Round to +inf
10858      3 Round to -inf
10859
10860   To perform the conversion, we do:
10861     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10862   */
10863
10864   MachineFunction &MF = DAG.getMachineFunction();
10865   const TargetMachine &TM = MF.getTarget();
10866   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10867   unsigned StackAlignment = TFI.getStackAlignment();
10868   EVT VT = Op.getValueType();
10869   DebugLoc DL = Op.getDebugLoc();
10870
10871   // Save FP Control Word to stack slot
10872   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10873   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10874
10875   MachineMemOperand *MMO =
10876    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10877                            MachineMemOperand::MOStore, 2, 2);
10878
10879   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10880   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10881                                           DAG.getVTList(MVT::Other),
10882                                           Ops, 2, MVT::i16, MMO);
10883
10884   // Load FP Control Word from stack slot
10885   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10886                             MachinePointerInfo(), false, false, false, 0);
10887
10888   // Transform as necessary
10889   SDValue CWD1 =
10890     DAG.getNode(ISD::SRL, DL, MVT::i16,
10891                 DAG.getNode(ISD::AND, DL, MVT::i16,
10892                             CWD, DAG.getConstant(0x800, MVT::i16)),
10893                 DAG.getConstant(11, MVT::i8));
10894   SDValue CWD2 =
10895     DAG.getNode(ISD::SRL, DL, MVT::i16,
10896                 DAG.getNode(ISD::AND, DL, MVT::i16,
10897                             CWD, DAG.getConstant(0x400, MVT::i16)),
10898                 DAG.getConstant(9, MVT::i8));
10899
10900   SDValue RetVal =
10901     DAG.getNode(ISD::AND, DL, MVT::i16,
10902                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10903                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10904                             DAG.getConstant(1, MVT::i16)),
10905                 DAG.getConstant(3, MVT::i16));
10906
10907   return DAG.getNode((VT.getSizeInBits() < 16 ?
10908                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10909 }
10910
10911 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10912   EVT VT = Op.getValueType();
10913   EVT OpVT = VT;
10914   unsigned NumBits = VT.getSizeInBits();
10915   DebugLoc dl = Op.getDebugLoc();
10916
10917   Op = Op.getOperand(0);
10918   if (VT == MVT::i8) {
10919     // Zero extend to i32 since there is not an i8 bsr.
10920     OpVT = MVT::i32;
10921     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10922   }
10923
10924   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10925   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10926   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10927
10928   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10929   SDValue Ops[] = {
10930     Op,
10931     DAG.getConstant(NumBits+NumBits-1, OpVT),
10932     DAG.getConstant(X86::COND_E, MVT::i8),
10933     Op.getValue(1)
10934   };
10935   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10936
10937   // Finally xor with NumBits-1.
10938   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10939
10940   if (VT == MVT::i8)
10941     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10942   return Op;
10943 }
10944
10945 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10946   EVT VT = Op.getValueType();
10947   EVT OpVT = VT;
10948   unsigned NumBits = VT.getSizeInBits();
10949   DebugLoc dl = Op.getDebugLoc();
10950
10951   Op = Op.getOperand(0);
10952   if (VT == MVT::i8) {
10953     // Zero extend to i32 since there is not an i8 bsr.
10954     OpVT = MVT::i32;
10955     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10956   }
10957
10958   // Issue a bsr (scan bits in reverse).
10959   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10960   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10961
10962   // And xor with NumBits-1.
10963   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10964
10965   if (VT == MVT::i8)
10966     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10967   return Op;
10968 }
10969
10970 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10971   EVT VT = Op.getValueType();
10972   unsigned NumBits = VT.getSizeInBits();
10973   DebugLoc dl = Op.getDebugLoc();
10974   Op = Op.getOperand(0);
10975
10976   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10977   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10978   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10979
10980   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10981   SDValue Ops[] = {
10982     Op,
10983     DAG.getConstant(NumBits, VT),
10984     DAG.getConstant(X86::COND_E, MVT::i8),
10985     Op.getValue(1)
10986   };
10987   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10988 }
10989
10990 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10991 // ones, and then concatenate the result back.
10992 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10993   EVT VT = Op.getValueType();
10994
10995   assert(VT.is256BitVector() && VT.isInteger() &&
10996          "Unsupported value type for operation");
10997
10998   unsigned NumElems = VT.getVectorNumElements();
10999   DebugLoc dl = Op.getDebugLoc();
11000
11001   // Extract the LHS vectors
11002   SDValue LHS = Op.getOperand(0);
11003   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11004   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11005
11006   // Extract the RHS vectors
11007   SDValue RHS = Op.getOperand(1);
11008   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11009   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11010
11011   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11012   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11013
11014   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11015                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11016                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11017 }
11018
11019 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11020   assert(Op.getValueType().is256BitVector() &&
11021          Op.getValueType().isInteger() &&
11022          "Only handle AVX 256-bit vector integer operation");
11023   return Lower256IntArith(Op, DAG);
11024 }
11025
11026 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11027   assert(Op.getValueType().is256BitVector() &&
11028          Op.getValueType().isInteger() &&
11029          "Only handle AVX 256-bit vector integer operation");
11030   return Lower256IntArith(Op, DAG);
11031 }
11032
11033 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11034                         SelectionDAG &DAG) {
11035   DebugLoc dl = Op.getDebugLoc();
11036   EVT VT = Op.getValueType();
11037
11038   // Decompose 256-bit ops into smaller 128-bit ops.
11039   if (VT.is256BitVector() && !Subtarget->hasInt256())
11040     return Lower256IntArith(Op, DAG);
11041
11042   SDValue A = Op.getOperand(0);
11043   SDValue B = Op.getOperand(1);
11044
11045   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11046   if (VT == MVT::v4i32) {
11047     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11048            "Should not custom lower when pmuldq is available!");
11049
11050     // Extract the odd parts.
11051     const int UnpackMask[] = { 1, -1, 3, -1 };
11052     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11053     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11054
11055     // Multiply the even parts.
11056     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11057     // Now multiply odd parts.
11058     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11059
11060     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11061     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11062
11063     // Merge the two vectors back together with a shuffle. This expands into 2
11064     // shuffles.
11065     const int ShufMask[] = { 0, 4, 2, 6 };
11066     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11067   }
11068
11069   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11070          "Only know how to lower V2I64/V4I64 multiply");
11071
11072   //  Ahi = psrlqi(a, 32);
11073   //  Bhi = psrlqi(b, 32);
11074   //
11075   //  AloBlo = pmuludq(a, b);
11076   //  AloBhi = pmuludq(a, Bhi);
11077   //  AhiBlo = pmuludq(Ahi, b);
11078
11079   //  AloBhi = psllqi(AloBhi, 32);
11080   //  AhiBlo = psllqi(AhiBlo, 32);
11081   //  return AloBlo + AloBhi + AhiBlo;
11082
11083   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11084
11085   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11086   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11087
11088   // Bit cast to 32-bit vectors for MULUDQ
11089   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11090   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11091   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11092   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11093   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11094
11095   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11096   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11097   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11098
11099   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11100   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11101
11102   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11103   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11104 }
11105
11106 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11107
11108   EVT VT = Op.getValueType();
11109   DebugLoc dl = Op.getDebugLoc();
11110   SDValue R = Op.getOperand(0);
11111   SDValue Amt = Op.getOperand(1);
11112   LLVMContext *Context = DAG.getContext();
11113
11114   if (!Subtarget->hasSSE2())
11115     return SDValue();
11116
11117   // Optimize shl/srl/sra with constant shift amount.
11118   if (isSplatVector(Amt.getNode())) {
11119     SDValue SclrAmt = Amt->getOperand(0);
11120     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11121       uint64_t ShiftAmt = C->getZExtValue();
11122
11123       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11124           (Subtarget->hasInt256() &&
11125            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11126         if (Op.getOpcode() == ISD::SHL)
11127           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11128                              DAG.getConstant(ShiftAmt, MVT::i32));
11129         if (Op.getOpcode() == ISD::SRL)
11130           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11131                              DAG.getConstant(ShiftAmt, MVT::i32));
11132         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11133           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11134                              DAG.getConstant(ShiftAmt, MVT::i32));
11135       }
11136
11137       if (VT == MVT::v16i8) {
11138         if (Op.getOpcode() == ISD::SHL) {
11139           // Make a large shift.
11140           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11141                                     DAG.getConstant(ShiftAmt, MVT::i32));
11142           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11143           // Zero out the rightmost bits.
11144           SmallVector<SDValue, 16> V(16,
11145                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11146                                                      MVT::i8));
11147           return DAG.getNode(ISD::AND, dl, VT, SHL,
11148                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11149         }
11150         if (Op.getOpcode() == ISD::SRL) {
11151           // Make a large shift.
11152           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11153                                     DAG.getConstant(ShiftAmt, MVT::i32));
11154           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11155           // Zero out the leftmost bits.
11156           SmallVector<SDValue, 16> V(16,
11157                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11158                                                      MVT::i8));
11159           return DAG.getNode(ISD::AND, dl, VT, SRL,
11160                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11161         }
11162         if (Op.getOpcode() == ISD::SRA) {
11163           if (ShiftAmt == 7) {
11164             // R s>> 7  ===  R s< 0
11165             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11166             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11167           }
11168
11169           // R s>> a === ((R u>> a) ^ m) - m
11170           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11171           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11172                                                          MVT::i8));
11173           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11174           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11175           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11176           return Res;
11177         }
11178         llvm_unreachable("Unknown shift opcode.");
11179       }
11180
11181       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11182         if (Op.getOpcode() == ISD::SHL) {
11183           // Make a large shift.
11184           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11185                                     DAG.getConstant(ShiftAmt, MVT::i32));
11186           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11187           // Zero out the rightmost bits.
11188           SmallVector<SDValue, 32> V(32,
11189                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11190                                                      MVT::i8));
11191           return DAG.getNode(ISD::AND, dl, VT, SHL,
11192                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11193         }
11194         if (Op.getOpcode() == ISD::SRL) {
11195           // Make a large shift.
11196           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11197                                     DAG.getConstant(ShiftAmt, MVT::i32));
11198           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11199           // Zero out the leftmost bits.
11200           SmallVector<SDValue, 32> V(32,
11201                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11202                                                      MVT::i8));
11203           return DAG.getNode(ISD::AND, dl, VT, SRL,
11204                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11205         }
11206         if (Op.getOpcode() == ISD::SRA) {
11207           if (ShiftAmt == 7) {
11208             // R s>> 7  ===  R s< 0
11209             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11210             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11211           }
11212
11213           // R s>> a === ((R u>> a) ^ m) - m
11214           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11215           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11216                                                          MVT::i8));
11217           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11218           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11219           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11220           return Res;
11221         }
11222         llvm_unreachable("Unknown shift opcode.");
11223       }
11224     }
11225   }
11226
11227   // Lower SHL with variable shift amount.
11228   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11229     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11230                      DAG.getConstant(23, MVT::i32));
11231
11232     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11233     Constant *C = ConstantDataVector::get(*Context, CV);
11234     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11235     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11236                                  MachinePointerInfo::getConstantPool(),
11237                                  false, false, false, 16);
11238
11239     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11240     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11241     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11242     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11243   }
11244   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11245     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11246
11247     // a = a << 5;
11248     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11249                      DAG.getConstant(5, MVT::i32));
11250     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11251
11252     // Turn 'a' into a mask suitable for VSELECT
11253     SDValue VSelM = DAG.getConstant(0x80, VT);
11254     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11255     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11256
11257     SDValue CM1 = DAG.getConstant(0x0f, VT);
11258     SDValue CM2 = DAG.getConstant(0x3f, VT);
11259
11260     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11261     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11262     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11263                             DAG.getConstant(4, MVT::i32), DAG);
11264     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11265     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11266
11267     // a += a
11268     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11269     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11270     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11271
11272     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11273     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11274     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11275                             DAG.getConstant(2, MVT::i32), DAG);
11276     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11277     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11278
11279     // a += a
11280     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11281     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11282     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11283
11284     // return VSELECT(r, r+r, a);
11285     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11286                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11287     return R;
11288   }
11289
11290   // Decompose 256-bit shifts into smaller 128-bit shifts.
11291   if (VT.is256BitVector()) {
11292     unsigned NumElems = VT.getVectorNumElements();
11293     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11294     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11295
11296     // Extract the two vectors
11297     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11298     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11299
11300     // Recreate the shift amount vectors
11301     SDValue Amt1, Amt2;
11302     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11303       // Constant shift amount
11304       SmallVector<SDValue, 4> Amt1Csts;
11305       SmallVector<SDValue, 4> Amt2Csts;
11306       for (unsigned i = 0; i != NumElems/2; ++i)
11307         Amt1Csts.push_back(Amt->getOperand(i));
11308       for (unsigned i = NumElems/2; i != NumElems; ++i)
11309         Amt2Csts.push_back(Amt->getOperand(i));
11310
11311       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11312                                  &Amt1Csts[0], NumElems/2);
11313       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11314                                  &Amt2Csts[0], NumElems/2);
11315     } else {
11316       // Variable shift amount
11317       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11318       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11319     }
11320
11321     // Issue new vector shifts for the smaller types
11322     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11323     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11324
11325     // Concatenate the result back
11326     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11327   }
11328
11329   return SDValue();
11330 }
11331
11332 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11333   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11334   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11335   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11336   // has only one use.
11337   SDNode *N = Op.getNode();
11338   SDValue LHS = N->getOperand(0);
11339   SDValue RHS = N->getOperand(1);
11340   unsigned BaseOp = 0;
11341   unsigned Cond = 0;
11342   DebugLoc DL = Op.getDebugLoc();
11343   switch (Op.getOpcode()) {
11344   default: llvm_unreachable("Unknown ovf instruction!");
11345   case ISD::SADDO:
11346     // A subtract of one will be selected as a INC. Note that INC doesn't
11347     // set CF, so we can't do this for UADDO.
11348     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11349       if (C->isOne()) {
11350         BaseOp = X86ISD::INC;
11351         Cond = X86::COND_O;
11352         break;
11353       }
11354     BaseOp = X86ISD::ADD;
11355     Cond = X86::COND_O;
11356     break;
11357   case ISD::UADDO:
11358     BaseOp = X86ISD::ADD;
11359     Cond = X86::COND_B;
11360     break;
11361   case ISD::SSUBO:
11362     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11363     // set CF, so we can't do this for USUBO.
11364     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11365       if (C->isOne()) {
11366         BaseOp = X86ISD::DEC;
11367         Cond = X86::COND_O;
11368         break;
11369       }
11370     BaseOp = X86ISD::SUB;
11371     Cond = X86::COND_O;
11372     break;
11373   case ISD::USUBO:
11374     BaseOp = X86ISD::SUB;
11375     Cond = X86::COND_B;
11376     break;
11377   case ISD::SMULO:
11378     BaseOp = X86ISD::SMUL;
11379     Cond = X86::COND_O;
11380     break;
11381   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11382     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11383                                  MVT::i32);
11384     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11385
11386     SDValue SetCC =
11387       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11388                   DAG.getConstant(X86::COND_O, MVT::i32),
11389                   SDValue(Sum.getNode(), 2));
11390
11391     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11392   }
11393   }
11394
11395   // Also sets EFLAGS.
11396   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11397   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11398
11399   SDValue SetCC =
11400     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11401                 DAG.getConstant(Cond, MVT::i32),
11402                 SDValue(Sum.getNode(), 1));
11403
11404   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11405 }
11406
11407 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11408                                                   SelectionDAG &DAG) const {
11409   DebugLoc dl = Op.getDebugLoc();
11410   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11411   EVT VT = Op.getValueType();
11412
11413   if (!Subtarget->hasSSE2() || !VT.isVector())
11414     return SDValue();
11415
11416   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11417                       ExtraVT.getScalarType().getSizeInBits();
11418   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11419
11420   switch (VT.getSimpleVT().SimpleTy) {
11421     default: return SDValue();
11422     case MVT::v8i32:
11423     case MVT::v16i16:
11424       if (!Subtarget->hasFp256())
11425         return SDValue();
11426       if (!Subtarget->hasInt256()) {
11427         // needs to be split
11428         unsigned NumElems = VT.getVectorNumElements();
11429
11430         // Extract the LHS vectors
11431         SDValue LHS = Op.getOperand(0);
11432         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11433         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11434
11435         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11436         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11437
11438         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11439         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11440         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11441                                    ExtraNumElems/2);
11442         SDValue Extra = DAG.getValueType(ExtraVT);
11443
11444         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11445         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11446
11447         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11448       }
11449       // fall through
11450     case MVT::v4i32:
11451     case MVT::v8i16: {
11452       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11453                                          Op.getOperand(0), ShAmt, DAG);
11454       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11455     }
11456   }
11457 }
11458
11459 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11460                               SelectionDAG &DAG) {
11461   DebugLoc dl = Op.getDebugLoc();
11462
11463   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11464   // There isn't any reason to disable it if the target processor supports it.
11465   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11466     SDValue Chain = Op.getOperand(0);
11467     SDValue Zero = DAG.getConstant(0, MVT::i32);
11468     SDValue Ops[] = {
11469       DAG.getRegister(X86::ESP, MVT::i32), // Base
11470       DAG.getTargetConstant(1, MVT::i8),   // Scale
11471       DAG.getRegister(0, MVT::i32),        // Index
11472       DAG.getTargetConstant(0, MVT::i32),  // Disp
11473       DAG.getRegister(0, MVT::i32),        // Segment.
11474       Zero,
11475       Chain
11476     };
11477     SDNode *Res =
11478       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11479                           array_lengthof(Ops));
11480     return SDValue(Res, 0);
11481   }
11482
11483   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11484   if (!isDev)
11485     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11486
11487   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11488   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11489   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11490   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11491
11492   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11493   if (!Op1 && !Op2 && !Op3 && Op4)
11494     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11495
11496   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11497   if (Op1 && !Op2 && !Op3 && !Op4)
11498     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11499
11500   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11501   //           (MFENCE)>;
11502   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11503 }
11504
11505 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11506                                  SelectionDAG &DAG) {
11507   DebugLoc dl = Op.getDebugLoc();
11508   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11509     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11510   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11511     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11512
11513   // The only fence that needs an instruction is a sequentially-consistent
11514   // cross-thread fence.
11515   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11516     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11517     // no-sse2). There isn't any reason to disable it if the target processor
11518     // supports it.
11519     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11520       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11521
11522     SDValue Chain = Op.getOperand(0);
11523     SDValue Zero = DAG.getConstant(0, MVT::i32);
11524     SDValue Ops[] = {
11525       DAG.getRegister(X86::ESP, MVT::i32), // Base
11526       DAG.getTargetConstant(1, MVT::i8),   // Scale
11527       DAG.getRegister(0, MVT::i32),        // Index
11528       DAG.getTargetConstant(0, MVT::i32),  // Disp
11529       DAG.getRegister(0, MVT::i32),        // Segment.
11530       Zero,
11531       Chain
11532     };
11533     SDNode *Res =
11534       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11535                          array_lengthof(Ops));
11536     return SDValue(Res, 0);
11537   }
11538
11539   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11540   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11541 }
11542
11543 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11544                              SelectionDAG &DAG) {
11545   EVT T = Op.getValueType();
11546   DebugLoc DL = Op.getDebugLoc();
11547   unsigned Reg = 0;
11548   unsigned size = 0;
11549   switch(T.getSimpleVT().SimpleTy) {
11550   default: llvm_unreachable("Invalid value type!");
11551   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11552   case MVT::i16: Reg = X86::AX;  size = 2; break;
11553   case MVT::i32: Reg = X86::EAX; size = 4; break;
11554   case MVT::i64:
11555     assert(Subtarget->is64Bit() && "Node not type legal!");
11556     Reg = X86::RAX; size = 8;
11557     break;
11558   }
11559   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11560                                     Op.getOperand(2), SDValue());
11561   SDValue Ops[] = { cpIn.getValue(0),
11562                     Op.getOperand(1),
11563                     Op.getOperand(3),
11564                     DAG.getTargetConstant(size, MVT::i8),
11565                     cpIn.getValue(1) };
11566   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11567   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11568   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11569                                            Ops, 5, T, MMO);
11570   SDValue cpOut =
11571     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11572   return cpOut;
11573 }
11574
11575 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11576                                      SelectionDAG &DAG) {
11577   assert(Subtarget->is64Bit() && "Result not type legalized?");
11578   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11579   SDValue TheChain = Op.getOperand(0);
11580   DebugLoc dl = Op.getDebugLoc();
11581   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11582   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11583   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11584                                    rax.getValue(2));
11585   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11586                             DAG.getConstant(32, MVT::i8));
11587   SDValue Ops[] = {
11588     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11589     rdx.getValue(1)
11590   };
11591   return DAG.getMergeValues(Ops, 2, dl);
11592 }
11593
11594 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11595   EVT SrcVT = Op.getOperand(0).getValueType();
11596   EVT DstVT = Op.getValueType();
11597   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11598          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11599   assert((DstVT == MVT::i64 ||
11600           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11601          "Unexpected custom BITCAST");
11602   // i64 <=> MMX conversions are Legal.
11603   if (SrcVT==MVT::i64 && DstVT.isVector())
11604     return Op;
11605   if (DstVT==MVT::i64 && SrcVT.isVector())
11606     return Op;
11607   // MMX <=> MMX conversions are Legal.
11608   if (SrcVT.isVector() && DstVT.isVector())
11609     return Op;
11610   // All other conversions need to be expanded.
11611   return SDValue();
11612 }
11613
11614 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11615   SDNode *Node = Op.getNode();
11616   DebugLoc dl = Node->getDebugLoc();
11617   EVT T = Node->getValueType(0);
11618   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11619                               DAG.getConstant(0, T), Node->getOperand(2));
11620   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11621                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11622                        Node->getOperand(0),
11623                        Node->getOperand(1), negOp,
11624                        cast<AtomicSDNode>(Node)->getSrcValue(),
11625                        cast<AtomicSDNode>(Node)->getAlignment(),
11626                        cast<AtomicSDNode>(Node)->getOrdering(),
11627                        cast<AtomicSDNode>(Node)->getSynchScope());
11628 }
11629
11630 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11631   SDNode *Node = Op.getNode();
11632   DebugLoc dl = Node->getDebugLoc();
11633   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11634
11635   // Convert seq_cst store -> xchg
11636   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11637   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11638   //        (The only way to get a 16-byte store is cmpxchg16b)
11639   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11640   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11641       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11642     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11643                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11644                                  Node->getOperand(0),
11645                                  Node->getOperand(1), Node->getOperand(2),
11646                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11647                                  cast<AtomicSDNode>(Node)->getOrdering(),
11648                                  cast<AtomicSDNode>(Node)->getSynchScope());
11649     return Swap.getValue(1);
11650   }
11651   // Other atomic stores have a simple pattern.
11652   return Op;
11653 }
11654
11655 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11656   EVT VT = Op.getNode()->getValueType(0);
11657
11658   // Let legalize expand this if it isn't a legal type yet.
11659   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11660     return SDValue();
11661
11662   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11663
11664   unsigned Opc;
11665   bool ExtraOp = false;
11666   switch (Op.getOpcode()) {
11667   default: llvm_unreachable("Invalid code");
11668   case ISD::ADDC: Opc = X86ISD::ADD; break;
11669   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11670   case ISD::SUBC: Opc = X86ISD::SUB; break;
11671   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11672   }
11673
11674   if (!ExtraOp)
11675     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11676                        Op.getOperand(1));
11677   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11678                      Op.getOperand(1), Op.getOperand(2));
11679 }
11680
11681 /// LowerOperation - Provide custom lowering hooks for some operations.
11682 ///
11683 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11684   switch (Op.getOpcode()) {
11685   default: llvm_unreachable("Should not custom lower this!");
11686   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11687   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11688   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11689   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11690   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11691   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11692   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11693   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11694   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11695   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11696   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11697   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11698   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11699   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11700   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11701   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11702   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11703   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11704   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11705   case ISD::SHL_PARTS:
11706   case ISD::SRA_PARTS:
11707   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11708   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11709   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11710   case ISD::TRUNCATE:           return lowerTRUNCATE(Op, DAG);
11711   case ISD::ZERO_EXTEND:        return lowerZERO_EXTEND(Op, DAG);
11712   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11713   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11714   case ISD::FP_EXTEND:          return lowerFP_EXTEND(Op, DAG);
11715   case ISD::FABS:               return LowerFABS(Op, DAG);
11716   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11717   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11718   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11719   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11720   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11721   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11722   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11723   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11724   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11725   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11726   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11727   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11728   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11729   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11730   case ISD::FRAME_TO_ARGS_OFFSET:
11731                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11732   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11733   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11734   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11735   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11736   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11737   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11738   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11739   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11740   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11741   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11742   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11743   case ISD::SRA:
11744   case ISD::SRL:
11745   case ISD::SHL:                return LowerShift(Op, DAG);
11746   case ISD::SADDO:
11747   case ISD::UADDO:
11748   case ISD::SSUBO:
11749   case ISD::USUBO:
11750   case ISD::SMULO:
11751   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11752   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11753   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11754   case ISD::ADDC:
11755   case ISD::ADDE:
11756   case ISD::SUBC:
11757   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11758   case ISD::ADD:                return LowerADD(Op, DAG);
11759   case ISD::SUB:                return LowerSUB(Op, DAG);
11760   }
11761 }
11762
11763 static void ReplaceATOMIC_LOAD(SDNode *Node,
11764                                   SmallVectorImpl<SDValue> &Results,
11765                                   SelectionDAG &DAG) {
11766   DebugLoc dl = Node->getDebugLoc();
11767   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11768
11769   // Convert wide load -> cmpxchg8b/cmpxchg16b
11770   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11771   //        (The only way to get a 16-byte load is cmpxchg16b)
11772   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11773   SDValue Zero = DAG.getConstant(0, VT);
11774   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11775                                Node->getOperand(0),
11776                                Node->getOperand(1), Zero, Zero,
11777                                cast<AtomicSDNode>(Node)->getMemOperand(),
11778                                cast<AtomicSDNode>(Node)->getOrdering(),
11779                                cast<AtomicSDNode>(Node)->getSynchScope());
11780   Results.push_back(Swap.getValue(0));
11781   Results.push_back(Swap.getValue(1));
11782 }
11783
11784 static void
11785 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11786                         SelectionDAG &DAG, unsigned NewOp) {
11787   DebugLoc dl = Node->getDebugLoc();
11788   assert (Node->getValueType(0) == MVT::i64 &&
11789           "Only know how to expand i64 atomics");
11790
11791   SDValue Chain = Node->getOperand(0);
11792   SDValue In1 = Node->getOperand(1);
11793   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11794                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11795   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11796                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11797   SDValue Ops[] = { Chain, In1, In2L, In2H };
11798   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11799   SDValue Result =
11800     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11801                             cast<MemSDNode>(Node)->getMemOperand());
11802   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11803   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11804   Results.push_back(Result.getValue(2));
11805 }
11806
11807 /// ReplaceNodeResults - Replace a node with an illegal result type
11808 /// with a new node built out of custom code.
11809 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11810                                            SmallVectorImpl<SDValue>&Results,
11811                                            SelectionDAG &DAG) const {
11812   DebugLoc dl = N->getDebugLoc();
11813   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11814   switch (N->getOpcode()) {
11815   default:
11816     llvm_unreachable("Do not know how to custom type legalize this operation!");
11817   case ISD::SIGN_EXTEND_INREG:
11818   case ISD::ADDC:
11819   case ISD::ADDE:
11820   case ISD::SUBC:
11821   case ISD::SUBE:
11822     // We don't want to expand or promote these.
11823     return;
11824   case ISD::FP_TO_SINT:
11825   case ISD::FP_TO_UINT: {
11826     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11827
11828     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11829       return;
11830
11831     std::pair<SDValue,SDValue> Vals =
11832         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11833     SDValue FIST = Vals.first, StackSlot = Vals.second;
11834     if (FIST.getNode() != 0) {
11835       EVT VT = N->getValueType(0);
11836       // Return a load from the stack slot.
11837       if (StackSlot.getNode() != 0)
11838         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11839                                       MachinePointerInfo(),
11840                                       false, false, false, 0));
11841       else
11842         Results.push_back(FIST);
11843     }
11844     return;
11845   }
11846   case ISD::UINT_TO_FP: {
11847     if (N->getOperand(0).getValueType() != MVT::v2i32 &&
11848         N->getValueType(0) != MVT::v2f32)
11849       return;
11850     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
11851                                  N->getOperand(0));
11852     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11853                                      MVT::f64);
11854     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
11855     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
11856                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
11857     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
11858     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
11859     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
11860     return;
11861   }
11862   case ISD::FP_ROUND: {
11863     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
11864         return;
11865     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11866     Results.push_back(V);
11867     return;
11868   }
11869   case ISD::READCYCLECOUNTER: {
11870     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11871     SDValue TheChain = N->getOperand(0);
11872     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11873     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11874                                      rd.getValue(1));
11875     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11876                                      eax.getValue(2));
11877     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11878     SDValue Ops[] = { eax, edx };
11879     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11880     Results.push_back(edx.getValue(1));
11881     return;
11882   }
11883   case ISD::ATOMIC_CMP_SWAP: {
11884     EVT T = N->getValueType(0);
11885     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11886     bool Regs64bit = T == MVT::i128;
11887     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11888     SDValue cpInL, cpInH;
11889     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11890                         DAG.getConstant(0, HalfT));
11891     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11892                         DAG.getConstant(1, HalfT));
11893     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11894                              Regs64bit ? X86::RAX : X86::EAX,
11895                              cpInL, SDValue());
11896     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11897                              Regs64bit ? X86::RDX : X86::EDX,
11898                              cpInH, cpInL.getValue(1));
11899     SDValue swapInL, swapInH;
11900     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11901                           DAG.getConstant(0, HalfT));
11902     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11903                           DAG.getConstant(1, HalfT));
11904     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11905                                Regs64bit ? X86::RBX : X86::EBX,
11906                                swapInL, cpInH.getValue(1));
11907     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11908                                Regs64bit ? X86::RCX : X86::ECX,
11909                                swapInH, swapInL.getValue(1));
11910     SDValue Ops[] = { swapInH.getValue(0),
11911                       N->getOperand(1),
11912                       swapInH.getValue(1) };
11913     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11914     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11915     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11916                                   X86ISD::LCMPXCHG8_DAG;
11917     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11918                                              Ops, 3, T, MMO);
11919     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11920                                         Regs64bit ? X86::RAX : X86::EAX,
11921                                         HalfT, Result.getValue(1));
11922     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11923                                         Regs64bit ? X86::RDX : X86::EDX,
11924                                         HalfT, cpOutL.getValue(2));
11925     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11926     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11927     Results.push_back(cpOutH.getValue(1));
11928     return;
11929   }
11930   case ISD::ATOMIC_LOAD_ADD:
11931   case ISD::ATOMIC_LOAD_AND:
11932   case ISD::ATOMIC_LOAD_NAND:
11933   case ISD::ATOMIC_LOAD_OR:
11934   case ISD::ATOMIC_LOAD_SUB:
11935   case ISD::ATOMIC_LOAD_XOR:
11936   case ISD::ATOMIC_LOAD_MAX:
11937   case ISD::ATOMIC_LOAD_MIN:
11938   case ISD::ATOMIC_LOAD_UMAX:
11939   case ISD::ATOMIC_LOAD_UMIN:
11940   case ISD::ATOMIC_SWAP: {
11941     unsigned Opc;
11942     switch (N->getOpcode()) {
11943     default: llvm_unreachable("Unexpected opcode");
11944     case ISD::ATOMIC_LOAD_ADD:
11945       Opc = X86ISD::ATOMADD64_DAG;
11946       break;
11947     case ISD::ATOMIC_LOAD_AND:
11948       Opc = X86ISD::ATOMAND64_DAG;
11949       break;
11950     case ISD::ATOMIC_LOAD_NAND:
11951       Opc = X86ISD::ATOMNAND64_DAG;
11952       break;
11953     case ISD::ATOMIC_LOAD_OR:
11954       Opc = X86ISD::ATOMOR64_DAG;
11955       break;
11956     case ISD::ATOMIC_LOAD_SUB:
11957       Opc = X86ISD::ATOMSUB64_DAG;
11958       break;
11959     case ISD::ATOMIC_LOAD_XOR:
11960       Opc = X86ISD::ATOMXOR64_DAG;
11961       break;
11962     case ISD::ATOMIC_LOAD_MAX:
11963       Opc = X86ISD::ATOMMAX64_DAG;
11964       break;
11965     case ISD::ATOMIC_LOAD_MIN:
11966       Opc = X86ISD::ATOMMIN64_DAG;
11967       break;
11968     case ISD::ATOMIC_LOAD_UMAX:
11969       Opc = X86ISD::ATOMUMAX64_DAG;
11970       break;
11971     case ISD::ATOMIC_LOAD_UMIN:
11972       Opc = X86ISD::ATOMUMIN64_DAG;
11973       break;
11974     case ISD::ATOMIC_SWAP:
11975       Opc = X86ISD::ATOMSWAP64_DAG;
11976       break;
11977     }
11978     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11979     return;
11980   }
11981   case ISD::ATOMIC_LOAD:
11982     ReplaceATOMIC_LOAD(N, Results, DAG);
11983   }
11984 }
11985
11986 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11987   switch (Opcode) {
11988   default: return NULL;
11989   case X86ISD::BSF:                return "X86ISD::BSF";
11990   case X86ISD::BSR:                return "X86ISD::BSR";
11991   case X86ISD::SHLD:               return "X86ISD::SHLD";
11992   case X86ISD::SHRD:               return "X86ISD::SHRD";
11993   case X86ISD::FAND:               return "X86ISD::FAND";
11994   case X86ISD::FOR:                return "X86ISD::FOR";
11995   case X86ISD::FXOR:               return "X86ISD::FXOR";
11996   case X86ISD::FSRL:               return "X86ISD::FSRL";
11997   case X86ISD::FILD:               return "X86ISD::FILD";
11998   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11999   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12000   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12001   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12002   case X86ISD::FLD:                return "X86ISD::FLD";
12003   case X86ISD::FST:                return "X86ISD::FST";
12004   case X86ISD::CALL:               return "X86ISD::CALL";
12005   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12006   case X86ISD::BT:                 return "X86ISD::BT";
12007   case X86ISD::CMP:                return "X86ISD::CMP";
12008   case X86ISD::COMI:               return "X86ISD::COMI";
12009   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12010   case X86ISD::SETCC:              return "X86ISD::SETCC";
12011   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12012   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12013   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12014   case X86ISD::CMOV:               return "X86ISD::CMOV";
12015   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12016   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12017   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12018   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12019   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12020   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12021   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12022   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12023   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12024   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12025   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12026   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12027   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12028   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12029   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12030   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12031   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12032   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12033   case X86ISD::HADD:               return "X86ISD::HADD";
12034   case X86ISD::HSUB:               return "X86ISD::HSUB";
12035   case X86ISD::FHADD:              return "X86ISD::FHADD";
12036   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12037   case X86ISD::UMAX:               return "X86ISD::UMAX";
12038   case X86ISD::UMIN:               return "X86ISD::UMIN";
12039   case X86ISD::SMAX:               return "X86ISD::SMAX";
12040   case X86ISD::SMIN:               return "X86ISD::SMIN";
12041   case X86ISD::FMAX:               return "X86ISD::FMAX";
12042   case X86ISD::FMIN:               return "X86ISD::FMIN";
12043   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12044   case X86ISD::FMINC:              return "X86ISD::FMINC";
12045   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12046   case X86ISD::FRCP:               return "X86ISD::FRCP";
12047   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12048   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12049   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12050   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12051   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12052   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12053   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12054   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12055   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12056   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12057   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12058   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12059   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12060   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12061   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12062   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12063   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12064   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12065   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12066   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12067   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12068   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12069   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12070   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12071   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12072   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12073   case X86ISD::VSHL:               return "X86ISD::VSHL";
12074   case X86ISD::VSRL:               return "X86ISD::VSRL";
12075   case X86ISD::VSRA:               return "X86ISD::VSRA";
12076   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12077   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12078   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12079   case X86ISD::CMPP:               return "X86ISD::CMPP";
12080   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12081   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12082   case X86ISD::ADD:                return "X86ISD::ADD";
12083   case X86ISD::SUB:                return "X86ISD::SUB";
12084   case X86ISD::ADC:                return "X86ISD::ADC";
12085   case X86ISD::SBB:                return "X86ISD::SBB";
12086   case X86ISD::SMUL:               return "X86ISD::SMUL";
12087   case X86ISD::UMUL:               return "X86ISD::UMUL";
12088   case X86ISD::INC:                return "X86ISD::INC";
12089   case X86ISD::DEC:                return "X86ISD::DEC";
12090   case X86ISD::OR:                 return "X86ISD::OR";
12091   case X86ISD::XOR:                return "X86ISD::XOR";
12092   case X86ISD::AND:                return "X86ISD::AND";
12093   case X86ISD::BLSI:               return "X86ISD::BLSI";
12094   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12095   case X86ISD::BLSR:               return "X86ISD::BLSR";
12096   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12097   case X86ISD::PTEST:              return "X86ISD::PTEST";
12098   case X86ISD::TESTP:              return "X86ISD::TESTP";
12099   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
12100   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12101   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12102   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12103   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12104   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12105   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12106   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12107   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12108   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12109   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12110   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12111   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12112   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12113   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12114   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12115   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12116   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12117   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12118   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12119   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12120   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12121   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12122   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12123   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12124   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12125   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12126   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12127   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12128   case X86ISD::SAHF:               return "X86ISD::SAHF";
12129   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12130   case X86ISD::FMADD:              return "X86ISD::FMADD";
12131   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12132   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12133   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12134   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12135   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12136   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12137   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12138   }
12139 }
12140
12141 // isLegalAddressingMode - Return true if the addressing mode represented
12142 // by AM is legal for this target, for a load/store of the specified type.
12143 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12144                                               Type *Ty) const {
12145   // X86 supports extremely general addressing modes.
12146   CodeModel::Model M = getTargetMachine().getCodeModel();
12147   Reloc::Model R = getTargetMachine().getRelocationModel();
12148
12149   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12150   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12151     return false;
12152
12153   if (AM.BaseGV) {
12154     unsigned GVFlags =
12155       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12156
12157     // If a reference to this global requires an extra load, we can't fold it.
12158     if (isGlobalStubReference(GVFlags))
12159       return false;
12160
12161     // If BaseGV requires a register for the PIC base, we cannot also have a
12162     // BaseReg specified.
12163     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12164       return false;
12165
12166     // If lower 4G is not available, then we must use rip-relative addressing.
12167     if ((M != CodeModel::Small || R != Reloc::Static) &&
12168         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12169       return false;
12170   }
12171
12172   switch (AM.Scale) {
12173   case 0:
12174   case 1:
12175   case 2:
12176   case 4:
12177   case 8:
12178     // These scales always work.
12179     break;
12180   case 3:
12181   case 5:
12182   case 9:
12183     // These scales are formed with basereg+scalereg.  Only accept if there is
12184     // no basereg yet.
12185     if (AM.HasBaseReg)
12186       return false;
12187     break;
12188   default:  // Other stuff never works.
12189     return false;
12190   }
12191
12192   return true;
12193 }
12194
12195 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12196   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12197     return false;
12198   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12199   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12200   if (NumBits1 <= NumBits2)
12201     return false;
12202   return true;
12203 }
12204
12205 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12206   return Imm == (int32_t)Imm;
12207 }
12208
12209 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12210   // Can also use sub to handle negated immediates.
12211   return Imm == (int32_t)Imm;
12212 }
12213
12214 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12215   if (!VT1.isInteger() || !VT2.isInteger())
12216     return false;
12217   unsigned NumBits1 = VT1.getSizeInBits();
12218   unsigned NumBits2 = VT2.getSizeInBits();
12219   if (NumBits1 <= NumBits2)
12220     return false;
12221   return true;
12222 }
12223
12224 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12225   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12226   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12227 }
12228
12229 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12230   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12231   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12232 }
12233
12234 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12235   EVT VT1 = Val.getValueType();
12236   if (isZExtFree(VT1, VT2))
12237     return true;
12238
12239   if (Val.getOpcode() != ISD::LOAD)
12240     return false;
12241
12242   if (!VT1.isSimple() || !VT1.isInteger() ||
12243       !VT2.isSimple() || !VT2.isInteger())
12244     return false;
12245
12246   switch (VT1.getSimpleVT().SimpleTy) {
12247   default: break;
12248   case MVT::i8:
12249   case MVT::i16:
12250   case MVT::i32:
12251     // X86 has 8, 16, and 32-bit zero-extending loads.
12252     return true;
12253   }
12254
12255   return false;
12256 }
12257
12258 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12259   // i16 instructions are longer (0x66 prefix) and potentially slower.
12260   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12261 }
12262
12263 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12264 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12265 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12266 /// are assumed to be legal.
12267 bool
12268 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12269                                       EVT VT) const {
12270   // Very little shuffling can be done for 64-bit vectors right now.
12271   if (VT.getSizeInBits() == 64)
12272     return false;
12273
12274   // FIXME: pshufb, blends, shifts.
12275   return (VT.getVectorNumElements() == 2 ||
12276           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12277           isMOVLMask(M, VT) ||
12278           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12279           isPSHUFDMask(M, VT) ||
12280           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12281           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12282           isPALIGNRMask(M, VT, Subtarget) ||
12283           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12284           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12285           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12286           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12287 }
12288
12289 bool
12290 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12291                                           EVT VT) const {
12292   unsigned NumElts = VT.getVectorNumElements();
12293   // FIXME: This collection of masks seems suspect.
12294   if (NumElts == 2)
12295     return true;
12296   if (NumElts == 4 && VT.is128BitVector()) {
12297     return (isMOVLMask(Mask, VT)  ||
12298             isCommutedMOVLMask(Mask, VT, true) ||
12299             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12300             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12301   }
12302   return false;
12303 }
12304
12305 //===----------------------------------------------------------------------===//
12306 //                           X86 Scheduler Hooks
12307 //===----------------------------------------------------------------------===//
12308
12309 /// Utility function to emit xbegin specifying the start of an RTM region.
12310 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12311                                      const TargetInstrInfo *TII) {
12312   DebugLoc DL = MI->getDebugLoc();
12313
12314   const BasicBlock *BB = MBB->getBasicBlock();
12315   MachineFunction::iterator I = MBB;
12316   ++I;
12317
12318   // For the v = xbegin(), we generate
12319   //
12320   // thisMBB:
12321   //  xbegin sinkMBB
12322   //
12323   // mainMBB:
12324   //  eax = -1
12325   //
12326   // sinkMBB:
12327   //  v = eax
12328
12329   MachineBasicBlock *thisMBB = MBB;
12330   MachineFunction *MF = MBB->getParent();
12331   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12332   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12333   MF->insert(I, mainMBB);
12334   MF->insert(I, sinkMBB);
12335
12336   // Transfer the remainder of BB and its successor edges to sinkMBB.
12337   sinkMBB->splice(sinkMBB->begin(), MBB,
12338                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12339   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12340
12341   // thisMBB:
12342   //  xbegin sinkMBB
12343   //  # fallthrough to mainMBB
12344   //  # abortion to sinkMBB
12345   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12346   thisMBB->addSuccessor(mainMBB);
12347   thisMBB->addSuccessor(sinkMBB);
12348
12349   // mainMBB:
12350   //  EAX = -1
12351   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12352   mainMBB->addSuccessor(sinkMBB);
12353
12354   // sinkMBB:
12355   // EAX is live into the sinkMBB
12356   sinkMBB->addLiveIn(X86::EAX);
12357   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12358           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12359     .addReg(X86::EAX);
12360
12361   MI->eraseFromParent();
12362   return sinkMBB;
12363 }
12364
12365 // Get CMPXCHG opcode for the specified data type.
12366 static unsigned getCmpXChgOpcode(EVT VT) {
12367   switch (VT.getSimpleVT().SimpleTy) {
12368   case MVT::i8:  return X86::LCMPXCHG8;
12369   case MVT::i16: return X86::LCMPXCHG16;
12370   case MVT::i32: return X86::LCMPXCHG32;
12371   case MVT::i64: return X86::LCMPXCHG64;
12372   default:
12373     break;
12374   }
12375   llvm_unreachable("Invalid operand size!");
12376 }
12377
12378 // Get LOAD opcode for the specified data type.
12379 static unsigned getLoadOpcode(EVT VT) {
12380   switch (VT.getSimpleVT().SimpleTy) {
12381   case MVT::i8:  return X86::MOV8rm;
12382   case MVT::i16: return X86::MOV16rm;
12383   case MVT::i32: return X86::MOV32rm;
12384   case MVT::i64: return X86::MOV64rm;
12385   default:
12386     break;
12387   }
12388   llvm_unreachable("Invalid operand size!");
12389 }
12390
12391 // Get opcode of the non-atomic one from the specified atomic instruction.
12392 static unsigned getNonAtomicOpcode(unsigned Opc) {
12393   switch (Opc) {
12394   case X86::ATOMAND8:  return X86::AND8rr;
12395   case X86::ATOMAND16: return X86::AND16rr;
12396   case X86::ATOMAND32: return X86::AND32rr;
12397   case X86::ATOMAND64: return X86::AND64rr;
12398   case X86::ATOMOR8:   return X86::OR8rr;
12399   case X86::ATOMOR16:  return X86::OR16rr;
12400   case X86::ATOMOR32:  return X86::OR32rr;
12401   case X86::ATOMOR64:  return X86::OR64rr;
12402   case X86::ATOMXOR8:  return X86::XOR8rr;
12403   case X86::ATOMXOR16: return X86::XOR16rr;
12404   case X86::ATOMXOR32: return X86::XOR32rr;
12405   case X86::ATOMXOR64: return X86::XOR64rr;
12406   }
12407   llvm_unreachable("Unhandled atomic-load-op opcode!");
12408 }
12409
12410 // Get opcode of the non-atomic one from the specified atomic instruction with
12411 // extra opcode.
12412 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12413                                                unsigned &ExtraOpc) {
12414   switch (Opc) {
12415   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12416   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12417   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12418   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12419   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12420   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12421   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12422   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12423   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12424   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12425   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12426   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12427   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12428   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12429   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12430   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12431   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12432   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12433   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12434   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12435   }
12436   llvm_unreachable("Unhandled atomic-load-op opcode!");
12437 }
12438
12439 // Get opcode of the non-atomic one from the specified atomic instruction for
12440 // 64-bit data type on 32-bit target.
12441 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12442   switch (Opc) {
12443   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12444   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12445   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12446   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12447   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12448   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12449   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12450   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12451   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12452   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12453   }
12454   llvm_unreachable("Unhandled atomic-load-op opcode!");
12455 }
12456
12457 // Get opcode of the non-atomic one from the specified atomic instruction for
12458 // 64-bit data type on 32-bit target with extra opcode.
12459 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12460                                                    unsigned &HiOpc,
12461                                                    unsigned &ExtraOpc) {
12462   switch (Opc) {
12463   case X86::ATOMNAND6432:
12464     ExtraOpc = X86::NOT32r;
12465     HiOpc = X86::AND32rr;
12466     return X86::AND32rr;
12467   }
12468   llvm_unreachable("Unhandled atomic-load-op opcode!");
12469 }
12470
12471 // Get pseudo CMOV opcode from the specified data type.
12472 static unsigned getPseudoCMOVOpc(EVT VT) {
12473   switch (VT.getSimpleVT().SimpleTy) {
12474   case MVT::i8:  return X86::CMOV_GR8;
12475   case MVT::i16: return X86::CMOV_GR16;
12476   case MVT::i32: return X86::CMOV_GR32;
12477   default:
12478     break;
12479   }
12480   llvm_unreachable("Unknown CMOV opcode!");
12481 }
12482
12483 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12484 // They will be translated into a spin-loop or compare-exchange loop from
12485 //
12486 //    ...
12487 //    dst = atomic-fetch-op MI.addr, MI.val
12488 //    ...
12489 //
12490 // to
12491 //
12492 //    ...
12493 //    EAX = LOAD MI.addr
12494 // loop:
12495 //    t1 = OP MI.val, EAX
12496 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12497 //    JNE loop
12498 // sink:
12499 //    dst = EAX
12500 //    ...
12501 MachineBasicBlock *
12502 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12503                                        MachineBasicBlock *MBB) const {
12504   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12505   DebugLoc DL = MI->getDebugLoc();
12506
12507   MachineFunction *MF = MBB->getParent();
12508   MachineRegisterInfo &MRI = MF->getRegInfo();
12509
12510   const BasicBlock *BB = MBB->getBasicBlock();
12511   MachineFunction::iterator I = MBB;
12512   ++I;
12513
12514   assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12515          "Unexpected number of operands");
12516
12517   assert(MI->hasOneMemOperand() &&
12518          "Expected atomic-load-op to have one memoperand");
12519
12520   // Memory Reference
12521   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12522   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12523
12524   unsigned DstReg, SrcReg;
12525   unsigned MemOpndSlot;
12526
12527   unsigned CurOp = 0;
12528
12529   DstReg = MI->getOperand(CurOp++).getReg();
12530   MemOpndSlot = CurOp;
12531   CurOp += X86::AddrNumOperands;
12532   SrcReg = MI->getOperand(CurOp++).getReg();
12533
12534   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12535   MVT::SimpleValueType VT = *RC->vt_begin();
12536   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12537
12538   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12539   unsigned LOADOpc = getLoadOpcode(VT);
12540
12541   // For the atomic load-arith operator, we generate
12542   //
12543   //  thisMBB:
12544   //    EAX = LOAD [MI.addr]
12545   //  mainMBB:
12546   //    t1 = OP MI.val, EAX
12547   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12548   //    JNE mainMBB
12549   //  sinkMBB:
12550
12551   MachineBasicBlock *thisMBB = MBB;
12552   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12553   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12554   MF->insert(I, mainMBB);
12555   MF->insert(I, sinkMBB);
12556
12557   MachineInstrBuilder MIB;
12558
12559   // Transfer the remainder of BB and its successor edges to sinkMBB.
12560   sinkMBB->splice(sinkMBB->begin(), MBB,
12561                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12562   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12563
12564   // thisMBB:
12565   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12566   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12567     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12568   MIB.setMemRefs(MMOBegin, MMOEnd);
12569
12570   thisMBB->addSuccessor(mainMBB);
12571
12572   // mainMBB:
12573   MachineBasicBlock *origMainMBB = mainMBB;
12574   mainMBB->addLiveIn(AccPhyReg);
12575
12576   // Copy AccPhyReg as it is used more than once.
12577   unsigned AccReg = MRI.createVirtualRegister(RC);
12578   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12579     .addReg(AccPhyReg);
12580
12581   unsigned t1 = MRI.createVirtualRegister(RC);
12582   unsigned Opc = MI->getOpcode();
12583   switch (Opc) {
12584   default:
12585     llvm_unreachable("Unhandled atomic-load-op opcode!");
12586   case X86::ATOMAND8:
12587   case X86::ATOMAND16:
12588   case X86::ATOMAND32:
12589   case X86::ATOMAND64:
12590   case X86::ATOMOR8:
12591   case X86::ATOMOR16:
12592   case X86::ATOMOR32:
12593   case X86::ATOMOR64:
12594   case X86::ATOMXOR8:
12595   case X86::ATOMXOR16:
12596   case X86::ATOMXOR32:
12597   case X86::ATOMXOR64: {
12598     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12599     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12600       .addReg(AccReg);
12601     break;
12602   }
12603   case X86::ATOMNAND8:
12604   case X86::ATOMNAND16:
12605   case X86::ATOMNAND32:
12606   case X86::ATOMNAND64: {
12607     unsigned t2 = MRI.createVirtualRegister(RC);
12608     unsigned NOTOpc;
12609     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12610     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12611       .addReg(AccReg);
12612     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12613     break;
12614   }
12615   case X86::ATOMMAX8:
12616   case X86::ATOMMAX16:
12617   case X86::ATOMMAX32:
12618   case X86::ATOMMAX64:
12619   case X86::ATOMMIN8:
12620   case X86::ATOMMIN16:
12621   case X86::ATOMMIN32:
12622   case X86::ATOMMIN64:
12623   case X86::ATOMUMAX8:
12624   case X86::ATOMUMAX16:
12625   case X86::ATOMUMAX32:
12626   case X86::ATOMUMAX64:
12627   case X86::ATOMUMIN8:
12628   case X86::ATOMUMIN16:
12629   case X86::ATOMUMIN32:
12630   case X86::ATOMUMIN64: {
12631     unsigned CMPOpc;
12632     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12633
12634     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12635       .addReg(SrcReg)
12636       .addReg(AccReg);
12637
12638     if (Subtarget->hasCMov()) {
12639       if (VT != MVT::i8) {
12640         // Native support
12641         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12642           .addReg(SrcReg)
12643           .addReg(AccReg);
12644       } else {
12645         // Promote i8 to i32 to use CMOV32
12646         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12647         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12648         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12649         unsigned t2 = MRI.createVirtualRegister(RC32);
12650
12651         unsigned Undef = MRI.createVirtualRegister(RC32);
12652         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12653
12654         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12655           .addReg(Undef)
12656           .addReg(SrcReg)
12657           .addImm(X86::sub_8bit);
12658         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12659           .addReg(Undef)
12660           .addReg(AccReg)
12661           .addImm(X86::sub_8bit);
12662
12663         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12664           .addReg(SrcReg32)
12665           .addReg(AccReg32);
12666
12667         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12668           .addReg(t2, 0, X86::sub_8bit);
12669       }
12670     } else {
12671       // Use pseudo select and lower them.
12672       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12673              "Invalid atomic-load-op transformation!");
12674       unsigned SelOpc = getPseudoCMOVOpc(VT);
12675       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12676       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12677       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12678               .addReg(SrcReg).addReg(AccReg)
12679               .addImm(CC);
12680       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12681     }
12682     break;
12683   }
12684   }
12685
12686   // Copy AccPhyReg back from virtual register.
12687   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12688     .addReg(AccReg);
12689
12690   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12691   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12692     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12693   MIB.addReg(t1);
12694   MIB.setMemRefs(MMOBegin, MMOEnd);
12695
12696   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12697
12698   mainMBB->addSuccessor(origMainMBB);
12699   mainMBB->addSuccessor(sinkMBB);
12700
12701   // sinkMBB:
12702   sinkMBB->addLiveIn(AccPhyReg);
12703
12704   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12705           TII->get(TargetOpcode::COPY), DstReg)
12706     .addReg(AccPhyReg);
12707
12708   MI->eraseFromParent();
12709   return sinkMBB;
12710 }
12711
12712 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12713 // instructions. They will be translated into a spin-loop or compare-exchange
12714 // loop from
12715 //
12716 //    ...
12717 //    dst = atomic-fetch-op MI.addr, MI.val
12718 //    ...
12719 //
12720 // to
12721 //
12722 //    ...
12723 //    EAX = LOAD [MI.addr + 0]
12724 //    EDX = LOAD [MI.addr + 4]
12725 // loop:
12726 //    EBX = OP MI.val.lo, EAX
12727 //    ECX = OP MI.val.hi, EDX
12728 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12729 //    JNE loop
12730 // sink:
12731 //    dst = EDX:EAX
12732 //    ...
12733 MachineBasicBlock *
12734 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12735                                            MachineBasicBlock *MBB) const {
12736   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12737   DebugLoc DL = MI->getDebugLoc();
12738
12739   MachineFunction *MF = MBB->getParent();
12740   MachineRegisterInfo &MRI = MF->getRegInfo();
12741
12742   const BasicBlock *BB = MBB->getBasicBlock();
12743   MachineFunction::iterator I = MBB;
12744   ++I;
12745
12746   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12747          "Unexpected number of operands");
12748
12749   assert(MI->hasOneMemOperand() &&
12750          "Expected atomic-load-op32 to have one memoperand");
12751
12752   // Memory Reference
12753   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12754   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12755
12756   unsigned DstLoReg, DstHiReg;
12757   unsigned SrcLoReg, SrcHiReg;
12758   unsigned MemOpndSlot;
12759
12760   unsigned CurOp = 0;
12761
12762   DstLoReg = MI->getOperand(CurOp++).getReg();
12763   DstHiReg = MI->getOperand(CurOp++).getReg();
12764   MemOpndSlot = CurOp;
12765   CurOp += X86::AddrNumOperands;
12766   SrcLoReg = MI->getOperand(CurOp++).getReg();
12767   SrcHiReg = MI->getOperand(CurOp++).getReg();
12768
12769   const TargetRegisterClass *RC = &X86::GR32RegClass;
12770   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12771
12772   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12773   unsigned LOADOpc = X86::MOV32rm;
12774
12775   // For the atomic load-arith operator, we generate
12776   //
12777   //  thisMBB:
12778   //    EAX = LOAD [MI.addr + 0]
12779   //    EDX = LOAD [MI.addr + 4]
12780   //  mainMBB:
12781   //    EBX = OP MI.vallo, EAX
12782   //    ECX = OP MI.valhi, EDX
12783   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12784   //    JNE mainMBB
12785   //  sinkMBB:
12786
12787   MachineBasicBlock *thisMBB = MBB;
12788   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12789   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12790   MF->insert(I, mainMBB);
12791   MF->insert(I, sinkMBB);
12792
12793   MachineInstrBuilder MIB;
12794
12795   // Transfer the remainder of BB and its successor edges to sinkMBB.
12796   sinkMBB->splice(sinkMBB->begin(), MBB,
12797                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12798   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12799
12800   // thisMBB:
12801   // Lo
12802   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12803   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12804     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12805   MIB.setMemRefs(MMOBegin, MMOEnd);
12806   // Hi
12807   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12808   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12809     if (i == X86::AddrDisp)
12810       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12811     else
12812       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12813   }
12814   MIB.setMemRefs(MMOBegin, MMOEnd);
12815
12816   thisMBB->addSuccessor(mainMBB);
12817
12818   // mainMBB:
12819   MachineBasicBlock *origMainMBB = mainMBB;
12820   mainMBB->addLiveIn(X86::EAX);
12821   mainMBB->addLiveIn(X86::EDX);
12822
12823   // Copy EDX:EAX as they are used more than once.
12824   unsigned LoReg = MRI.createVirtualRegister(RC);
12825   unsigned HiReg = MRI.createVirtualRegister(RC);
12826   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12827   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12828
12829   unsigned t1L = MRI.createVirtualRegister(RC);
12830   unsigned t1H = MRI.createVirtualRegister(RC);
12831
12832   unsigned Opc = MI->getOpcode();
12833   switch (Opc) {
12834   default:
12835     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12836   case X86::ATOMAND6432:
12837   case X86::ATOMOR6432:
12838   case X86::ATOMXOR6432:
12839   case X86::ATOMADD6432:
12840   case X86::ATOMSUB6432: {
12841     unsigned HiOpc;
12842     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12843     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
12844     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
12845     break;
12846   }
12847   case X86::ATOMNAND6432: {
12848     unsigned HiOpc, NOTOpc;
12849     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12850     unsigned t2L = MRI.createVirtualRegister(RC);
12851     unsigned t2H = MRI.createVirtualRegister(RC);
12852     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12853     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12854     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12855     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12856     break;
12857   }
12858   case X86::ATOMMAX6432:
12859   case X86::ATOMMIN6432:
12860   case X86::ATOMUMAX6432:
12861   case X86::ATOMUMIN6432: {
12862     unsigned HiOpc;
12863     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12864     unsigned cL = MRI.createVirtualRegister(RC8);
12865     unsigned cH = MRI.createVirtualRegister(RC8);
12866     unsigned cL32 = MRI.createVirtualRegister(RC);
12867     unsigned cH32 = MRI.createVirtualRegister(RC);
12868     unsigned cc = MRI.createVirtualRegister(RC);
12869     // cl := cmp src_lo, lo
12870     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12871       .addReg(SrcLoReg).addReg(LoReg);
12872     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12873     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12874     // ch := cmp src_hi, hi
12875     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12876       .addReg(SrcHiReg).addReg(HiReg);
12877     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12878     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12879     // cc := if (src_hi == hi) ? cl : ch;
12880     if (Subtarget->hasCMov()) {
12881       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12882         .addReg(cH32).addReg(cL32);
12883     } else {
12884       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12885               .addReg(cH32).addReg(cL32)
12886               .addImm(X86::COND_E);
12887       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12888     }
12889     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12890     if (Subtarget->hasCMov()) {
12891       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12892         .addReg(SrcLoReg).addReg(LoReg);
12893       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12894         .addReg(SrcHiReg).addReg(HiReg);
12895     } else {
12896       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12897               .addReg(SrcLoReg).addReg(LoReg)
12898               .addImm(X86::COND_NE);
12899       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12900       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12901               .addReg(SrcHiReg).addReg(HiReg)
12902               .addImm(X86::COND_NE);
12903       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12904     }
12905     break;
12906   }
12907   case X86::ATOMSWAP6432: {
12908     unsigned HiOpc;
12909     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12910     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12911     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12912     break;
12913   }
12914   }
12915
12916   // Copy EDX:EAX back from HiReg:LoReg
12917   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12918   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12919   // Copy ECX:EBX from t1H:t1L
12920   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12921   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12922
12923   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12924   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12925     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12926   MIB.setMemRefs(MMOBegin, MMOEnd);
12927
12928   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12929
12930   mainMBB->addSuccessor(origMainMBB);
12931   mainMBB->addSuccessor(sinkMBB);
12932
12933   // sinkMBB:
12934   sinkMBB->addLiveIn(X86::EAX);
12935   sinkMBB->addLiveIn(X86::EDX);
12936
12937   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12938           TII->get(TargetOpcode::COPY), DstLoReg)
12939     .addReg(X86::EAX);
12940   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12941           TII->get(TargetOpcode::COPY), DstHiReg)
12942     .addReg(X86::EDX);
12943
12944   MI->eraseFromParent();
12945   return sinkMBB;
12946 }
12947
12948 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12949 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12950 // in the .td file.
12951 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
12952                                        const TargetInstrInfo *TII) {
12953   unsigned Opc;
12954   switch (MI->getOpcode()) {
12955   default: llvm_unreachable("illegal opcode!");
12956   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
12957   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
12958   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
12959   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
12960   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
12961   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
12962   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
12963   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
12964   }
12965
12966   DebugLoc dl = MI->getDebugLoc();
12967   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12968
12969   unsigned NumArgs = MI->getNumOperands();
12970   for (unsigned i = 1; i < NumArgs; ++i) {
12971     MachineOperand &Op = MI->getOperand(i);
12972     if (!(Op.isReg() && Op.isImplicit()))
12973       MIB.addOperand(Op);
12974   }
12975   if (MI->hasOneMemOperand())
12976     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
12977
12978   BuildMI(*BB, MI, dl,
12979     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12980     .addReg(X86::XMM0);
12981
12982   MI->eraseFromParent();
12983   return BB;
12984 }
12985
12986 // FIXME: Custom handling because TableGen doesn't support multiple implicit
12987 // defs in an instruction pattern
12988 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
12989                                        const TargetInstrInfo *TII) {
12990   unsigned Opc;
12991   switch (MI->getOpcode()) {
12992   default: llvm_unreachable("illegal opcode!");
12993   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
12994   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
12995   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
12996   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
12997   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
12998   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
12999   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13000   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13001   }
13002
13003   DebugLoc dl = MI->getDebugLoc();
13004   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13005
13006   unsigned NumArgs = MI->getNumOperands(); // remove the results
13007   for (unsigned i = 1; i < NumArgs; ++i) {
13008     MachineOperand &Op = MI->getOperand(i);
13009     if (!(Op.isReg() && Op.isImplicit()))
13010       MIB.addOperand(Op);
13011   }
13012   if (MI->hasOneMemOperand())
13013     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13014
13015   BuildMI(*BB, MI, dl,
13016     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13017     .addReg(X86::ECX);
13018
13019   MI->eraseFromParent();
13020   return BB;
13021 }
13022
13023 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13024                                        const TargetInstrInfo *TII,
13025                                        const X86Subtarget* Subtarget) {
13026   DebugLoc dl = MI->getDebugLoc();
13027
13028   // Address into RAX/EAX, other two args into ECX, EDX.
13029   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13030   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13031   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13032   for (int i = 0; i < X86::AddrNumOperands; ++i)
13033     MIB.addOperand(MI->getOperand(i));
13034
13035   unsigned ValOps = X86::AddrNumOperands;
13036   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13037     .addReg(MI->getOperand(ValOps).getReg());
13038   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13039     .addReg(MI->getOperand(ValOps+1).getReg());
13040
13041   // The instruction doesn't actually take any operands though.
13042   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13043
13044   MI->eraseFromParent(); // The pseudo is gone now.
13045   return BB;
13046 }
13047
13048 MachineBasicBlock *
13049 X86TargetLowering::EmitVAARG64WithCustomInserter(
13050                    MachineInstr *MI,
13051                    MachineBasicBlock *MBB) const {
13052   // Emit va_arg instruction on X86-64.
13053
13054   // Operands to this pseudo-instruction:
13055   // 0  ) Output        : destination address (reg)
13056   // 1-5) Input         : va_list address (addr, i64mem)
13057   // 6  ) ArgSize       : Size (in bytes) of vararg type
13058   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13059   // 8  ) Align         : Alignment of type
13060   // 9  ) EFLAGS (implicit-def)
13061
13062   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13063   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13064
13065   unsigned DestReg = MI->getOperand(0).getReg();
13066   MachineOperand &Base = MI->getOperand(1);
13067   MachineOperand &Scale = MI->getOperand(2);
13068   MachineOperand &Index = MI->getOperand(3);
13069   MachineOperand &Disp = MI->getOperand(4);
13070   MachineOperand &Segment = MI->getOperand(5);
13071   unsigned ArgSize = MI->getOperand(6).getImm();
13072   unsigned ArgMode = MI->getOperand(7).getImm();
13073   unsigned Align = MI->getOperand(8).getImm();
13074
13075   // Memory Reference
13076   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13077   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13078   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13079
13080   // Machine Information
13081   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13082   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13083   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13084   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13085   DebugLoc DL = MI->getDebugLoc();
13086
13087   // struct va_list {
13088   //   i32   gp_offset
13089   //   i32   fp_offset
13090   //   i64   overflow_area (address)
13091   //   i64   reg_save_area (address)
13092   // }
13093   // sizeof(va_list) = 24
13094   // alignment(va_list) = 8
13095
13096   unsigned TotalNumIntRegs = 6;
13097   unsigned TotalNumXMMRegs = 8;
13098   bool UseGPOffset = (ArgMode == 1);
13099   bool UseFPOffset = (ArgMode == 2);
13100   unsigned MaxOffset = TotalNumIntRegs * 8 +
13101                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13102
13103   /* Align ArgSize to a multiple of 8 */
13104   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13105   bool NeedsAlign = (Align > 8);
13106
13107   MachineBasicBlock *thisMBB = MBB;
13108   MachineBasicBlock *overflowMBB;
13109   MachineBasicBlock *offsetMBB;
13110   MachineBasicBlock *endMBB;
13111
13112   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13113   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13114   unsigned OffsetReg = 0;
13115
13116   if (!UseGPOffset && !UseFPOffset) {
13117     // If we only pull from the overflow region, we don't create a branch.
13118     // We don't need to alter control flow.
13119     OffsetDestReg = 0; // unused
13120     OverflowDestReg = DestReg;
13121
13122     offsetMBB = NULL;
13123     overflowMBB = thisMBB;
13124     endMBB = thisMBB;
13125   } else {
13126     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13127     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13128     // If not, pull from overflow_area. (branch to overflowMBB)
13129     //
13130     //       thisMBB
13131     //         |     .
13132     //         |        .
13133     //     offsetMBB   overflowMBB
13134     //         |        .
13135     //         |     .
13136     //        endMBB
13137
13138     // Registers for the PHI in endMBB
13139     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13140     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13141
13142     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13143     MachineFunction *MF = MBB->getParent();
13144     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13145     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13146     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13147
13148     MachineFunction::iterator MBBIter = MBB;
13149     ++MBBIter;
13150
13151     // Insert the new basic blocks
13152     MF->insert(MBBIter, offsetMBB);
13153     MF->insert(MBBIter, overflowMBB);
13154     MF->insert(MBBIter, endMBB);
13155
13156     // Transfer the remainder of MBB and its successor edges to endMBB.
13157     endMBB->splice(endMBB->begin(), thisMBB,
13158                     llvm::next(MachineBasicBlock::iterator(MI)),
13159                     thisMBB->end());
13160     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13161
13162     // Make offsetMBB and overflowMBB successors of thisMBB
13163     thisMBB->addSuccessor(offsetMBB);
13164     thisMBB->addSuccessor(overflowMBB);
13165
13166     // endMBB is a successor of both offsetMBB and overflowMBB
13167     offsetMBB->addSuccessor(endMBB);
13168     overflowMBB->addSuccessor(endMBB);
13169
13170     // Load the offset value into a register
13171     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13172     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13173       .addOperand(Base)
13174       .addOperand(Scale)
13175       .addOperand(Index)
13176       .addDisp(Disp, UseFPOffset ? 4 : 0)
13177       .addOperand(Segment)
13178       .setMemRefs(MMOBegin, MMOEnd);
13179
13180     // Check if there is enough room left to pull this argument.
13181     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13182       .addReg(OffsetReg)
13183       .addImm(MaxOffset + 8 - ArgSizeA8);
13184
13185     // Branch to "overflowMBB" if offset >= max
13186     // Fall through to "offsetMBB" otherwise
13187     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13188       .addMBB(overflowMBB);
13189   }
13190
13191   // In offsetMBB, emit code to use the reg_save_area.
13192   if (offsetMBB) {
13193     assert(OffsetReg != 0);
13194
13195     // Read the reg_save_area address.
13196     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13197     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13198       .addOperand(Base)
13199       .addOperand(Scale)
13200       .addOperand(Index)
13201       .addDisp(Disp, 16)
13202       .addOperand(Segment)
13203       .setMemRefs(MMOBegin, MMOEnd);
13204
13205     // Zero-extend the offset
13206     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13207       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13208         .addImm(0)
13209         .addReg(OffsetReg)
13210         .addImm(X86::sub_32bit);
13211
13212     // Add the offset to the reg_save_area to get the final address.
13213     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13214       .addReg(OffsetReg64)
13215       .addReg(RegSaveReg);
13216
13217     // Compute the offset for the next argument
13218     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13219     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13220       .addReg(OffsetReg)
13221       .addImm(UseFPOffset ? 16 : 8);
13222
13223     // Store it back into the va_list.
13224     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13225       .addOperand(Base)
13226       .addOperand(Scale)
13227       .addOperand(Index)
13228       .addDisp(Disp, UseFPOffset ? 4 : 0)
13229       .addOperand(Segment)
13230       .addReg(NextOffsetReg)
13231       .setMemRefs(MMOBegin, MMOEnd);
13232
13233     // Jump to endMBB
13234     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13235       .addMBB(endMBB);
13236   }
13237
13238   //
13239   // Emit code to use overflow area
13240   //
13241
13242   // Load the overflow_area address into a register.
13243   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13244   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13245     .addOperand(Base)
13246     .addOperand(Scale)
13247     .addOperand(Index)
13248     .addDisp(Disp, 8)
13249     .addOperand(Segment)
13250     .setMemRefs(MMOBegin, MMOEnd);
13251
13252   // If we need to align it, do so. Otherwise, just copy the address
13253   // to OverflowDestReg.
13254   if (NeedsAlign) {
13255     // Align the overflow address
13256     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13257     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13258
13259     // aligned_addr = (addr + (align-1)) & ~(align-1)
13260     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13261       .addReg(OverflowAddrReg)
13262       .addImm(Align-1);
13263
13264     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13265       .addReg(TmpReg)
13266       .addImm(~(uint64_t)(Align-1));
13267   } else {
13268     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13269       .addReg(OverflowAddrReg);
13270   }
13271
13272   // Compute the next overflow address after this argument.
13273   // (the overflow address should be kept 8-byte aligned)
13274   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13275   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13276     .addReg(OverflowDestReg)
13277     .addImm(ArgSizeA8);
13278
13279   // Store the new overflow address.
13280   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13281     .addOperand(Base)
13282     .addOperand(Scale)
13283     .addOperand(Index)
13284     .addDisp(Disp, 8)
13285     .addOperand(Segment)
13286     .addReg(NextAddrReg)
13287     .setMemRefs(MMOBegin, MMOEnd);
13288
13289   // If we branched, emit the PHI to the front of endMBB.
13290   if (offsetMBB) {
13291     BuildMI(*endMBB, endMBB->begin(), DL,
13292             TII->get(X86::PHI), DestReg)
13293       .addReg(OffsetDestReg).addMBB(offsetMBB)
13294       .addReg(OverflowDestReg).addMBB(overflowMBB);
13295   }
13296
13297   // Erase the pseudo instruction
13298   MI->eraseFromParent();
13299
13300   return endMBB;
13301 }
13302
13303 MachineBasicBlock *
13304 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13305                                                  MachineInstr *MI,
13306                                                  MachineBasicBlock *MBB) const {
13307   // Emit code to save XMM registers to the stack. The ABI says that the
13308   // number of registers to save is given in %al, so it's theoretically
13309   // possible to do an indirect jump trick to avoid saving all of them,
13310   // however this code takes a simpler approach and just executes all
13311   // of the stores if %al is non-zero. It's less code, and it's probably
13312   // easier on the hardware branch predictor, and stores aren't all that
13313   // expensive anyway.
13314
13315   // Create the new basic blocks. One block contains all the XMM stores,
13316   // and one block is the final destination regardless of whether any
13317   // stores were performed.
13318   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13319   MachineFunction *F = MBB->getParent();
13320   MachineFunction::iterator MBBIter = MBB;
13321   ++MBBIter;
13322   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13323   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13324   F->insert(MBBIter, XMMSaveMBB);
13325   F->insert(MBBIter, EndMBB);
13326
13327   // Transfer the remainder of MBB and its successor edges to EndMBB.
13328   EndMBB->splice(EndMBB->begin(), MBB,
13329                  llvm::next(MachineBasicBlock::iterator(MI)),
13330                  MBB->end());
13331   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13332
13333   // The original block will now fall through to the XMM save block.
13334   MBB->addSuccessor(XMMSaveMBB);
13335   // The XMMSaveMBB will fall through to the end block.
13336   XMMSaveMBB->addSuccessor(EndMBB);
13337
13338   // Now add the instructions.
13339   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13340   DebugLoc DL = MI->getDebugLoc();
13341
13342   unsigned CountReg = MI->getOperand(0).getReg();
13343   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13344   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13345
13346   if (!Subtarget->isTargetWin64()) {
13347     // If %al is 0, branch around the XMM save block.
13348     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13349     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13350     MBB->addSuccessor(EndMBB);
13351   }
13352
13353   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13354   // In the XMM save block, save all the XMM argument registers.
13355   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13356     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13357     MachineMemOperand *MMO =
13358       F->getMachineMemOperand(
13359           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13360         MachineMemOperand::MOStore,
13361         /*Size=*/16, /*Align=*/16);
13362     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13363       .addFrameIndex(RegSaveFrameIndex)
13364       .addImm(/*Scale=*/1)
13365       .addReg(/*IndexReg=*/0)
13366       .addImm(/*Disp=*/Offset)
13367       .addReg(/*Segment=*/0)
13368       .addReg(MI->getOperand(i).getReg())
13369       .addMemOperand(MMO);
13370   }
13371
13372   MI->eraseFromParent();   // The pseudo instruction is gone now.
13373
13374   return EndMBB;
13375 }
13376
13377 // The EFLAGS operand of SelectItr might be missing a kill marker
13378 // because there were multiple uses of EFLAGS, and ISel didn't know
13379 // which to mark. Figure out whether SelectItr should have had a
13380 // kill marker, and set it if it should. Returns the correct kill
13381 // marker value.
13382 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13383                                      MachineBasicBlock* BB,
13384                                      const TargetRegisterInfo* TRI) {
13385   // Scan forward through BB for a use/def of EFLAGS.
13386   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13387   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13388     const MachineInstr& mi = *miI;
13389     if (mi.readsRegister(X86::EFLAGS))
13390       return false;
13391     if (mi.definesRegister(X86::EFLAGS))
13392       break; // Should have kill-flag - update below.
13393   }
13394
13395   // If we hit the end of the block, check whether EFLAGS is live into a
13396   // successor.
13397   if (miI == BB->end()) {
13398     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13399                                           sEnd = BB->succ_end();
13400          sItr != sEnd; ++sItr) {
13401       MachineBasicBlock* succ = *sItr;
13402       if (succ->isLiveIn(X86::EFLAGS))
13403         return false;
13404     }
13405   }
13406
13407   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13408   // out. SelectMI should have a kill flag on EFLAGS.
13409   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13410   return true;
13411 }
13412
13413 MachineBasicBlock *
13414 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13415                                      MachineBasicBlock *BB) const {
13416   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13417   DebugLoc DL = MI->getDebugLoc();
13418
13419   // To "insert" a SELECT_CC instruction, we actually have to insert the
13420   // diamond control-flow pattern.  The incoming instruction knows the
13421   // destination vreg to set, the condition code register to branch on, the
13422   // true/false values to select between, and a branch opcode to use.
13423   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13424   MachineFunction::iterator It = BB;
13425   ++It;
13426
13427   //  thisMBB:
13428   //  ...
13429   //   TrueVal = ...
13430   //   cmpTY ccX, r1, r2
13431   //   bCC copy1MBB
13432   //   fallthrough --> copy0MBB
13433   MachineBasicBlock *thisMBB = BB;
13434   MachineFunction *F = BB->getParent();
13435   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13436   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13437   F->insert(It, copy0MBB);
13438   F->insert(It, sinkMBB);
13439
13440   // If the EFLAGS register isn't dead in the terminator, then claim that it's
13441   // live into the sink and copy blocks.
13442   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13443   if (!MI->killsRegister(X86::EFLAGS) &&
13444       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13445     copy0MBB->addLiveIn(X86::EFLAGS);
13446     sinkMBB->addLiveIn(X86::EFLAGS);
13447   }
13448
13449   // Transfer the remainder of BB and its successor edges to sinkMBB.
13450   sinkMBB->splice(sinkMBB->begin(), BB,
13451                   llvm::next(MachineBasicBlock::iterator(MI)),
13452                   BB->end());
13453   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13454
13455   // Add the true and fallthrough blocks as its successors.
13456   BB->addSuccessor(copy0MBB);
13457   BB->addSuccessor(sinkMBB);
13458
13459   // Create the conditional branch instruction.
13460   unsigned Opc =
13461     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13462   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13463
13464   //  copy0MBB:
13465   //   %FalseValue = ...
13466   //   # fallthrough to sinkMBB
13467   copy0MBB->addSuccessor(sinkMBB);
13468
13469   //  sinkMBB:
13470   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13471   //  ...
13472   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13473           TII->get(X86::PHI), MI->getOperand(0).getReg())
13474     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13475     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13476
13477   MI->eraseFromParent();   // The pseudo instruction is gone now.
13478   return sinkMBB;
13479 }
13480
13481 MachineBasicBlock *
13482 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13483                                         bool Is64Bit) const {
13484   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13485   DebugLoc DL = MI->getDebugLoc();
13486   MachineFunction *MF = BB->getParent();
13487   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13488
13489   assert(getTargetMachine().Options.EnableSegmentedStacks);
13490
13491   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13492   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13493
13494   // BB:
13495   //  ... [Till the alloca]
13496   // If stacklet is not large enough, jump to mallocMBB
13497   //
13498   // bumpMBB:
13499   //  Allocate by subtracting from RSP
13500   //  Jump to continueMBB
13501   //
13502   // mallocMBB:
13503   //  Allocate by call to runtime
13504   //
13505   // continueMBB:
13506   //  ...
13507   //  [rest of original BB]
13508   //
13509
13510   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13511   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13512   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13513
13514   MachineRegisterInfo &MRI = MF->getRegInfo();
13515   const TargetRegisterClass *AddrRegClass =
13516     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13517
13518   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13519     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13520     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13521     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13522     sizeVReg = MI->getOperand(1).getReg(),
13523     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13524
13525   MachineFunction::iterator MBBIter = BB;
13526   ++MBBIter;
13527
13528   MF->insert(MBBIter, bumpMBB);
13529   MF->insert(MBBIter, mallocMBB);
13530   MF->insert(MBBIter, continueMBB);
13531
13532   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13533                       (MachineBasicBlock::iterator(MI)), BB->end());
13534   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13535
13536   // Add code to the main basic block to check if the stack limit has been hit,
13537   // and if so, jump to mallocMBB otherwise to bumpMBB.
13538   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13539   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13540     .addReg(tmpSPVReg).addReg(sizeVReg);
13541   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13542     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13543     .addReg(SPLimitVReg);
13544   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13545
13546   // bumpMBB simply decreases the stack pointer, since we know the current
13547   // stacklet has enough space.
13548   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13549     .addReg(SPLimitVReg);
13550   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13551     .addReg(SPLimitVReg);
13552   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13553
13554   // Calls into a routine in libgcc to allocate more space from the heap.
13555   const uint32_t *RegMask =
13556     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13557   if (Is64Bit) {
13558     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13559       .addReg(sizeVReg);
13560     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13561       .addExternalSymbol("__morestack_allocate_stack_space")
13562       .addRegMask(RegMask)
13563       .addReg(X86::RDI, RegState::Implicit)
13564       .addReg(X86::RAX, RegState::ImplicitDefine);
13565   } else {
13566     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13567       .addImm(12);
13568     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13569     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13570       .addExternalSymbol("__morestack_allocate_stack_space")
13571       .addRegMask(RegMask)
13572       .addReg(X86::EAX, RegState::ImplicitDefine);
13573   }
13574
13575   if (!Is64Bit)
13576     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13577       .addImm(16);
13578
13579   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13580     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13581   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13582
13583   // Set up the CFG correctly.
13584   BB->addSuccessor(bumpMBB);
13585   BB->addSuccessor(mallocMBB);
13586   mallocMBB->addSuccessor(continueMBB);
13587   bumpMBB->addSuccessor(continueMBB);
13588
13589   // Take care of the PHI nodes.
13590   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13591           MI->getOperand(0).getReg())
13592     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13593     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13594
13595   // Delete the original pseudo instruction.
13596   MI->eraseFromParent();
13597
13598   // And we're done.
13599   return continueMBB;
13600 }
13601
13602 MachineBasicBlock *
13603 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13604                                           MachineBasicBlock *BB) const {
13605   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13606   DebugLoc DL = MI->getDebugLoc();
13607
13608   assert(!Subtarget->isTargetEnvMacho());
13609
13610   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13611   // non-trivial part is impdef of ESP.
13612
13613   if (Subtarget->isTargetWin64()) {
13614     if (Subtarget->isTargetCygMing()) {
13615       // ___chkstk(Mingw64):
13616       // Clobbers R10, R11, RAX and EFLAGS.
13617       // Updates RSP.
13618       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13619         .addExternalSymbol("___chkstk")
13620         .addReg(X86::RAX, RegState::Implicit)
13621         .addReg(X86::RSP, RegState::Implicit)
13622         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13623         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13624         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13625     } else {
13626       // __chkstk(MSVCRT): does not update stack pointer.
13627       // Clobbers R10, R11 and EFLAGS.
13628       // FIXME: RAX(allocated size) might be reused and not killed.
13629       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13630         .addExternalSymbol("__chkstk")
13631         .addReg(X86::RAX, RegState::Implicit)
13632         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13633       // RAX has the offset to subtracted from RSP.
13634       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13635         .addReg(X86::RSP)
13636         .addReg(X86::RAX);
13637     }
13638   } else {
13639     const char *StackProbeSymbol =
13640       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13641
13642     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13643       .addExternalSymbol(StackProbeSymbol)
13644       .addReg(X86::EAX, RegState::Implicit)
13645       .addReg(X86::ESP, RegState::Implicit)
13646       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13647       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13648       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13649   }
13650
13651   MI->eraseFromParent();   // The pseudo instruction is gone now.
13652   return BB;
13653 }
13654
13655 MachineBasicBlock *
13656 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13657                                       MachineBasicBlock *BB) const {
13658   // This is pretty easy.  We're taking the value that we received from
13659   // our load from the relocation, sticking it in either RDI (x86-64)
13660   // or EAX and doing an indirect call.  The return value will then
13661   // be in the normal return register.
13662   const X86InstrInfo *TII
13663     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13664   DebugLoc DL = MI->getDebugLoc();
13665   MachineFunction *F = BB->getParent();
13666
13667   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13668   assert(MI->getOperand(3).isGlobal() && "This should be a global");
13669
13670   // Get a register mask for the lowered call.
13671   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13672   // proper register mask.
13673   const uint32_t *RegMask =
13674     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13675   if (Subtarget->is64Bit()) {
13676     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13677                                       TII->get(X86::MOV64rm), X86::RDI)
13678     .addReg(X86::RIP)
13679     .addImm(0).addReg(0)
13680     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13681                       MI->getOperand(3).getTargetFlags())
13682     .addReg(0);
13683     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13684     addDirectMem(MIB, X86::RDI);
13685     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13686   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13687     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13688                                       TII->get(X86::MOV32rm), X86::EAX)
13689     .addReg(0)
13690     .addImm(0).addReg(0)
13691     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13692                       MI->getOperand(3).getTargetFlags())
13693     .addReg(0);
13694     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13695     addDirectMem(MIB, X86::EAX);
13696     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13697   } else {
13698     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13699                                       TII->get(X86::MOV32rm), X86::EAX)
13700     .addReg(TII->getGlobalBaseReg(F))
13701     .addImm(0).addReg(0)
13702     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13703                       MI->getOperand(3).getTargetFlags())
13704     .addReg(0);
13705     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13706     addDirectMem(MIB, X86::EAX);
13707     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13708   }
13709
13710   MI->eraseFromParent(); // The pseudo instruction is gone now.
13711   return BB;
13712 }
13713
13714 MachineBasicBlock *
13715 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13716                                     MachineBasicBlock *MBB) const {
13717   DebugLoc DL = MI->getDebugLoc();
13718   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13719
13720   MachineFunction *MF = MBB->getParent();
13721   MachineRegisterInfo &MRI = MF->getRegInfo();
13722
13723   const BasicBlock *BB = MBB->getBasicBlock();
13724   MachineFunction::iterator I = MBB;
13725   ++I;
13726
13727   // Memory Reference
13728   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13729   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13730
13731   unsigned DstReg;
13732   unsigned MemOpndSlot = 0;
13733
13734   unsigned CurOp = 0;
13735
13736   DstReg = MI->getOperand(CurOp++).getReg();
13737   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13738   assert(RC->hasType(MVT::i32) && "Invalid destination!");
13739   unsigned mainDstReg = MRI.createVirtualRegister(RC);
13740   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13741
13742   MemOpndSlot = CurOp;
13743
13744   MVT PVT = getPointerTy();
13745   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13746          "Invalid Pointer Size!");
13747
13748   // For v = setjmp(buf), we generate
13749   //
13750   // thisMBB:
13751   //  buf[LabelOffset] = restoreMBB
13752   //  SjLjSetup restoreMBB
13753   //
13754   // mainMBB:
13755   //  v_main = 0
13756   //
13757   // sinkMBB:
13758   //  v = phi(main, restore)
13759   //
13760   // restoreMBB:
13761   //  v_restore = 1
13762
13763   MachineBasicBlock *thisMBB = MBB;
13764   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13765   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13766   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13767   MF->insert(I, mainMBB);
13768   MF->insert(I, sinkMBB);
13769   MF->push_back(restoreMBB);
13770
13771   MachineInstrBuilder MIB;
13772
13773   // Transfer the remainder of BB and its successor edges to sinkMBB.
13774   sinkMBB->splice(sinkMBB->begin(), MBB,
13775                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13776   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13777
13778   // thisMBB:
13779   unsigned PtrStoreOpc = 0;
13780   unsigned LabelReg = 0;
13781   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13782   Reloc::Model RM = getTargetMachine().getRelocationModel();
13783   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13784                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13785
13786   // Prepare IP either in reg or imm.
13787   if (!UseImmLabel) {
13788     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13789     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13790     LabelReg = MRI.createVirtualRegister(PtrRC);
13791     if (Subtarget->is64Bit()) {
13792       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13793               .addReg(X86::RIP)
13794               .addImm(0)
13795               .addReg(0)
13796               .addMBB(restoreMBB)
13797               .addReg(0);
13798     } else {
13799       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13800       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13801               .addReg(XII->getGlobalBaseReg(MF))
13802               .addImm(0)
13803               .addReg(0)
13804               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13805               .addReg(0);
13806     }
13807   } else
13808     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13809   // Store IP
13810   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13811   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13812     if (i == X86::AddrDisp)
13813       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13814     else
13815       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13816   }
13817   if (!UseImmLabel)
13818     MIB.addReg(LabelReg);
13819   else
13820     MIB.addMBB(restoreMBB);
13821   MIB.setMemRefs(MMOBegin, MMOEnd);
13822   // Setup
13823   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13824           .addMBB(restoreMBB);
13825   MIB.addRegMask(RegInfo->getNoPreservedMask());
13826   thisMBB->addSuccessor(mainMBB);
13827   thisMBB->addSuccessor(restoreMBB);
13828
13829   // mainMBB:
13830   //  EAX = 0
13831   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13832   mainMBB->addSuccessor(sinkMBB);
13833
13834   // sinkMBB:
13835   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13836           TII->get(X86::PHI), DstReg)
13837     .addReg(mainDstReg).addMBB(mainMBB)
13838     .addReg(restoreDstReg).addMBB(restoreMBB);
13839
13840   // restoreMBB:
13841   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13842   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13843   restoreMBB->addSuccessor(sinkMBB);
13844
13845   MI->eraseFromParent();
13846   return sinkMBB;
13847 }
13848
13849 MachineBasicBlock *
13850 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13851                                      MachineBasicBlock *MBB) const {
13852   DebugLoc DL = MI->getDebugLoc();
13853   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13854
13855   MachineFunction *MF = MBB->getParent();
13856   MachineRegisterInfo &MRI = MF->getRegInfo();
13857
13858   // Memory Reference
13859   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13860   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13861
13862   MVT PVT = getPointerTy();
13863   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13864          "Invalid Pointer Size!");
13865
13866   const TargetRegisterClass *RC =
13867     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13868   unsigned Tmp = MRI.createVirtualRegister(RC);
13869   // Since FP is only updated here but NOT referenced, it's treated as GPR.
13870   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13871   unsigned SP = RegInfo->getStackRegister();
13872
13873   MachineInstrBuilder MIB;
13874
13875   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13876   const int64_t SPOffset = 2 * PVT.getStoreSize();
13877
13878   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13879   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13880
13881   // Reload FP
13882   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13883   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13884     MIB.addOperand(MI->getOperand(i));
13885   MIB.setMemRefs(MMOBegin, MMOEnd);
13886   // Reload IP
13887   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13888   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13889     if (i == X86::AddrDisp)
13890       MIB.addDisp(MI->getOperand(i), LabelOffset);
13891     else
13892       MIB.addOperand(MI->getOperand(i));
13893   }
13894   MIB.setMemRefs(MMOBegin, MMOEnd);
13895   // Reload SP
13896   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13897   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13898     if (i == X86::AddrDisp)
13899       MIB.addDisp(MI->getOperand(i), SPOffset);
13900     else
13901       MIB.addOperand(MI->getOperand(i));
13902   }
13903   MIB.setMemRefs(MMOBegin, MMOEnd);
13904   // Jump
13905   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13906
13907   MI->eraseFromParent();
13908   return MBB;
13909 }
13910
13911 MachineBasicBlock *
13912 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13913                                                MachineBasicBlock *BB) const {
13914   switch (MI->getOpcode()) {
13915   default: llvm_unreachable("Unexpected instr type to insert");
13916   case X86::TAILJMPd64:
13917   case X86::TAILJMPr64:
13918   case X86::TAILJMPm64:
13919     llvm_unreachable("TAILJMP64 would not be touched here.");
13920   case X86::TCRETURNdi64:
13921   case X86::TCRETURNri64:
13922   case X86::TCRETURNmi64:
13923     return BB;
13924   case X86::WIN_ALLOCA:
13925     return EmitLoweredWinAlloca(MI, BB);
13926   case X86::SEG_ALLOCA_32:
13927     return EmitLoweredSegAlloca(MI, BB, false);
13928   case X86::SEG_ALLOCA_64:
13929     return EmitLoweredSegAlloca(MI, BB, true);
13930   case X86::TLSCall_32:
13931   case X86::TLSCall_64:
13932     return EmitLoweredTLSCall(MI, BB);
13933   case X86::CMOV_GR8:
13934   case X86::CMOV_FR32:
13935   case X86::CMOV_FR64:
13936   case X86::CMOV_V4F32:
13937   case X86::CMOV_V2F64:
13938   case X86::CMOV_V2I64:
13939   case X86::CMOV_V8F32:
13940   case X86::CMOV_V4F64:
13941   case X86::CMOV_V4I64:
13942   case X86::CMOV_GR16:
13943   case X86::CMOV_GR32:
13944   case X86::CMOV_RFP32:
13945   case X86::CMOV_RFP64:
13946   case X86::CMOV_RFP80:
13947     return EmitLoweredSelect(MI, BB);
13948
13949   case X86::FP32_TO_INT16_IN_MEM:
13950   case X86::FP32_TO_INT32_IN_MEM:
13951   case X86::FP32_TO_INT64_IN_MEM:
13952   case X86::FP64_TO_INT16_IN_MEM:
13953   case X86::FP64_TO_INT32_IN_MEM:
13954   case X86::FP64_TO_INT64_IN_MEM:
13955   case X86::FP80_TO_INT16_IN_MEM:
13956   case X86::FP80_TO_INT32_IN_MEM:
13957   case X86::FP80_TO_INT64_IN_MEM: {
13958     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13959     DebugLoc DL = MI->getDebugLoc();
13960
13961     // Change the floating point control register to use "round towards zero"
13962     // mode when truncating to an integer value.
13963     MachineFunction *F = BB->getParent();
13964     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13965     addFrameReference(BuildMI(*BB, MI, DL,
13966                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
13967
13968     // Load the old value of the high byte of the control word...
13969     unsigned OldCW =
13970       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13971     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13972                       CWFrameIdx);
13973
13974     // Set the high part to be round to zero...
13975     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13976       .addImm(0xC7F);
13977
13978     // Reload the modified control word now...
13979     addFrameReference(BuildMI(*BB, MI, DL,
13980                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13981
13982     // Restore the memory image of control word to original value
13983     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13984       .addReg(OldCW);
13985
13986     // Get the X86 opcode to use.
13987     unsigned Opc;
13988     switch (MI->getOpcode()) {
13989     default: llvm_unreachable("illegal opcode!");
13990     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13991     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13992     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13993     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13994     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13995     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13996     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13997     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13998     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13999     }
14000
14001     X86AddressMode AM;
14002     MachineOperand &Op = MI->getOperand(0);
14003     if (Op.isReg()) {
14004       AM.BaseType = X86AddressMode::RegBase;
14005       AM.Base.Reg = Op.getReg();
14006     } else {
14007       AM.BaseType = X86AddressMode::FrameIndexBase;
14008       AM.Base.FrameIndex = Op.getIndex();
14009     }
14010     Op = MI->getOperand(1);
14011     if (Op.isImm())
14012       AM.Scale = Op.getImm();
14013     Op = MI->getOperand(2);
14014     if (Op.isImm())
14015       AM.IndexReg = Op.getImm();
14016     Op = MI->getOperand(3);
14017     if (Op.isGlobal()) {
14018       AM.GV = Op.getGlobal();
14019     } else {
14020       AM.Disp = Op.getImm();
14021     }
14022     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14023                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14024
14025     // Reload the original control word now.
14026     addFrameReference(BuildMI(*BB, MI, DL,
14027                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14028
14029     MI->eraseFromParent();   // The pseudo instruction is gone now.
14030     return BB;
14031   }
14032     // String/text processing lowering.
14033   case X86::PCMPISTRM128REG:
14034   case X86::VPCMPISTRM128REG:
14035   case X86::PCMPISTRM128MEM:
14036   case X86::VPCMPISTRM128MEM:
14037   case X86::PCMPESTRM128REG:
14038   case X86::VPCMPESTRM128REG:
14039   case X86::PCMPESTRM128MEM:
14040   case X86::VPCMPESTRM128MEM:
14041     assert(Subtarget->hasSSE42() &&
14042            "Target must have SSE4.2 or AVX features enabled");
14043     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14044
14045   // String/text processing lowering.
14046   case X86::PCMPISTRIREG:
14047   case X86::VPCMPISTRIREG:
14048   case X86::PCMPISTRIMEM:
14049   case X86::VPCMPISTRIMEM:
14050   case X86::PCMPESTRIREG:
14051   case X86::VPCMPESTRIREG:
14052   case X86::PCMPESTRIMEM:
14053   case X86::VPCMPESTRIMEM:
14054     assert(Subtarget->hasSSE42() &&
14055            "Target must have SSE4.2 or AVX features enabled");
14056     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14057
14058   // Thread synchronization.
14059   case X86::MONITOR:
14060     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14061
14062   // xbegin
14063   case X86::XBEGIN:
14064     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14065
14066   // Atomic Lowering.
14067   case X86::ATOMAND8:
14068   case X86::ATOMAND16:
14069   case X86::ATOMAND32:
14070   case X86::ATOMAND64:
14071     // Fall through
14072   case X86::ATOMOR8:
14073   case X86::ATOMOR16:
14074   case X86::ATOMOR32:
14075   case X86::ATOMOR64:
14076     // Fall through
14077   case X86::ATOMXOR16:
14078   case X86::ATOMXOR8:
14079   case X86::ATOMXOR32:
14080   case X86::ATOMXOR64:
14081     // Fall through
14082   case X86::ATOMNAND8:
14083   case X86::ATOMNAND16:
14084   case X86::ATOMNAND32:
14085   case X86::ATOMNAND64:
14086     // Fall through
14087   case X86::ATOMMAX8:
14088   case X86::ATOMMAX16:
14089   case X86::ATOMMAX32:
14090   case X86::ATOMMAX64:
14091     // Fall through
14092   case X86::ATOMMIN8:
14093   case X86::ATOMMIN16:
14094   case X86::ATOMMIN32:
14095   case X86::ATOMMIN64:
14096     // Fall through
14097   case X86::ATOMUMAX8:
14098   case X86::ATOMUMAX16:
14099   case X86::ATOMUMAX32:
14100   case X86::ATOMUMAX64:
14101     // Fall through
14102   case X86::ATOMUMIN8:
14103   case X86::ATOMUMIN16:
14104   case X86::ATOMUMIN32:
14105   case X86::ATOMUMIN64:
14106     return EmitAtomicLoadArith(MI, BB);
14107
14108   // This group does 64-bit operations on a 32-bit host.
14109   case X86::ATOMAND6432:
14110   case X86::ATOMOR6432:
14111   case X86::ATOMXOR6432:
14112   case X86::ATOMNAND6432:
14113   case X86::ATOMADD6432:
14114   case X86::ATOMSUB6432:
14115   case X86::ATOMMAX6432:
14116   case X86::ATOMMIN6432:
14117   case X86::ATOMUMAX6432:
14118   case X86::ATOMUMIN6432:
14119   case X86::ATOMSWAP6432:
14120     return EmitAtomicLoadArith6432(MI, BB);
14121
14122   case X86::VASTART_SAVE_XMM_REGS:
14123     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14124
14125   case X86::VAARG_64:
14126     return EmitVAARG64WithCustomInserter(MI, BB);
14127
14128   case X86::EH_SjLj_SetJmp32:
14129   case X86::EH_SjLj_SetJmp64:
14130     return emitEHSjLjSetJmp(MI, BB);
14131
14132   case X86::EH_SjLj_LongJmp32:
14133   case X86::EH_SjLj_LongJmp64:
14134     return emitEHSjLjLongJmp(MI, BB);
14135   }
14136 }
14137
14138 //===----------------------------------------------------------------------===//
14139 //                           X86 Optimization Hooks
14140 //===----------------------------------------------------------------------===//
14141
14142 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14143                                                        APInt &KnownZero,
14144                                                        APInt &KnownOne,
14145                                                        const SelectionDAG &DAG,
14146                                                        unsigned Depth) const {
14147   unsigned BitWidth = KnownZero.getBitWidth();
14148   unsigned Opc = Op.getOpcode();
14149   assert((Opc >= ISD::BUILTIN_OP_END ||
14150           Opc == ISD::INTRINSIC_WO_CHAIN ||
14151           Opc == ISD::INTRINSIC_W_CHAIN ||
14152           Opc == ISD::INTRINSIC_VOID) &&
14153          "Should use MaskedValueIsZero if you don't know whether Op"
14154          " is a target node!");
14155
14156   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14157   switch (Opc) {
14158   default: break;
14159   case X86ISD::ADD:
14160   case X86ISD::SUB:
14161   case X86ISD::ADC:
14162   case X86ISD::SBB:
14163   case X86ISD::SMUL:
14164   case X86ISD::UMUL:
14165   case X86ISD::INC:
14166   case X86ISD::DEC:
14167   case X86ISD::OR:
14168   case X86ISD::XOR:
14169   case X86ISD::AND:
14170     // These nodes' second result is a boolean.
14171     if (Op.getResNo() == 0)
14172       break;
14173     // Fallthrough
14174   case X86ISD::SETCC:
14175     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14176     break;
14177   case ISD::INTRINSIC_WO_CHAIN: {
14178     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14179     unsigned NumLoBits = 0;
14180     switch (IntId) {
14181     default: break;
14182     case Intrinsic::x86_sse_movmsk_ps:
14183     case Intrinsic::x86_avx_movmsk_ps_256:
14184     case Intrinsic::x86_sse2_movmsk_pd:
14185     case Intrinsic::x86_avx_movmsk_pd_256:
14186     case Intrinsic::x86_mmx_pmovmskb:
14187     case Intrinsic::x86_sse2_pmovmskb_128:
14188     case Intrinsic::x86_avx2_pmovmskb: {
14189       // High bits of movmskp{s|d}, pmovmskb are known zero.
14190       switch (IntId) {
14191         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14192         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14193         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14194         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14195         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14196         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14197         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14198         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14199       }
14200       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14201       break;
14202     }
14203     }
14204     break;
14205   }
14206   }
14207 }
14208
14209 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14210                                                          unsigned Depth) const {
14211   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14212   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14213     return Op.getValueType().getScalarType().getSizeInBits();
14214
14215   // Fallback case.
14216   return 1;
14217 }
14218
14219 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14220 /// node is a GlobalAddress + offset.
14221 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14222                                        const GlobalValue* &GA,
14223                                        int64_t &Offset) const {
14224   if (N->getOpcode() == X86ISD::Wrapper) {
14225     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14226       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14227       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14228       return true;
14229     }
14230   }
14231   return TargetLowering::isGAPlusOffset(N, GA, Offset);
14232 }
14233
14234 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14235 /// same as extracting the high 128-bit part of 256-bit vector and then
14236 /// inserting the result into the low part of a new 256-bit vector
14237 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14238   EVT VT = SVOp->getValueType(0);
14239   unsigned NumElems = VT.getVectorNumElements();
14240
14241   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14242   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14243     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14244         SVOp->getMaskElt(j) >= 0)
14245       return false;
14246
14247   return true;
14248 }
14249
14250 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14251 /// same as extracting the low 128-bit part of 256-bit vector and then
14252 /// inserting the result into the high part of a new 256-bit vector
14253 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14254   EVT VT = SVOp->getValueType(0);
14255   unsigned NumElems = VT.getVectorNumElements();
14256
14257   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14258   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14259     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14260         SVOp->getMaskElt(j) >= 0)
14261       return false;
14262
14263   return true;
14264 }
14265
14266 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14267 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14268                                         TargetLowering::DAGCombinerInfo &DCI,
14269                                         const X86Subtarget* Subtarget) {
14270   DebugLoc dl = N->getDebugLoc();
14271   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14272   SDValue V1 = SVOp->getOperand(0);
14273   SDValue V2 = SVOp->getOperand(1);
14274   EVT VT = SVOp->getValueType(0);
14275   unsigned NumElems = VT.getVectorNumElements();
14276
14277   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14278       V2.getOpcode() == ISD::CONCAT_VECTORS) {
14279     //
14280     //                   0,0,0,...
14281     //                      |
14282     //    V      UNDEF    BUILD_VECTOR    UNDEF
14283     //     \      /           \           /
14284     //  CONCAT_VECTOR         CONCAT_VECTOR
14285     //         \                  /
14286     //          \                /
14287     //          RESULT: V + zero extended
14288     //
14289     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14290         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14291         V1.getOperand(1).getOpcode() != ISD::UNDEF)
14292       return SDValue();
14293
14294     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14295       return SDValue();
14296
14297     // To match the shuffle mask, the first half of the mask should
14298     // be exactly the first vector, and all the rest a splat with the
14299     // first element of the second one.
14300     for (unsigned i = 0; i != NumElems/2; ++i)
14301       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14302           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14303         return SDValue();
14304
14305     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14306     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14307       if (Ld->hasNUsesOfValue(1, 0)) {
14308         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14309         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14310         SDValue ResNode =
14311           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14312                                   Ld->getMemoryVT(),
14313                                   Ld->getPointerInfo(),
14314                                   Ld->getAlignment(),
14315                                   false/*isVolatile*/, true/*ReadMem*/,
14316                                   false/*WriteMem*/);
14317
14318         // Make sure the newly-created LOAD is in the same position as Ld in
14319         // terms of dependency. We create a TokenFactor for Ld and ResNode,
14320         // and update uses of Ld's output chain to use the TokenFactor.
14321         if (Ld->hasAnyUseOfValue(1)) {
14322           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14323                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14324           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14325           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14326                                  SDValue(ResNode.getNode(), 1));
14327         }
14328
14329         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14330       }
14331     }
14332
14333     // Emit a zeroed vector and insert the desired subvector on its
14334     // first half.
14335     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14336     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14337     return DCI.CombineTo(N, InsV);
14338   }
14339
14340   //===--------------------------------------------------------------------===//
14341   // Combine some shuffles into subvector extracts and inserts:
14342   //
14343
14344   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14345   if (isShuffleHigh128VectorInsertLow(SVOp)) {
14346     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14347     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14348     return DCI.CombineTo(N, InsV);
14349   }
14350
14351   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14352   if (isShuffleLow128VectorInsertHigh(SVOp)) {
14353     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14354     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14355     return DCI.CombineTo(N, InsV);
14356   }
14357
14358   return SDValue();
14359 }
14360
14361 /// PerformShuffleCombine - Performs several different shuffle combines.
14362 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14363                                      TargetLowering::DAGCombinerInfo &DCI,
14364                                      const X86Subtarget *Subtarget) {
14365   DebugLoc dl = N->getDebugLoc();
14366   EVT VT = N->getValueType(0);
14367
14368   // Don't create instructions with illegal types after legalize types has run.
14369   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14370   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14371     return SDValue();
14372
14373   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14374   if (Subtarget->hasFp256() && VT.is256BitVector() &&
14375       N->getOpcode() == ISD::VECTOR_SHUFFLE)
14376     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14377
14378   // Only handle 128 wide vector from here on.
14379   if (!VT.is128BitVector())
14380     return SDValue();
14381
14382   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14383   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14384   // consecutive, non-overlapping, and in the right order.
14385   SmallVector<SDValue, 16> Elts;
14386   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14387     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14388
14389   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14390 }
14391
14392 /// PerformTruncateCombine - Converts truncate operation to
14393 /// a sequence of vector shuffle operations.
14394 /// It is possible when we truncate 256-bit vector to 128-bit vector
14395 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14396                                       TargetLowering::DAGCombinerInfo &DCI,
14397                                       const X86Subtarget *Subtarget)  {
14398   if (!DCI.isBeforeLegalizeOps())
14399     return SDValue();
14400
14401   if (!Subtarget->hasFp256())
14402     return SDValue();
14403
14404   EVT VT = N->getValueType(0);
14405   SDValue Op = N->getOperand(0);
14406   EVT OpVT = Op.getValueType();
14407   DebugLoc dl = N->getDebugLoc();
14408
14409   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14410
14411     if (Subtarget->hasInt256()) {
14412       // AVX2: v4i64 -> v4i32
14413
14414       // VPERMD
14415       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14416
14417       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14418       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14419                                 ShufMask);
14420
14421       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14422                          DAG.getIntPtrConstant(0));
14423     }
14424
14425     // AVX: v4i64 -> v4i32
14426     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14427                                DAG.getIntPtrConstant(0));
14428
14429     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14430                                DAG.getIntPtrConstant(2));
14431
14432     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14433     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14434
14435     // PSHUFD
14436     static const int ShufMask1[] = {0, 2, 0, 0};
14437
14438     SDValue Undef = DAG.getUNDEF(VT);
14439     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14440     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14441
14442     // MOVLHPS
14443     static const int ShufMask2[] = {0, 1, 4, 5};
14444
14445     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14446   }
14447
14448   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14449
14450     if (Subtarget->hasInt256()) {
14451       // AVX2: v8i32 -> v8i16
14452
14453       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14454
14455       // PSHUFB
14456       SmallVector<SDValue,32> pshufbMask;
14457       for (unsigned i = 0; i < 2; ++i) {
14458         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14459         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14460         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14461         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14462         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14463         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14464         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14465         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14466         for (unsigned j = 0; j < 8; ++j)
14467           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14468       }
14469       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14470                                &pshufbMask[0], 32);
14471       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14472
14473       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14474
14475       static const int ShufMask[] = {0,  2,  -1,  -1};
14476       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
14477                                 &ShufMask[0]);
14478
14479       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14480                        DAG.getIntPtrConstant(0));
14481
14482       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14483     }
14484
14485     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14486                                DAG.getIntPtrConstant(0));
14487
14488     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14489                                DAG.getIntPtrConstant(4));
14490
14491     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14492     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14493
14494     // PSHUFB
14495     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14496                                    -1, -1, -1, -1, -1, -1, -1, -1};
14497
14498     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14499     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14500     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14501
14502     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14503     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14504
14505     // MOVLHPS
14506     static const int ShufMask2[] = {0, 1, 4, 5};
14507
14508     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14509     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14510   }
14511
14512   return SDValue();
14513 }
14514
14515 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14516 /// specific shuffle of a load can be folded into a single element load.
14517 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14518 /// shuffles have been customed lowered so we need to handle those here.
14519 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14520                                          TargetLowering::DAGCombinerInfo &DCI) {
14521   if (DCI.isBeforeLegalizeOps())
14522     return SDValue();
14523
14524   SDValue InVec = N->getOperand(0);
14525   SDValue EltNo = N->getOperand(1);
14526
14527   if (!isa<ConstantSDNode>(EltNo))
14528     return SDValue();
14529
14530   EVT VT = InVec.getValueType();
14531
14532   bool HasShuffleIntoBitcast = false;
14533   if (InVec.getOpcode() == ISD::BITCAST) {
14534     // Don't duplicate a load with other uses.
14535     if (!InVec.hasOneUse())
14536       return SDValue();
14537     EVT BCVT = InVec.getOperand(0).getValueType();
14538     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14539       return SDValue();
14540     InVec = InVec.getOperand(0);
14541     HasShuffleIntoBitcast = true;
14542   }
14543
14544   if (!isTargetShuffle(InVec.getOpcode()))
14545     return SDValue();
14546
14547   // Don't duplicate a load with other uses.
14548   if (!InVec.hasOneUse())
14549     return SDValue();
14550
14551   SmallVector<int, 16> ShuffleMask;
14552   bool UnaryShuffle;
14553   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14554                             UnaryShuffle))
14555     return SDValue();
14556
14557   // Select the input vector, guarding against out of range extract vector.
14558   unsigned NumElems = VT.getVectorNumElements();
14559   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14560   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14561   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14562                                          : InVec.getOperand(1);
14563
14564   // If inputs to shuffle are the same for both ops, then allow 2 uses
14565   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14566
14567   if (LdNode.getOpcode() == ISD::BITCAST) {
14568     // Don't duplicate a load with other uses.
14569     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14570       return SDValue();
14571
14572     AllowedUses = 1; // only allow 1 load use if we have a bitcast
14573     LdNode = LdNode.getOperand(0);
14574   }
14575
14576   if (!ISD::isNormalLoad(LdNode.getNode()))
14577     return SDValue();
14578
14579   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14580
14581   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14582     return SDValue();
14583
14584   if (HasShuffleIntoBitcast) {
14585     // If there's a bitcast before the shuffle, check if the load type and
14586     // alignment is valid.
14587     unsigned Align = LN0->getAlignment();
14588     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14589     unsigned NewAlign = TLI.getDataLayout()->
14590       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14591
14592     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14593       return SDValue();
14594   }
14595
14596   // All checks match so transform back to vector_shuffle so that DAG combiner
14597   // can finish the job
14598   DebugLoc dl = N->getDebugLoc();
14599
14600   // Create shuffle node taking into account the case that its a unary shuffle
14601   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14602   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14603                                  InVec.getOperand(0), Shuffle,
14604                                  &ShuffleMask[0]);
14605   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14606   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14607                      EltNo);
14608 }
14609
14610 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14611 /// generation and convert it from being a bunch of shuffles and extracts
14612 /// to a simple store and scalar loads to extract the elements.
14613 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14614                                          TargetLowering::DAGCombinerInfo &DCI) {
14615   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14616   if (NewOp.getNode())
14617     return NewOp;
14618
14619   SDValue InputVector = N->getOperand(0);
14620   // Detect whether we are trying to convert from mmx to i32 and the bitcast
14621   // from mmx to v2i32 has a single usage.
14622   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14623       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14624       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14625     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14626                        N->getValueType(0),
14627                        InputVector.getNode()->getOperand(0));
14628
14629   // Only operate on vectors of 4 elements, where the alternative shuffling
14630   // gets to be more expensive.
14631   if (InputVector.getValueType() != MVT::v4i32)
14632     return SDValue();
14633
14634   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14635   // single use which is a sign-extend or zero-extend, and all elements are
14636   // used.
14637   SmallVector<SDNode *, 4> Uses;
14638   unsigned ExtractedElements = 0;
14639   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14640        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14641     if (UI.getUse().getResNo() != InputVector.getResNo())
14642       return SDValue();
14643
14644     SDNode *Extract = *UI;
14645     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14646       return SDValue();
14647
14648     if (Extract->getValueType(0) != MVT::i32)
14649       return SDValue();
14650     if (!Extract->hasOneUse())
14651       return SDValue();
14652     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14653         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14654       return SDValue();
14655     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14656       return SDValue();
14657
14658     // Record which element was extracted.
14659     ExtractedElements |=
14660       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14661
14662     Uses.push_back(Extract);
14663   }
14664
14665   // If not all the elements were used, this may not be worthwhile.
14666   if (ExtractedElements != 15)
14667     return SDValue();
14668
14669   // Ok, we've now decided to do the transformation.
14670   DebugLoc dl = InputVector.getDebugLoc();
14671
14672   // Store the value to a temporary stack slot.
14673   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14674   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14675                             MachinePointerInfo(), false, false, 0);
14676
14677   // Replace each use (extract) with a load of the appropriate element.
14678   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14679        UE = Uses.end(); UI != UE; ++UI) {
14680     SDNode *Extract = *UI;
14681
14682     // cOMpute the element's address.
14683     SDValue Idx = Extract->getOperand(1);
14684     unsigned EltSize =
14685         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14686     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14687     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14688     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14689
14690     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14691                                      StackPtr, OffsetVal);
14692
14693     // Load the scalar.
14694     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14695                                      ScalarAddr, MachinePointerInfo(),
14696                                      false, false, false, 0);
14697
14698     // Replace the exact with the load.
14699     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14700   }
14701
14702   // The replacement was made in place; don't return anything.
14703   return SDValue();
14704 }
14705
14706 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
14707 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
14708                                    SDValue RHS, SelectionDAG &DAG,
14709                                    const X86Subtarget *Subtarget) {
14710   if (!VT.isVector())
14711     return 0;
14712
14713   switch (VT.getSimpleVT().SimpleTy) {
14714   default: return 0;
14715   case MVT::v32i8:
14716   case MVT::v16i16:
14717   case MVT::v8i32:
14718     if (!Subtarget->hasAVX2())
14719       return 0;
14720   case MVT::v16i8:
14721   case MVT::v8i16:
14722   case MVT::v4i32:
14723     if (!Subtarget->hasSSE2())
14724       return 0;
14725   }
14726
14727   // SSE2 has only a small subset of the operations.
14728   bool hasUnsigned = Subtarget->hasSSE41() ||
14729                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
14730   bool hasSigned = Subtarget->hasSSE41() ||
14731                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
14732
14733   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14734
14735   // Check for x CC y ? x : y.
14736   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14737       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14738     switch (CC) {
14739     default: break;
14740     case ISD::SETULT:
14741     case ISD::SETULE:
14742       return hasUnsigned ? X86ISD::UMIN : 0;
14743     case ISD::SETUGT:
14744     case ISD::SETUGE:
14745       return hasUnsigned ? X86ISD::UMAX : 0;
14746     case ISD::SETLT:
14747     case ISD::SETLE:
14748       return hasSigned ? X86ISD::SMIN : 0;
14749     case ISD::SETGT:
14750     case ISD::SETGE:
14751       return hasSigned ? X86ISD::SMAX : 0;
14752     }
14753   // Check for x CC y ? y : x -- a min/max with reversed arms.
14754   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14755              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14756     switch (CC) {
14757     default: break;
14758     case ISD::SETULT:
14759     case ISD::SETULE:
14760       return hasUnsigned ? X86ISD::UMAX : 0;
14761     case ISD::SETUGT:
14762     case ISD::SETUGE:
14763       return hasUnsigned ? X86ISD::UMIN : 0;
14764     case ISD::SETLT:
14765     case ISD::SETLE:
14766       return hasSigned ? X86ISD::SMAX : 0;
14767     case ISD::SETGT:
14768     case ISD::SETGE:
14769       return hasSigned ? X86ISD::SMIN : 0;
14770     }
14771   }
14772
14773   return 0;
14774 }
14775
14776 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14777 /// nodes.
14778 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14779                                     TargetLowering::DAGCombinerInfo &DCI,
14780                                     const X86Subtarget *Subtarget) {
14781   DebugLoc DL = N->getDebugLoc();
14782   SDValue Cond = N->getOperand(0);
14783   // Get the LHS/RHS of the select.
14784   SDValue LHS = N->getOperand(1);
14785   SDValue RHS = N->getOperand(2);
14786   EVT VT = LHS.getValueType();
14787
14788   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14789   // instructions match the semantics of the common C idiom x<y?x:y but not
14790   // x<=y?x:y, because of how they handle negative zero (which can be
14791   // ignored in unsafe-math mode).
14792   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14793       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14794       (Subtarget->hasSSE2() ||
14795        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14796     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14797
14798     unsigned Opcode = 0;
14799     // Check for x CC y ? x : y.
14800     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14801         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14802       switch (CC) {
14803       default: break;
14804       case ISD::SETULT:
14805         // Converting this to a min would handle NaNs incorrectly, and swapping
14806         // the operands would cause it to handle comparisons between positive
14807         // and negative zero incorrectly.
14808         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14809           if (!DAG.getTarget().Options.UnsafeFPMath &&
14810               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14811             break;
14812           std::swap(LHS, RHS);
14813         }
14814         Opcode = X86ISD::FMIN;
14815         break;
14816       case ISD::SETOLE:
14817         // Converting this to a min would handle comparisons between positive
14818         // and negative zero incorrectly.
14819         if (!DAG.getTarget().Options.UnsafeFPMath &&
14820             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14821           break;
14822         Opcode = X86ISD::FMIN;
14823         break;
14824       case ISD::SETULE:
14825         // Converting this to a min would handle both negative zeros and NaNs
14826         // incorrectly, but we can swap the operands to fix both.
14827         std::swap(LHS, RHS);
14828       case ISD::SETOLT:
14829       case ISD::SETLT:
14830       case ISD::SETLE:
14831         Opcode = X86ISD::FMIN;
14832         break;
14833
14834       case ISD::SETOGE:
14835         // Converting this to a max would handle comparisons between positive
14836         // and negative zero incorrectly.
14837         if (!DAG.getTarget().Options.UnsafeFPMath &&
14838             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14839           break;
14840         Opcode = X86ISD::FMAX;
14841         break;
14842       case ISD::SETUGT:
14843         // Converting this to a max would handle NaNs incorrectly, and swapping
14844         // the operands would cause it to handle comparisons between positive
14845         // and negative zero incorrectly.
14846         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14847           if (!DAG.getTarget().Options.UnsafeFPMath &&
14848               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14849             break;
14850           std::swap(LHS, RHS);
14851         }
14852         Opcode = X86ISD::FMAX;
14853         break;
14854       case ISD::SETUGE:
14855         // Converting this to a max would handle both negative zeros and NaNs
14856         // incorrectly, but we can swap the operands to fix both.
14857         std::swap(LHS, RHS);
14858       case ISD::SETOGT:
14859       case ISD::SETGT:
14860       case ISD::SETGE:
14861         Opcode = X86ISD::FMAX;
14862         break;
14863       }
14864     // Check for x CC y ? y : x -- a min/max with reversed arms.
14865     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14866                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14867       switch (CC) {
14868       default: break;
14869       case ISD::SETOGE:
14870         // Converting this to a min would handle comparisons between positive
14871         // and negative zero incorrectly, and swapping the operands would
14872         // cause it to handle NaNs incorrectly.
14873         if (!DAG.getTarget().Options.UnsafeFPMath &&
14874             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14875           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14876             break;
14877           std::swap(LHS, RHS);
14878         }
14879         Opcode = X86ISD::FMIN;
14880         break;
14881       case ISD::SETUGT:
14882         // Converting this to a min would handle NaNs incorrectly.
14883         if (!DAG.getTarget().Options.UnsafeFPMath &&
14884             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14885           break;
14886         Opcode = X86ISD::FMIN;
14887         break;
14888       case ISD::SETUGE:
14889         // Converting this to a min would handle both negative zeros and NaNs
14890         // incorrectly, but we can swap the operands to fix both.
14891         std::swap(LHS, RHS);
14892       case ISD::SETOGT:
14893       case ISD::SETGT:
14894       case ISD::SETGE:
14895         Opcode = X86ISD::FMIN;
14896         break;
14897
14898       case ISD::SETULT:
14899         // Converting this to a max would handle NaNs incorrectly.
14900         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14901           break;
14902         Opcode = X86ISD::FMAX;
14903         break;
14904       case ISD::SETOLE:
14905         // Converting this to a max would handle comparisons between positive
14906         // and negative zero incorrectly, and swapping the operands would
14907         // cause it to handle NaNs incorrectly.
14908         if (!DAG.getTarget().Options.UnsafeFPMath &&
14909             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14910           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14911             break;
14912           std::swap(LHS, RHS);
14913         }
14914         Opcode = X86ISD::FMAX;
14915         break;
14916       case ISD::SETULE:
14917         // Converting this to a max would handle both negative zeros and NaNs
14918         // incorrectly, but we can swap the operands to fix both.
14919         std::swap(LHS, RHS);
14920       case ISD::SETOLT:
14921       case ISD::SETLT:
14922       case ISD::SETLE:
14923         Opcode = X86ISD::FMAX;
14924         break;
14925       }
14926     }
14927
14928     if (Opcode)
14929       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14930   }
14931
14932   // If this is a select between two integer constants, try to do some
14933   // optimizations.
14934   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14935     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14936       // Don't do this for crazy integer types.
14937       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14938         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14939         // so that TrueC (the true value) is larger than FalseC.
14940         bool NeedsCondInvert = false;
14941
14942         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14943             // Efficiently invertible.
14944             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
14945              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
14946               isa<ConstantSDNode>(Cond.getOperand(1))))) {
14947           NeedsCondInvert = true;
14948           std::swap(TrueC, FalseC);
14949         }
14950
14951         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
14952         if (FalseC->getAPIntValue() == 0 &&
14953             TrueC->getAPIntValue().isPowerOf2()) {
14954           if (NeedsCondInvert) // Invert the condition if needed.
14955             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14956                                DAG.getConstant(1, Cond.getValueType()));
14957
14958           // Zero extend the condition if needed.
14959           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14960
14961           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14962           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14963                              DAG.getConstant(ShAmt, MVT::i8));
14964         }
14965
14966         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14967         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14968           if (NeedsCondInvert) // Invert the condition if needed.
14969             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14970                                DAG.getConstant(1, Cond.getValueType()));
14971
14972           // Zero extend the condition if needed.
14973           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14974                              FalseC->getValueType(0), Cond);
14975           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14976                              SDValue(FalseC, 0));
14977         }
14978
14979         // Optimize cases that will turn into an LEA instruction.  This requires
14980         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14981         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14982           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14983           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14984
14985           bool isFastMultiplier = false;
14986           if (Diff < 10) {
14987             switch ((unsigned char)Diff) {
14988               default: break;
14989               case 1:  // result = add base, cond
14990               case 2:  // result = lea base(    , cond*2)
14991               case 3:  // result = lea base(cond, cond*2)
14992               case 4:  // result = lea base(    , cond*4)
14993               case 5:  // result = lea base(cond, cond*4)
14994               case 8:  // result = lea base(    , cond*8)
14995               case 9:  // result = lea base(cond, cond*8)
14996                 isFastMultiplier = true;
14997                 break;
14998             }
14999           }
15000
15001           if (isFastMultiplier) {
15002             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15003             if (NeedsCondInvert) // Invert the condition if needed.
15004               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15005                                  DAG.getConstant(1, Cond.getValueType()));
15006
15007             // Zero extend the condition if needed.
15008             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15009                                Cond);
15010             // Scale the condition by the difference.
15011             if (Diff != 1)
15012               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15013                                  DAG.getConstant(Diff, Cond.getValueType()));
15014
15015             // Add the base if non-zero.
15016             if (FalseC->getAPIntValue() != 0)
15017               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15018                                  SDValue(FalseC, 0));
15019             return Cond;
15020           }
15021         }
15022       }
15023   }
15024
15025   // Canonicalize max and min:
15026   // (x > y) ? x : y -> (x >= y) ? x : y
15027   // (x < y) ? x : y -> (x <= y) ? x : y
15028   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15029   // the need for an extra compare
15030   // against zero. e.g.
15031   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15032   // subl   %esi, %edi
15033   // testl  %edi, %edi
15034   // movl   $0, %eax
15035   // cmovgl %edi, %eax
15036   // =>
15037   // xorl   %eax, %eax
15038   // subl   %esi, $edi
15039   // cmovsl %eax, %edi
15040   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15041       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15042       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15043     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15044     switch (CC) {
15045     default: break;
15046     case ISD::SETLT:
15047     case ISD::SETGT: {
15048       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15049       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15050                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15051       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15052     }
15053     }
15054   }
15055
15056   // Match VSELECTs into subs with unsigned saturation.
15057   if (!DCI.isBeforeLegalize() &&
15058       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15059       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15060       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15061        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15062     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15063
15064     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15065     // left side invert the predicate to simplify logic below.
15066     SDValue Other;
15067     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15068       Other = RHS;
15069       CC = ISD::getSetCCInverse(CC, true);
15070     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15071       Other = LHS;
15072     }
15073
15074     if (Other.getNode() && Other->getNumOperands() == 2 &&
15075         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15076       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15077       SDValue CondRHS = Cond->getOperand(1);
15078
15079       // Look for a general sub with unsigned saturation first.
15080       // x >= y ? x-y : 0 --> subus x, y
15081       // x >  y ? x-y : 0 --> subus x, y
15082       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15083           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15084         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15085
15086       // If the RHS is a constant we have to reverse the const canonicalization.
15087       // x > C-1 ? x+-C : 0 --> subus x, C
15088       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15089           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15090         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15091         if (CondRHS.getConstantOperandVal(0) == -A-1) {
15092           SmallVector<SDValue, 32> V(VT.getVectorNumElements(),
15093                                      DAG.getConstant(-A, VT.getScalarType()));
15094           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15095                              DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
15096                                          V.data(), V.size()));
15097         }
15098       }
15099
15100       // Another special case: If C was a sign bit, the sub has been
15101       // canonicalized into a xor.
15102       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15103       //        it's safe to decanonicalize the xor?
15104       // x s< 0 ? x^C : 0 --> subus x, C
15105       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15106           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15107           isSplatVector(OpRHS.getNode())) {
15108         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15109         if (A.isSignBit())
15110           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15111       }
15112     }
15113   }
15114
15115   // Try to match a min/max vector operation.
15116   if (!DCI.isBeforeLegalize() &&
15117       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15118     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15119       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15120
15121   // If we know that this node is legal then we know that it is going to be
15122   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15123   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15124   // to simplify previous instructions.
15125   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15126   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15127       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15128     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15129
15130     // Don't optimize vector selects that map to mask-registers.
15131     if (BitWidth == 1)
15132       return SDValue();
15133
15134     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15135     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15136
15137     APInt KnownZero, KnownOne;
15138     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15139                                           DCI.isBeforeLegalizeOps());
15140     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15141         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15142       DCI.CommitTargetLoweringOpt(TLO);
15143   }
15144
15145   return SDValue();
15146 }
15147
15148 // Check whether a boolean test is testing a boolean value generated by
15149 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15150 // code.
15151 //
15152 // Simplify the following patterns:
15153 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15154 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15155 // to (Op EFLAGS Cond)
15156 //
15157 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15158 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15159 // to (Op EFLAGS !Cond)
15160 //
15161 // where Op could be BRCOND or CMOV.
15162 //
15163 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15164   // Quit if not CMP and SUB with its value result used.
15165   if (Cmp.getOpcode() != X86ISD::CMP &&
15166       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15167       return SDValue();
15168
15169   // Quit if not used as a boolean value.
15170   if (CC != X86::COND_E && CC != X86::COND_NE)
15171     return SDValue();
15172
15173   // Check CMP operands. One of them should be 0 or 1 and the other should be
15174   // an SetCC or extended from it.
15175   SDValue Op1 = Cmp.getOperand(0);
15176   SDValue Op2 = Cmp.getOperand(1);
15177
15178   SDValue SetCC;
15179   const ConstantSDNode* C = 0;
15180   bool needOppositeCond = (CC == X86::COND_E);
15181
15182   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15183     SetCC = Op2;
15184   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15185     SetCC = Op1;
15186   else // Quit if all operands are not constants.
15187     return SDValue();
15188
15189   if (C->getZExtValue() == 1)
15190     needOppositeCond = !needOppositeCond;
15191   else if (C->getZExtValue() != 0)
15192     // Quit if the constant is neither 0 or 1.
15193     return SDValue();
15194
15195   // Skip 'zext' node.
15196   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15197     SetCC = SetCC.getOperand(0);
15198
15199   switch (SetCC.getOpcode()) {
15200   case X86ISD::SETCC:
15201     // Set the condition code or opposite one if necessary.
15202     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15203     if (needOppositeCond)
15204       CC = X86::GetOppositeBranchCondition(CC);
15205     return SetCC.getOperand(1);
15206   case X86ISD::CMOV: {
15207     // Check whether false/true value has canonical one, i.e. 0 or 1.
15208     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15209     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15210     // Quit if true value is not a constant.
15211     if (!TVal)
15212       return SDValue();
15213     // Quit if false value is not a constant.
15214     if (!FVal) {
15215       // A special case for rdrand, where 0 is set if false cond is found.
15216       SDValue Op = SetCC.getOperand(0);
15217       if (Op.getOpcode() != X86ISD::RDRAND)
15218         return SDValue();
15219     }
15220     // Quit if false value is not the constant 0 or 1.
15221     bool FValIsFalse = true;
15222     if (FVal && FVal->getZExtValue() != 0) {
15223       if (FVal->getZExtValue() != 1)
15224         return SDValue();
15225       // If FVal is 1, opposite cond is needed.
15226       needOppositeCond = !needOppositeCond;
15227       FValIsFalse = false;
15228     }
15229     // Quit if TVal is not the constant opposite of FVal.
15230     if (FValIsFalse && TVal->getZExtValue() != 1)
15231       return SDValue();
15232     if (!FValIsFalse && TVal->getZExtValue() != 0)
15233       return SDValue();
15234     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15235     if (needOppositeCond)
15236       CC = X86::GetOppositeBranchCondition(CC);
15237     return SetCC.getOperand(3);
15238   }
15239   }
15240
15241   return SDValue();
15242 }
15243
15244 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15245 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15246                                   TargetLowering::DAGCombinerInfo &DCI,
15247                                   const X86Subtarget *Subtarget) {
15248   DebugLoc DL = N->getDebugLoc();
15249
15250   // If the flag operand isn't dead, don't touch this CMOV.
15251   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15252     return SDValue();
15253
15254   SDValue FalseOp = N->getOperand(0);
15255   SDValue TrueOp = N->getOperand(1);
15256   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15257   SDValue Cond = N->getOperand(3);
15258
15259   if (CC == X86::COND_E || CC == X86::COND_NE) {
15260     switch (Cond.getOpcode()) {
15261     default: break;
15262     case X86ISD::BSR:
15263     case X86ISD::BSF:
15264       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15265       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15266         return (CC == X86::COND_E) ? FalseOp : TrueOp;
15267     }
15268   }
15269
15270   SDValue Flags;
15271
15272   Flags = checkBoolTestSetCCCombine(Cond, CC);
15273   if (Flags.getNode() &&
15274       // Extra check as FCMOV only supports a subset of X86 cond.
15275       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15276     SDValue Ops[] = { FalseOp, TrueOp,
15277                       DAG.getConstant(CC, MVT::i8), Flags };
15278     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15279                        Ops, array_lengthof(Ops));
15280   }
15281
15282   // If this is a select between two integer constants, try to do some
15283   // optimizations.  Note that the operands are ordered the opposite of SELECT
15284   // operands.
15285   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15286     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15287       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15288       // larger than FalseC (the false value).
15289       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15290         CC = X86::GetOppositeBranchCondition(CC);
15291         std::swap(TrueC, FalseC);
15292         std::swap(TrueOp, FalseOp);
15293       }
15294
15295       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
15296       // This is efficient for any integer data type (including i8/i16) and
15297       // shift amount.
15298       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15299         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15300                            DAG.getConstant(CC, MVT::i8), Cond);
15301
15302         // Zero extend the condition if needed.
15303         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15304
15305         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15306         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15307                            DAG.getConstant(ShAmt, MVT::i8));
15308         if (N->getNumValues() == 2)  // Dead flag value?
15309           return DCI.CombineTo(N, Cond, SDValue());
15310         return Cond;
15311       }
15312
15313       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
15314       // for any integer data type, including i8/i16.
15315       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15316         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15317                            DAG.getConstant(CC, MVT::i8), Cond);
15318
15319         // Zero extend the condition if needed.
15320         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15321                            FalseC->getValueType(0), Cond);
15322         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15323                            SDValue(FalseC, 0));
15324
15325         if (N->getNumValues() == 2)  // Dead flag value?
15326           return DCI.CombineTo(N, Cond, SDValue());
15327         return Cond;
15328       }
15329
15330       // Optimize cases that will turn into an LEA instruction.  This requires
15331       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15332       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15333         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15334         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15335
15336         bool isFastMultiplier = false;
15337         if (Diff < 10) {
15338           switch ((unsigned char)Diff) {
15339           default: break;
15340           case 1:  // result = add base, cond
15341           case 2:  // result = lea base(    , cond*2)
15342           case 3:  // result = lea base(cond, cond*2)
15343           case 4:  // result = lea base(    , cond*4)
15344           case 5:  // result = lea base(cond, cond*4)
15345           case 8:  // result = lea base(    , cond*8)
15346           case 9:  // result = lea base(cond, cond*8)
15347             isFastMultiplier = true;
15348             break;
15349           }
15350         }
15351
15352         if (isFastMultiplier) {
15353           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15354           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15355                              DAG.getConstant(CC, MVT::i8), Cond);
15356           // Zero extend the condition if needed.
15357           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15358                              Cond);
15359           // Scale the condition by the difference.
15360           if (Diff != 1)
15361             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15362                                DAG.getConstant(Diff, Cond.getValueType()));
15363
15364           // Add the base if non-zero.
15365           if (FalseC->getAPIntValue() != 0)
15366             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15367                                SDValue(FalseC, 0));
15368           if (N->getNumValues() == 2)  // Dead flag value?
15369             return DCI.CombineTo(N, Cond, SDValue());
15370           return Cond;
15371         }
15372       }
15373     }
15374   }
15375
15376   // Handle these cases:
15377   //   (select (x != c), e, c) -> select (x != c), e, x),
15378   //   (select (x == c), c, e) -> select (x == c), x, e)
15379   // where the c is an integer constant, and the "select" is the combination
15380   // of CMOV and CMP.
15381   //
15382   // The rationale for this change is that the conditional-move from a constant
15383   // needs two instructions, however, conditional-move from a register needs
15384   // only one instruction.
15385   //
15386   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15387   //  some instruction-combining opportunities. This opt needs to be
15388   //  postponed as late as possible.
15389   //
15390   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15391     // the DCI.xxxx conditions are provided to postpone the optimization as
15392     // late as possible.
15393
15394     ConstantSDNode *CmpAgainst = 0;
15395     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15396         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15397         dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15398
15399       if (CC == X86::COND_NE &&
15400           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15401         CC = X86::GetOppositeBranchCondition(CC);
15402         std::swap(TrueOp, FalseOp);
15403       }
15404
15405       if (CC == X86::COND_E &&
15406           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15407         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15408                           DAG.getConstant(CC, MVT::i8), Cond };
15409         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15410                            array_lengthof(Ops));
15411       }
15412     }
15413   }
15414
15415   return SDValue();
15416 }
15417
15418 /// PerformMulCombine - Optimize a single multiply with constant into two
15419 /// in order to implement it with two cheaper instructions, e.g.
15420 /// LEA + SHL, LEA + LEA.
15421 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15422                                  TargetLowering::DAGCombinerInfo &DCI) {
15423   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15424     return SDValue();
15425
15426   EVT VT = N->getValueType(0);
15427   if (VT != MVT::i64)
15428     return SDValue();
15429
15430   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15431   if (!C)
15432     return SDValue();
15433   uint64_t MulAmt = C->getZExtValue();
15434   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15435     return SDValue();
15436
15437   uint64_t MulAmt1 = 0;
15438   uint64_t MulAmt2 = 0;
15439   if ((MulAmt % 9) == 0) {
15440     MulAmt1 = 9;
15441     MulAmt2 = MulAmt / 9;
15442   } else if ((MulAmt % 5) == 0) {
15443     MulAmt1 = 5;
15444     MulAmt2 = MulAmt / 5;
15445   } else if ((MulAmt % 3) == 0) {
15446     MulAmt1 = 3;
15447     MulAmt2 = MulAmt / 3;
15448   }
15449   if (MulAmt2 &&
15450       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15451     DebugLoc DL = N->getDebugLoc();
15452
15453     if (isPowerOf2_64(MulAmt2) &&
15454         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15455       // If second multiplifer is pow2, issue it first. We want the multiply by
15456       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15457       // is an add.
15458       std::swap(MulAmt1, MulAmt2);
15459
15460     SDValue NewMul;
15461     if (isPowerOf2_64(MulAmt1))
15462       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15463                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15464     else
15465       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15466                            DAG.getConstant(MulAmt1, VT));
15467
15468     if (isPowerOf2_64(MulAmt2))
15469       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15470                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15471     else
15472       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15473                            DAG.getConstant(MulAmt2, VT));
15474
15475     // Do not add new nodes to DAG combiner worklist.
15476     DCI.CombineTo(N, NewMul, false);
15477   }
15478   return SDValue();
15479 }
15480
15481 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15482   SDValue N0 = N->getOperand(0);
15483   SDValue N1 = N->getOperand(1);
15484   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15485   EVT VT = N0.getValueType();
15486
15487   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15488   // since the result of setcc_c is all zero's or all ones.
15489   if (VT.isInteger() && !VT.isVector() &&
15490       N1C && N0.getOpcode() == ISD::AND &&
15491       N0.getOperand(1).getOpcode() == ISD::Constant) {
15492     SDValue N00 = N0.getOperand(0);
15493     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15494         ((N00.getOpcode() == ISD::ANY_EXTEND ||
15495           N00.getOpcode() == ISD::ZERO_EXTEND) &&
15496          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15497       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15498       APInt ShAmt = N1C->getAPIntValue();
15499       Mask = Mask.shl(ShAmt);
15500       if (Mask != 0)
15501         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15502                            N00, DAG.getConstant(Mask, VT));
15503     }
15504   }
15505
15506   // Hardware support for vector shifts is sparse which makes us scalarize the
15507   // vector operations in many cases. Also, on sandybridge ADD is faster than
15508   // shl.
15509   // (shl V, 1) -> add V,V
15510   if (isSplatVector(N1.getNode())) {
15511     assert(N0.getValueType().isVector() && "Invalid vector shift type");
15512     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15513     // We shift all of the values by one. In many cases we do not have
15514     // hardware support for this operation. This is better expressed as an ADD
15515     // of two values.
15516     if (N1C && (1 == N1C->getZExtValue())) {
15517       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15518     }
15519   }
15520
15521   return SDValue();
15522 }
15523
15524 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15525 ///                       when possible.
15526 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15527                                    TargetLowering::DAGCombinerInfo &DCI,
15528                                    const X86Subtarget *Subtarget) {
15529   EVT VT = N->getValueType(0);
15530   if (N->getOpcode() == ISD::SHL) {
15531     SDValue V = PerformSHLCombine(N, DAG);
15532     if (V.getNode()) return V;
15533   }
15534
15535   // On X86 with SSE2 support, we can transform this to a vector shift if
15536   // all elements are shifted by the same amount.  We can't do this in legalize
15537   // because the a constant vector is typically transformed to a constant pool
15538   // so we have no knowledge of the shift amount.
15539   if (!Subtarget->hasSSE2())
15540     return SDValue();
15541
15542   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15543       (!Subtarget->hasInt256() ||
15544        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15545     return SDValue();
15546
15547   SDValue ShAmtOp = N->getOperand(1);
15548   EVT EltVT = VT.getVectorElementType();
15549   DebugLoc DL = N->getDebugLoc();
15550   SDValue BaseShAmt = SDValue();
15551   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15552     unsigned NumElts = VT.getVectorNumElements();
15553     unsigned i = 0;
15554     for (; i != NumElts; ++i) {
15555       SDValue Arg = ShAmtOp.getOperand(i);
15556       if (Arg.getOpcode() == ISD::UNDEF) continue;
15557       BaseShAmt = Arg;
15558       break;
15559     }
15560     // Handle the case where the build_vector is all undef
15561     // FIXME: Should DAG allow this?
15562     if (i == NumElts)
15563       return SDValue();
15564
15565     for (; i != NumElts; ++i) {
15566       SDValue Arg = ShAmtOp.getOperand(i);
15567       if (Arg.getOpcode() == ISD::UNDEF) continue;
15568       if (Arg != BaseShAmt) {
15569         return SDValue();
15570       }
15571     }
15572   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15573              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15574     SDValue InVec = ShAmtOp.getOperand(0);
15575     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15576       unsigned NumElts = InVec.getValueType().getVectorNumElements();
15577       unsigned i = 0;
15578       for (; i != NumElts; ++i) {
15579         SDValue Arg = InVec.getOperand(i);
15580         if (Arg.getOpcode() == ISD::UNDEF) continue;
15581         BaseShAmt = Arg;
15582         break;
15583       }
15584     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15585        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15586          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15587          if (C->getZExtValue() == SplatIdx)
15588            BaseShAmt = InVec.getOperand(1);
15589        }
15590     }
15591     if (BaseShAmt.getNode() == 0) {
15592       // Don't create instructions with illegal types after legalize
15593       // types has run.
15594       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15595           !DCI.isBeforeLegalize())
15596         return SDValue();
15597
15598       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15599                               DAG.getIntPtrConstant(0));
15600     }
15601   } else
15602     return SDValue();
15603
15604   // The shift amount is an i32.
15605   if (EltVT.bitsGT(MVT::i32))
15606     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15607   else if (EltVT.bitsLT(MVT::i32))
15608     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15609
15610   // The shift amount is identical so we can do a vector shift.
15611   SDValue  ValOp = N->getOperand(0);
15612   switch (N->getOpcode()) {
15613   default:
15614     llvm_unreachable("Unknown shift opcode!");
15615   case ISD::SHL:
15616     switch (VT.getSimpleVT().SimpleTy) {
15617     default: return SDValue();
15618     case MVT::v2i64:
15619     case MVT::v4i32:
15620     case MVT::v8i16:
15621     case MVT::v4i64:
15622     case MVT::v8i32:
15623     case MVT::v16i16:
15624       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15625     }
15626   case ISD::SRA:
15627     switch (VT.getSimpleVT().SimpleTy) {
15628     default: return SDValue();
15629     case MVT::v4i32:
15630     case MVT::v8i16:
15631     case MVT::v8i32:
15632     case MVT::v16i16:
15633       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15634     }
15635   case ISD::SRL:
15636     switch (VT.getSimpleVT().SimpleTy) {
15637     default: return SDValue();
15638     case MVT::v2i64:
15639     case MVT::v4i32:
15640     case MVT::v8i16:
15641     case MVT::v4i64:
15642     case MVT::v8i32:
15643     case MVT::v16i16:
15644       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15645     }
15646   }
15647 }
15648
15649 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15650 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15651 // and friends.  Likewise for OR -> CMPNEQSS.
15652 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15653                             TargetLowering::DAGCombinerInfo &DCI,
15654                             const X86Subtarget *Subtarget) {
15655   unsigned opcode;
15656
15657   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15658   // we're requiring SSE2 for both.
15659   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15660     SDValue N0 = N->getOperand(0);
15661     SDValue N1 = N->getOperand(1);
15662     SDValue CMP0 = N0->getOperand(1);
15663     SDValue CMP1 = N1->getOperand(1);
15664     DebugLoc DL = N->getDebugLoc();
15665
15666     // The SETCCs should both refer to the same CMP.
15667     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15668       return SDValue();
15669
15670     SDValue CMP00 = CMP0->getOperand(0);
15671     SDValue CMP01 = CMP0->getOperand(1);
15672     EVT     VT    = CMP00.getValueType();
15673
15674     if (VT == MVT::f32 || VT == MVT::f64) {
15675       bool ExpectingFlags = false;
15676       // Check for any users that want flags:
15677       for (SDNode::use_iterator UI = N->use_begin(),
15678              UE = N->use_end();
15679            !ExpectingFlags && UI != UE; ++UI)
15680         switch (UI->getOpcode()) {
15681         default:
15682         case ISD::BR_CC:
15683         case ISD::BRCOND:
15684         case ISD::SELECT:
15685           ExpectingFlags = true;
15686           break;
15687         case ISD::CopyToReg:
15688         case ISD::SIGN_EXTEND:
15689         case ISD::ZERO_EXTEND:
15690         case ISD::ANY_EXTEND:
15691           break;
15692         }
15693
15694       if (!ExpectingFlags) {
15695         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15696         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15697
15698         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15699           X86::CondCode tmp = cc0;
15700           cc0 = cc1;
15701           cc1 = tmp;
15702         }
15703
15704         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15705             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15706           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15707           X86ISD::NodeType NTOperator = is64BitFP ?
15708             X86ISD::FSETCCsd : X86ISD::FSETCCss;
15709           // FIXME: need symbolic constants for these magic numbers.
15710           // See X86ATTInstPrinter.cpp:printSSECC().
15711           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15712           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15713                                               DAG.getConstant(x86cc, MVT::i8));
15714           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15715                                               OnesOrZeroesF);
15716           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15717                                       DAG.getConstant(1, MVT::i32));
15718           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15719           return OneBitOfTruth;
15720         }
15721       }
15722     }
15723   }
15724   return SDValue();
15725 }
15726
15727 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15728 /// so it can be folded inside ANDNP.
15729 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15730   EVT VT = N->getValueType(0);
15731
15732   // Match direct AllOnes for 128 and 256-bit vectors
15733   if (ISD::isBuildVectorAllOnes(N))
15734     return true;
15735
15736   // Look through a bit convert.
15737   if (N->getOpcode() == ISD::BITCAST)
15738     N = N->getOperand(0).getNode();
15739
15740   // Sometimes the operand may come from a insert_subvector building a 256-bit
15741   // allones vector
15742   if (VT.is256BitVector() &&
15743       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15744     SDValue V1 = N->getOperand(0);
15745     SDValue V2 = N->getOperand(1);
15746
15747     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15748         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15749         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15750         ISD::isBuildVectorAllOnes(V2.getNode()))
15751       return true;
15752   }
15753
15754   return false;
15755 }
15756
15757 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15758                                  TargetLowering::DAGCombinerInfo &DCI,
15759                                  const X86Subtarget *Subtarget) {
15760   if (DCI.isBeforeLegalizeOps())
15761     return SDValue();
15762
15763   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15764   if (R.getNode())
15765     return R;
15766
15767   EVT VT = N->getValueType(0);
15768
15769   // Create BLSI, and BLSR instructions
15770   // BLSI is X & (-X)
15771   // BLSR is X & (X-1)
15772   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15773     SDValue N0 = N->getOperand(0);
15774     SDValue N1 = N->getOperand(1);
15775     DebugLoc DL = N->getDebugLoc();
15776
15777     // Check LHS for neg
15778     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15779         isZero(N0.getOperand(0)))
15780       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15781
15782     // Check RHS for neg
15783     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15784         isZero(N1.getOperand(0)))
15785       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15786
15787     // Check LHS for X-1
15788     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15789         isAllOnes(N0.getOperand(1)))
15790       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15791
15792     // Check RHS for X-1
15793     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15794         isAllOnes(N1.getOperand(1)))
15795       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15796
15797     return SDValue();
15798   }
15799
15800   // Want to form ANDNP nodes:
15801   // 1) In the hopes of then easily combining them with OR and AND nodes
15802   //    to form PBLEND/PSIGN.
15803   // 2) To match ANDN packed intrinsics
15804   if (VT != MVT::v2i64 && VT != MVT::v4i64)
15805     return SDValue();
15806
15807   SDValue N0 = N->getOperand(0);
15808   SDValue N1 = N->getOperand(1);
15809   DebugLoc DL = N->getDebugLoc();
15810
15811   // Check LHS for vnot
15812   if (N0.getOpcode() == ISD::XOR &&
15813       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15814       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15815     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15816
15817   // Check RHS for vnot
15818   if (N1.getOpcode() == ISD::XOR &&
15819       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15820       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15821     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15822
15823   return SDValue();
15824 }
15825
15826 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15827                                 TargetLowering::DAGCombinerInfo &DCI,
15828                                 const X86Subtarget *Subtarget) {
15829   if (DCI.isBeforeLegalizeOps())
15830     return SDValue();
15831
15832   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15833   if (R.getNode())
15834     return R;
15835
15836   EVT VT = N->getValueType(0);
15837
15838   SDValue N0 = N->getOperand(0);
15839   SDValue N1 = N->getOperand(1);
15840
15841   // look for psign/blend
15842   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15843     if (!Subtarget->hasSSSE3() ||
15844         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
15845       return SDValue();
15846
15847     // Canonicalize pandn to RHS
15848     if (N0.getOpcode() == X86ISD::ANDNP)
15849       std::swap(N0, N1);
15850     // or (and (m, y), (pandn m, x))
15851     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15852       SDValue Mask = N1.getOperand(0);
15853       SDValue X    = N1.getOperand(1);
15854       SDValue Y;
15855       if (N0.getOperand(0) == Mask)
15856         Y = N0.getOperand(1);
15857       if (N0.getOperand(1) == Mask)
15858         Y = N0.getOperand(0);
15859
15860       // Check to see if the mask appeared in both the AND and ANDNP and
15861       if (!Y.getNode())
15862         return SDValue();
15863
15864       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15865       // Look through mask bitcast.
15866       if (Mask.getOpcode() == ISD::BITCAST)
15867         Mask = Mask.getOperand(0);
15868       if (X.getOpcode() == ISD::BITCAST)
15869         X = X.getOperand(0);
15870       if (Y.getOpcode() == ISD::BITCAST)
15871         Y = Y.getOperand(0);
15872
15873       EVT MaskVT = Mask.getValueType();
15874
15875       // Validate that the Mask operand is a vector sra node.
15876       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15877       // there is no psrai.b
15878       if (Mask.getOpcode() != X86ISD::VSRAI)
15879         return SDValue();
15880
15881       // Check that the SRA is all signbits.
15882       SDValue SraC = Mask.getOperand(1);
15883       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
15884       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15885       if ((SraAmt + 1) != EltBits)
15886         return SDValue();
15887
15888       DebugLoc DL = N->getDebugLoc();
15889
15890       // We are going to replace the AND, OR, NAND with either BLEND
15891       // or PSIGN, which only look at the MSB. The VSRAI instruction
15892       // does not affect the highest bit, so we can get rid of it.
15893       Mask = Mask.getOperand(0);
15894
15895       // Now we know we at least have a plendvb with the mask val.  See if
15896       // we can form a psignb/w/d.
15897       // psign = x.type == y.type == mask.type && y = sub(0, x);
15898       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15899           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15900           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15901         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15902                "Unsupported VT for PSIGN");
15903         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask);
15904         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15905       }
15906       // PBLENDVB only available on SSE 4.1
15907       if (!Subtarget->hasSSE41())
15908         return SDValue();
15909
15910       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15911
15912       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15913       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15914       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15915       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15916       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15917     }
15918   }
15919
15920   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15921     return SDValue();
15922
15923   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15924   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15925     std::swap(N0, N1);
15926   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15927     return SDValue();
15928   if (!N0.hasOneUse() || !N1.hasOneUse())
15929     return SDValue();
15930
15931   SDValue ShAmt0 = N0.getOperand(1);
15932   if (ShAmt0.getValueType() != MVT::i8)
15933     return SDValue();
15934   SDValue ShAmt1 = N1.getOperand(1);
15935   if (ShAmt1.getValueType() != MVT::i8)
15936     return SDValue();
15937   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15938     ShAmt0 = ShAmt0.getOperand(0);
15939   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15940     ShAmt1 = ShAmt1.getOperand(0);
15941
15942   DebugLoc DL = N->getDebugLoc();
15943   unsigned Opc = X86ISD::SHLD;
15944   SDValue Op0 = N0.getOperand(0);
15945   SDValue Op1 = N1.getOperand(0);
15946   if (ShAmt0.getOpcode() == ISD::SUB) {
15947     Opc = X86ISD::SHRD;
15948     std::swap(Op0, Op1);
15949     std::swap(ShAmt0, ShAmt1);
15950   }
15951
15952   unsigned Bits = VT.getSizeInBits();
15953   if (ShAmt1.getOpcode() == ISD::SUB) {
15954     SDValue Sum = ShAmt1.getOperand(0);
15955     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15956       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15957       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15958         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15959       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15960         return DAG.getNode(Opc, DL, VT,
15961                            Op0, Op1,
15962                            DAG.getNode(ISD::TRUNCATE, DL,
15963                                        MVT::i8, ShAmt0));
15964     }
15965   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15966     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15967     if (ShAmt0C &&
15968         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15969       return DAG.getNode(Opc, DL, VT,
15970                          N0.getOperand(0), N1.getOperand(0),
15971                          DAG.getNode(ISD::TRUNCATE, DL,
15972                                        MVT::i8, ShAmt0));
15973   }
15974
15975   return SDValue();
15976 }
15977
15978 // Generate NEG and CMOV for integer abs.
15979 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15980   EVT VT = N->getValueType(0);
15981
15982   // Since X86 does not have CMOV for 8-bit integer, we don't convert
15983   // 8-bit integer abs to NEG and CMOV.
15984   if (VT.isInteger() && VT.getSizeInBits() == 8)
15985     return SDValue();
15986
15987   SDValue N0 = N->getOperand(0);
15988   SDValue N1 = N->getOperand(1);
15989   DebugLoc DL = N->getDebugLoc();
15990
15991   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15992   // and change it to SUB and CMOV.
15993   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15994       N0.getOpcode() == ISD::ADD &&
15995       N0.getOperand(1) == N1 &&
15996       N1.getOpcode() == ISD::SRA &&
15997       N1.getOperand(0) == N0.getOperand(0))
15998     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15999       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16000         // Generate SUB & CMOV.
16001         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16002                                   DAG.getConstant(0, VT), N0.getOperand(0));
16003
16004         SDValue Ops[] = { N0.getOperand(0), Neg,
16005                           DAG.getConstant(X86::COND_GE, MVT::i8),
16006                           SDValue(Neg.getNode(), 1) };
16007         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16008                            Ops, array_lengthof(Ops));
16009       }
16010   return SDValue();
16011 }
16012
16013 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16014 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16015                                  TargetLowering::DAGCombinerInfo &DCI,
16016                                  const X86Subtarget *Subtarget) {
16017   if (DCI.isBeforeLegalizeOps())
16018     return SDValue();
16019
16020   if (Subtarget->hasCMov()) {
16021     SDValue RV = performIntegerAbsCombine(N, DAG);
16022     if (RV.getNode())
16023       return RV;
16024   }
16025
16026   // Try forming BMI if it is available.
16027   if (!Subtarget->hasBMI())
16028     return SDValue();
16029
16030   EVT VT = N->getValueType(0);
16031
16032   if (VT != MVT::i32 && VT != MVT::i64)
16033     return SDValue();
16034
16035   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16036
16037   // Create BLSMSK instructions by finding X ^ (X-1)
16038   SDValue N0 = N->getOperand(0);
16039   SDValue N1 = N->getOperand(1);
16040   DebugLoc DL = N->getDebugLoc();
16041
16042   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16043       isAllOnes(N0.getOperand(1)))
16044     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16045
16046   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16047       isAllOnes(N1.getOperand(1)))
16048     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16049
16050   return SDValue();
16051 }
16052
16053 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16054 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16055                                   TargetLowering::DAGCombinerInfo &DCI,
16056                                   const X86Subtarget *Subtarget) {
16057   LoadSDNode *Ld = cast<LoadSDNode>(N);
16058   EVT RegVT = Ld->getValueType(0);
16059   EVT MemVT = Ld->getMemoryVT();
16060   DebugLoc dl = Ld->getDebugLoc();
16061   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16062
16063   ISD::LoadExtType Ext = Ld->getExtensionType();
16064
16065   // If this is a vector EXT Load then attempt to optimize it using a
16066   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16067   // expansion is still better than scalar code.
16068   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16069   // emit a shuffle and a arithmetic shift.
16070   // TODO: It is possible to support ZExt by zeroing the undef values
16071   // during the shuffle phase or after the shuffle.
16072   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16073       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16074     assert(MemVT != RegVT && "Cannot extend to the same type");
16075     assert(MemVT.isVector() && "Must load a vector from memory");
16076
16077     unsigned NumElems = RegVT.getVectorNumElements();
16078     unsigned RegSz = RegVT.getSizeInBits();
16079     unsigned MemSz = MemVT.getSizeInBits();
16080     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16081
16082     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16083       return SDValue();
16084
16085     // All sizes must be a power of two.
16086     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16087       return SDValue();
16088
16089     // Attempt to load the original value using scalar loads.
16090     // Find the largest scalar type that divides the total loaded size.
16091     MVT SclrLoadTy = MVT::i8;
16092     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16093          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16094       MVT Tp = (MVT::SimpleValueType)tp;
16095       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16096         SclrLoadTy = Tp;
16097       }
16098     }
16099
16100     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16101     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16102         (64 <= MemSz))
16103       SclrLoadTy = MVT::f64;
16104
16105     // Calculate the number of scalar loads that we need to perform
16106     // in order to load our vector from memory.
16107     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16108     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16109       return SDValue();
16110
16111     unsigned loadRegZize = RegSz;
16112     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16113       loadRegZize /= 2;
16114
16115     // Represent our vector as a sequence of elements which are the
16116     // largest scalar that we can load.
16117     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16118       loadRegZize/SclrLoadTy.getSizeInBits());
16119
16120     // Represent the data using the same element type that is stored in
16121     // memory. In practice, we ''widen'' MemVT.
16122     EVT WideVecVT = 
16123           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16124                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16125
16126     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16127       "Invalid vector type");
16128
16129     // We can't shuffle using an illegal type.
16130     if (!TLI.isTypeLegal(WideVecVT))
16131       return SDValue();
16132
16133     SmallVector<SDValue, 8> Chains;
16134     SDValue Ptr = Ld->getBasePtr();
16135     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16136                                         TLI.getPointerTy());
16137     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16138
16139     for (unsigned i = 0; i < NumLoads; ++i) {
16140       // Perform a single load.
16141       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16142                                        Ptr, Ld->getPointerInfo(),
16143                                        Ld->isVolatile(), Ld->isNonTemporal(),
16144                                        Ld->isInvariant(), Ld->getAlignment());
16145       Chains.push_back(ScalarLoad.getValue(1));
16146       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16147       // another round of DAGCombining.
16148       if (i == 0)
16149         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16150       else
16151         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16152                           ScalarLoad, DAG.getIntPtrConstant(i));
16153
16154       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16155     }
16156
16157     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16158                                Chains.size());
16159
16160     // Bitcast the loaded value to a vector of the original element type, in
16161     // the size of the target vector type.
16162     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16163     unsigned SizeRatio = RegSz/MemSz;
16164
16165     if (Ext == ISD::SEXTLOAD) {
16166       // If we have SSE4.1 we can directly emit a VSEXT node.
16167       if (Subtarget->hasSSE41()) {
16168         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16169         return DCI.CombineTo(N, Sext, TF, true);
16170       }
16171
16172       // Otherwise we'll shuffle the small elements in the high bits of the
16173       // larger type and perform an arithmetic shift. If the shift is not legal
16174       // it's better to scalarize.
16175       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16176         return SDValue();
16177
16178       // Redistribute the loaded elements into the different locations.
16179       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16180       for (unsigned i = 0; i != NumElems; ++i)
16181         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16182
16183       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16184                                            DAG.getUNDEF(WideVecVT),
16185                                            &ShuffleVec[0]);
16186
16187       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16188
16189       // Build the arithmetic shift.
16190       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16191                      MemVT.getVectorElementType().getSizeInBits();
16192       SmallVector<SDValue, 8> C(NumElems,
16193                                 DAG.getConstant(Amt, RegVT.getScalarType()));
16194       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, RegVT, &C[0], C.size());
16195       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff, BV);
16196
16197       return DCI.CombineTo(N, Shuff, TF, true);
16198     }
16199
16200     // Redistribute the loaded elements into the different locations.
16201     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16202     for (unsigned i = 0; i != NumElems; ++i)
16203       ShuffleVec[i*SizeRatio] = i;
16204
16205     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16206                                          DAG.getUNDEF(WideVecVT),
16207                                          &ShuffleVec[0]);
16208
16209     // Bitcast to the requested type.
16210     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16211     // Replace the original load with the new sequence
16212     // and return the new chain.
16213     return DCI.CombineTo(N, Shuff, TF, true);
16214   }
16215
16216   return SDValue();
16217 }
16218
16219 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16220 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16221                                    const X86Subtarget *Subtarget) {
16222   StoreSDNode *St = cast<StoreSDNode>(N);
16223   EVT VT = St->getValue().getValueType();
16224   EVT StVT = St->getMemoryVT();
16225   DebugLoc dl = St->getDebugLoc();
16226   SDValue StoredVal = St->getOperand(1);
16227   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16228
16229   // If we are saving a concatenation of two XMM registers, perform two stores.
16230   // On Sandy Bridge, 256-bit memory operations are executed by two
16231   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16232   // memory  operation.
16233   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16234       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
16235       StoredVal.getNumOperands() == 2) {
16236     SDValue Value0 = StoredVal.getOperand(0);
16237     SDValue Value1 = StoredVal.getOperand(1);
16238
16239     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16240     SDValue Ptr0 = St->getBasePtr();
16241     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16242
16243     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16244                                 St->getPointerInfo(), St->isVolatile(),
16245                                 St->isNonTemporal(), St->getAlignment());
16246     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16247                                 St->getPointerInfo(), St->isVolatile(),
16248                                 St->isNonTemporal(), St->getAlignment());
16249     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16250   }
16251
16252   // Optimize trunc store (of multiple scalars) to shuffle and store.
16253   // First, pack all of the elements in one place. Next, store to memory
16254   // in fewer chunks.
16255   if (St->isTruncatingStore() && VT.isVector()) {
16256     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16257     unsigned NumElems = VT.getVectorNumElements();
16258     assert(StVT != VT && "Cannot truncate to the same type");
16259     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16260     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16261
16262     // From, To sizes and ElemCount must be pow of two
16263     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16264     // We are going to use the original vector elt for storing.
16265     // Accumulated smaller vector elements must be a multiple of the store size.
16266     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16267
16268     unsigned SizeRatio  = FromSz / ToSz;
16269
16270     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16271
16272     // Create a type on which we perform the shuffle
16273     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16274             StVT.getScalarType(), NumElems*SizeRatio);
16275
16276     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16277
16278     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16279     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16280     for (unsigned i = 0; i != NumElems; ++i)
16281       ShuffleVec[i] = i * SizeRatio;
16282
16283     // Can't shuffle using an illegal type.
16284     if (!TLI.isTypeLegal(WideVecVT))
16285       return SDValue();
16286
16287     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16288                                          DAG.getUNDEF(WideVecVT),
16289                                          &ShuffleVec[0]);
16290     // At this point all of the data is stored at the bottom of the
16291     // register. We now need to save it to mem.
16292
16293     // Find the largest store unit
16294     MVT StoreType = MVT::i8;
16295     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16296          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16297       MVT Tp = (MVT::SimpleValueType)tp;
16298       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16299         StoreType = Tp;
16300     }
16301
16302     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16303     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16304         (64 <= NumElems * ToSz))
16305       StoreType = MVT::f64;
16306
16307     // Bitcast the original vector into a vector of store-size units
16308     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16309             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16310     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16311     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16312     SmallVector<SDValue, 8> Chains;
16313     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16314                                         TLI.getPointerTy());
16315     SDValue Ptr = St->getBasePtr();
16316
16317     // Perform one or more big stores into memory.
16318     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16319       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16320                                    StoreType, ShuffWide,
16321                                    DAG.getIntPtrConstant(i));
16322       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16323                                 St->getPointerInfo(), St->isVolatile(),
16324                                 St->isNonTemporal(), St->getAlignment());
16325       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16326       Chains.push_back(Ch);
16327     }
16328
16329     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16330                                Chains.size());
16331   }
16332
16333   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
16334   // the FP state in cases where an emms may be missing.
16335   // A preferable solution to the general problem is to figure out the right
16336   // places to insert EMMS.  This qualifies as a quick hack.
16337
16338   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16339   if (VT.getSizeInBits() != 64)
16340     return SDValue();
16341
16342   const Function *F = DAG.getMachineFunction().getFunction();
16343   bool NoImplicitFloatOps = F->getFnAttributes().
16344     hasAttribute(Attribute::NoImplicitFloat);
16345   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16346                      && Subtarget->hasSSE2();
16347   if ((VT.isVector() ||
16348        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16349       isa<LoadSDNode>(St->getValue()) &&
16350       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16351       St->getChain().hasOneUse() && !St->isVolatile()) {
16352     SDNode* LdVal = St->getValue().getNode();
16353     LoadSDNode *Ld = 0;
16354     int TokenFactorIndex = -1;
16355     SmallVector<SDValue, 8> Ops;
16356     SDNode* ChainVal = St->getChain().getNode();
16357     // Must be a store of a load.  We currently handle two cases:  the load
16358     // is a direct child, and it's under an intervening TokenFactor.  It is
16359     // possible to dig deeper under nested TokenFactors.
16360     if (ChainVal == LdVal)
16361       Ld = cast<LoadSDNode>(St->getChain());
16362     else if (St->getValue().hasOneUse() &&
16363              ChainVal->getOpcode() == ISD::TokenFactor) {
16364       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16365         if (ChainVal->getOperand(i).getNode() == LdVal) {
16366           TokenFactorIndex = i;
16367           Ld = cast<LoadSDNode>(St->getValue());
16368         } else
16369           Ops.push_back(ChainVal->getOperand(i));
16370       }
16371     }
16372
16373     if (!Ld || !ISD::isNormalLoad(Ld))
16374       return SDValue();
16375
16376     // If this is not the MMX case, i.e. we are just turning i64 load/store
16377     // into f64 load/store, avoid the transformation if there are multiple
16378     // uses of the loaded value.
16379     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16380       return SDValue();
16381
16382     DebugLoc LdDL = Ld->getDebugLoc();
16383     DebugLoc StDL = N->getDebugLoc();
16384     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16385     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16386     // pair instead.
16387     if (Subtarget->is64Bit() || F64IsLegal) {
16388       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16389       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16390                                   Ld->getPointerInfo(), Ld->isVolatile(),
16391                                   Ld->isNonTemporal(), Ld->isInvariant(),
16392                                   Ld->getAlignment());
16393       SDValue NewChain = NewLd.getValue(1);
16394       if (TokenFactorIndex != -1) {
16395         Ops.push_back(NewChain);
16396         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16397                                Ops.size());
16398       }
16399       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16400                           St->getPointerInfo(),
16401                           St->isVolatile(), St->isNonTemporal(),
16402                           St->getAlignment());
16403     }
16404
16405     // Otherwise, lower to two pairs of 32-bit loads / stores.
16406     SDValue LoAddr = Ld->getBasePtr();
16407     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16408                                  DAG.getConstant(4, MVT::i32));
16409
16410     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16411                                Ld->getPointerInfo(),
16412                                Ld->isVolatile(), Ld->isNonTemporal(),
16413                                Ld->isInvariant(), Ld->getAlignment());
16414     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16415                                Ld->getPointerInfo().getWithOffset(4),
16416                                Ld->isVolatile(), Ld->isNonTemporal(),
16417                                Ld->isInvariant(),
16418                                MinAlign(Ld->getAlignment(), 4));
16419
16420     SDValue NewChain = LoLd.getValue(1);
16421     if (TokenFactorIndex != -1) {
16422       Ops.push_back(LoLd);
16423       Ops.push_back(HiLd);
16424       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16425                              Ops.size());
16426     }
16427
16428     LoAddr = St->getBasePtr();
16429     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16430                          DAG.getConstant(4, MVT::i32));
16431
16432     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16433                                 St->getPointerInfo(),
16434                                 St->isVolatile(), St->isNonTemporal(),
16435                                 St->getAlignment());
16436     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16437                                 St->getPointerInfo().getWithOffset(4),
16438                                 St->isVolatile(),
16439                                 St->isNonTemporal(),
16440                                 MinAlign(St->getAlignment(), 4));
16441     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16442   }
16443   return SDValue();
16444 }
16445
16446 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16447 /// and return the operands for the horizontal operation in LHS and RHS.  A
16448 /// horizontal operation performs the binary operation on successive elements
16449 /// of its first operand, then on successive elements of its second operand,
16450 /// returning the resulting values in a vector.  For example, if
16451 ///   A = < float a0, float a1, float a2, float a3 >
16452 /// and
16453 ///   B = < float b0, float b1, float b2, float b3 >
16454 /// then the result of doing a horizontal operation on A and B is
16455 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16456 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16457 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16458 /// set to A, RHS to B, and the routine returns 'true'.
16459 /// Note that the binary operation should have the property that if one of the
16460 /// operands is UNDEF then the result is UNDEF.
16461 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16462   // Look for the following pattern: if
16463   //   A = < float a0, float a1, float a2, float a3 >
16464   //   B = < float b0, float b1, float b2, float b3 >
16465   // and
16466   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16467   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16468   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16469   // which is A horizontal-op B.
16470
16471   // At least one of the operands should be a vector shuffle.
16472   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16473       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16474     return false;
16475
16476   EVT VT = LHS.getValueType();
16477
16478   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16479          "Unsupported vector type for horizontal add/sub");
16480
16481   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16482   // operate independently on 128-bit lanes.
16483   unsigned NumElts = VT.getVectorNumElements();
16484   unsigned NumLanes = VT.getSizeInBits()/128;
16485   unsigned NumLaneElts = NumElts / NumLanes;
16486   assert((NumLaneElts % 2 == 0) &&
16487          "Vector type should have an even number of elements in each lane");
16488   unsigned HalfLaneElts = NumLaneElts/2;
16489
16490   // View LHS in the form
16491   //   LHS = VECTOR_SHUFFLE A, B, LMask
16492   // If LHS is not a shuffle then pretend it is the shuffle
16493   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16494   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16495   // type VT.
16496   SDValue A, B;
16497   SmallVector<int, 16> LMask(NumElts);
16498   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16499     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16500       A = LHS.getOperand(0);
16501     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16502       B = LHS.getOperand(1);
16503     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16504     std::copy(Mask.begin(), Mask.end(), LMask.begin());
16505   } else {
16506     if (LHS.getOpcode() != ISD::UNDEF)
16507       A = LHS;
16508     for (unsigned i = 0; i != NumElts; ++i)
16509       LMask[i] = i;
16510   }
16511
16512   // Likewise, view RHS in the form
16513   //   RHS = VECTOR_SHUFFLE C, D, RMask
16514   SDValue C, D;
16515   SmallVector<int, 16> RMask(NumElts);
16516   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16517     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16518       C = RHS.getOperand(0);
16519     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16520       D = RHS.getOperand(1);
16521     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16522     std::copy(Mask.begin(), Mask.end(), RMask.begin());
16523   } else {
16524     if (RHS.getOpcode() != ISD::UNDEF)
16525       C = RHS;
16526     for (unsigned i = 0; i != NumElts; ++i)
16527       RMask[i] = i;
16528   }
16529
16530   // Check that the shuffles are both shuffling the same vectors.
16531   if (!(A == C && B == D) && !(A == D && B == C))
16532     return false;
16533
16534   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16535   if (!A.getNode() && !B.getNode())
16536     return false;
16537
16538   // If A and B occur in reverse order in RHS, then "swap" them (which means
16539   // rewriting the mask).
16540   if (A != C)
16541     CommuteVectorShuffleMask(RMask, NumElts);
16542
16543   // At this point LHS and RHS are equivalent to
16544   //   LHS = VECTOR_SHUFFLE A, B, LMask
16545   //   RHS = VECTOR_SHUFFLE A, B, RMask
16546   // Check that the masks correspond to performing a horizontal operation.
16547   for (unsigned i = 0; i != NumElts; ++i) {
16548     int LIdx = LMask[i], RIdx = RMask[i];
16549
16550     // Ignore any UNDEF components.
16551     if (LIdx < 0 || RIdx < 0 ||
16552         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16553         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16554       continue;
16555
16556     // Check that successive elements are being operated on.  If not, this is
16557     // not a horizontal operation.
16558     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16559     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16560     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16561     if (!(LIdx == Index && RIdx == Index + 1) &&
16562         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16563       return false;
16564   }
16565
16566   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16567   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16568   return true;
16569 }
16570
16571 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16572 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16573                                   const X86Subtarget *Subtarget) {
16574   EVT VT = N->getValueType(0);
16575   SDValue LHS = N->getOperand(0);
16576   SDValue RHS = N->getOperand(1);
16577
16578   // Try to synthesize horizontal adds from adds of shuffles.
16579   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16580        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16581       isHorizontalBinOp(LHS, RHS, true))
16582     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16583   return SDValue();
16584 }
16585
16586 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16587 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16588                                   const X86Subtarget *Subtarget) {
16589   EVT VT = N->getValueType(0);
16590   SDValue LHS = N->getOperand(0);
16591   SDValue RHS = N->getOperand(1);
16592
16593   // Try to synthesize horizontal subs from subs of shuffles.
16594   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16595        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16596       isHorizontalBinOp(LHS, RHS, false))
16597     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16598   return SDValue();
16599 }
16600
16601 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16602 /// X86ISD::FXOR nodes.
16603 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16604   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16605   // F[X]OR(0.0, x) -> x
16606   // F[X]OR(x, 0.0) -> x
16607   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16608     if (C->getValueAPF().isPosZero())
16609       return N->getOperand(1);
16610   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16611     if (C->getValueAPF().isPosZero())
16612       return N->getOperand(0);
16613   return SDValue();
16614 }
16615
16616 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16617 /// X86ISD::FMAX nodes.
16618 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16619   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16620
16621   // Only perform optimizations if UnsafeMath is used.
16622   if (!DAG.getTarget().Options.UnsafeFPMath)
16623     return SDValue();
16624
16625   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16626   // into FMINC and FMAXC, which are Commutative operations.
16627   unsigned NewOp = 0;
16628   switch (N->getOpcode()) {
16629     default: llvm_unreachable("unknown opcode");
16630     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
16631     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
16632   }
16633
16634   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16635                      N->getOperand(0), N->getOperand(1));
16636 }
16637
16638 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16639 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16640   // FAND(0.0, x) -> 0.0
16641   // FAND(x, 0.0) -> 0.0
16642   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16643     if (C->getValueAPF().isPosZero())
16644       return N->getOperand(0);
16645   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16646     if (C->getValueAPF().isPosZero())
16647       return N->getOperand(1);
16648   return SDValue();
16649 }
16650
16651 static SDValue PerformBTCombine(SDNode *N,
16652                                 SelectionDAG &DAG,
16653                                 TargetLowering::DAGCombinerInfo &DCI) {
16654   // BT ignores high bits in the bit index operand.
16655   SDValue Op1 = N->getOperand(1);
16656   if (Op1.hasOneUse()) {
16657     unsigned BitWidth = Op1.getValueSizeInBits();
16658     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16659     APInt KnownZero, KnownOne;
16660     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16661                                           !DCI.isBeforeLegalizeOps());
16662     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16663     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16664         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16665       DCI.CommitTargetLoweringOpt(TLO);
16666   }
16667   return SDValue();
16668 }
16669
16670 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16671   SDValue Op = N->getOperand(0);
16672   if (Op.getOpcode() == ISD::BITCAST)
16673     Op = Op.getOperand(0);
16674   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16675   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16676       VT.getVectorElementType().getSizeInBits() ==
16677       OpVT.getVectorElementType().getSizeInBits()) {
16678     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16679   }
16680   return SDValue();
16681 }
16682
16683 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16684                                   TargetLowering::DAGCombinerInfo &DCI,
16685                                   const X86Subtarget *Subtarget) {
16686   if (!DCI.isBeforeLegalizeOps())
16687     return SDValue();
16688
16689   if (!Subtarget->hasFp256())
16690     return SDValue();
16691
16692   EVT VT = N->getValueType(0);
16693   SDValue Op = N->getOperand(0);
16694   EVT OpVT = Op.getValueType();
16695   DebugLoc dl = N->getDebugLoc();
16696
16697   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16698       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16699
16700     if (Subtarget->hasInt256())
16701       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16702
16703     // Optimize vectors in AVX mode
16704     // Sign extend  v8i16 to v8i32 and
16705     //              v4i32 to v4i64
16706     //
16707     // Divide input vector into two parts
16708     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16709     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16710     // concat the vectors to original VT
16711
16712     unsigned NumElems = OpVT.getVectorNumElements();
16713     SDValue Undef = DAG.getUNDEF(OpVT);
16714
16715     SmallVector<int,8> ShufMask1(NumElems, -1);
16716     for (unsigned i = 0; i != NumElems/2; ++i)
16717       ShufMask1[i] = i;
16718
16719     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16720
16721     SmallVector<int,8> ShufMask2(NumElems, -1);
16722     for (unsigned i = 0; i != NumElems/2; ++i)
16723       ShufMask2[i] = i + NumElems/2;
16724
16725     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16726
16727     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16728                                   VT.getVectorNumElements()/2);
16729
16730     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16731     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16732
16733     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16734   }
16735   return SDValue();
16736 }
16737
16738 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16739                                  const X86Subtarget* Subtarget) {
16740   DebugLoc dl = N->getDebugLoc();
16741   EVT VT = N->getValueType(0);
16742
16743   // Let legalize expand this if it isn't a legal type yet.
16744   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16745     return SDValue();
16746
16747   EVT ScalarVT = VT.getScalarType();
16748   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16749       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16750     return SDValue();
16751
16752   SDValue A = N->getOperand(0);
16753   SDValue B = N->getOperand(1);
16754   SDValue C = N->getOperand(2);
16755
16756   bool NegA = (A.getOpcode() == ISD::FNEG);
16757   bool NegB = (B.getOpcode() == ISD::FNEG);
16758   bool NegC = (C.getOpcode() == ISD::FNEG);
16759
16760   // Negative multiplication when NegA xor NegB
16761   bool NegMul = (NegA != NegB);
16762   if (NegA)
16763     A = A.getOperand(0);
16764   if (NegB)
16765     B = B.getOperand(0);
16766   if (NegC)
16767     C = C.getOperand(0);
16768
16769   unsigned Opcode;
16770   if (!NegMul)
16771     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16772   else
16773     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16774
16775   return DAG.getNode(Opcode, dl, VT, A, B, C);
16776 }
16777
16778 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16779                                   TargetLowering::DAGCombinerInfo &DCI,
16780                                   const X86Subtarget *Subtarget) {
16781   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
16782   //           (and (i32 x86isd::setcc_carry), 1)
16783   // This eliminates the zext. This transformation is necessary because
16784   // ISD::SETCC is always legalized to i8.
16785   DebugLoc dl = N->getDebugLoc();
16786   SDValue N0 = N->getOperand(0);
16787   EVT VT = N->getValueType(0);
16788   EVT OpVT = N0.getValueType();
16789
16790   if (N0.getOpcode() == ISD::AND &&
16791       N0.hasOneUse() &&
16792       N0.getOperand(0).hasOneUse()) {
16793     SDValue N00 = N0.getOperand(0);
16794     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16795       return SDValue();
16796     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16797     if (!C || C->getZExtValue() != 1)
16798       return SDValue();
16799     return DAG.getNode(ISD::AND, dl, VT,
16800                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16801                                    N00.getOperand(0), N00.getOperand(1)),
16802                        DAG.getConstant(1, VT));
16803   }
16804
16805   // Optimize vectors in AVX mode:
16806   //
16807   //   v8i16 -> v8i32
16808   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
16809   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
16810   //   Concat upper and lower parts.
16811   //
16812   //   v4i32 -> v4i64
16813   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
16814   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
16815   //   Concat upper and lower parts.
16816   //
16817   if (!DCI.isBeforeLegalizeOps())
16818     return SDValue();
16819
16820   if (!Subtarget->hasFp256())
16821     return SDValue();
16822
16823   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16824       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
16825
16826     if (Subtarget->hasInt256())
16827       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16828
16829     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16830     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16831     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16832
16833     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16834                                VT.getVectorNumElements()/2);
16835
16836     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16837     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16838
16839     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16840   }
16841
16842   return SDValue();
16843 }
16844
16845 // Optimize x == -y --> x+y == 0
16846 //          x != -y --> x+y != 0
16847 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16848   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16849   SDValue LHS = N->getOperand(0);
16850   SDValue RHS = N->getOperand(1);
16851
16852   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16853     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16854       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16855         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16856                                    LHS.getValueType(), RHS, LHS.getOperand(1));
16857         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16858                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16859       }
16860   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16861     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16862       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16863         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16864                                    RHS.getValueType(), LHS, RHS.getOperand(1));
16865         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16866                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16867       }
16868   return SDValue();
16869 }
16870
16871 // Helper function of PerformSETCCCombine. It is to materialize "setb reg" 
16872 // as "sbb reg,reg", since it can be extended without zext and produces 
16873 // an all-ones bit which is more useful than 0/1 in some cases.
16874 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
16875   return DAG.getNode(ISD::AND, DL, MVT::i8,
16876                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16877                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
16878                      DAG.getConstant(1, MVT::i8));
16879 }
16880
16881 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16882 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16883                                    TargetLowering::DAGCombinerInfo &DCI,
16884                                    const X86Subtarget *Subtarget) {
16885   DebugLoc DL = N->getDebugLoc();
16886   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16887   SDValue EFLAGS = N->getOperand(1);
16888
16889   if (CC == X86::COND_A) {
16890     // Try to convert COND_A into COND_B in an attempt to facilitate 
16891     // materializing "setb reg".
16892     //
16893     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
16894     // cannot take an immediate as its first operand.
16895     //
16896     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() && 
16897         EFLAGS.getValueType().isInteger() &&
16898         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
16899       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
16900                                    EFLAGS.getNode()->getVTList(),
16901                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
16902       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
16903       return MaterializeSETB(DL, NewEFLAGS, DAG);
16904     }
16905   }
16906
16907   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16908   // a zext and produces an all-ones bit which is more useful than 0/1 in some
16909   // cases.
16910   if (CC == X86::COND_B)
16911     return MaterializeSETB(DL, EFLAGS, DAG);
16912
16913   SDValue Flags;
16914
16915   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16916   if (Flags.getNode()) {
16917     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16918     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16919   }
16920
16921   return SDValue();
16922 }
16923
16924 // Optimize branch condition evaluation.
16925 //
16926 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16927                                     TargetLowering::DAGCombinerInfo &DCI,
16928                                     const X86Subtarget *Subtarget) {
16929   DebugLoc DL = N->getDebugLoc();
16930   SDValue Chain = N->getOperand(0);
16931   SDValue Dest = N->getOperand(1);
16932   SDValue EFLAGS = N->getOperand(3);
16933   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16934
16935   SDValue Flags;
16936
16937   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16938   if (Flags.getNode()) {
16939     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16940     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16941                        Flags);
16942   }
16943
16944   return SDValue();
16945 }
16946
16947 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16948                                         const X86TargetLowering *XTLI) {
16949   SDValue Op0 = N->getOperand(0);
16950   EVT InVT = Op0->getValueType(0);
16951
16952   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16953   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16954     DebugLoc dl = N->getDebugLoc();
16955     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16956     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16957     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16958   }
16959
16960   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16961   // a 32-bit target where SSE doesn't support i64->FP operations.
16962   if (Op0.getOpcode() == ISD::LOAD) {
16963     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16964     EVT VT = Ld->getValueType(0);
16965     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16966         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16967         !XTLI->getSubtarget()->is64Bit() &&
16968         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16969       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16970                                           Ld->getChain(), Op0, DAG);
16971       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16972       return FILDChain;
16973     }
16974   }
16975   return SDValue();
16976 }
16977
16978 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16979 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16980                                  X86TargetLowering::DAGCombinerInfo &DCI) {
16981   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16982   // the result is either zero or one (depending on the input carry bit).
16983   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16984   if (X86::isZeroNode(N->getOperand(0)) &&
16985       X86::isZeroNode(N->getOperand(1)) &&
16986       // We don't have a good way to replace an EFLAGS use, so only do this when
16987       // dead right now.
16988       SDValue(N, 1).use_empty()) {
16989     DebugLoc DL = N->getDebugLoc();
16990     EVT VT = N->getValueType(0);
16991     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16992     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16993                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16994                                            DAG.getConstant(X86::COND_B,MVT::i8),
16995                                            N->getOperand(2)),
16996                                DAG.getConstant(1, VT));
16997     return DCI.CombineTo(N, Res1, CarryOut);
16998   }
16999
17000   return SDValue();
17001 }
17002
17003 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17004 //      (add Y, (setne X, 0)) -> sbb -1, Y
17005 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17006 //      (sub (setne X, 0), Y) -> adc -1, Y
17007 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17008   DebugLoc DL = N->getDebugLoc();
17009
17010   // Look through ZExts.
17011   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17012   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17013     return SDValue();
17014
17015   SDValue SetCC = Ext.getOperand(0);
17016   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17017     return SDValue();
17018
17019   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17020   if (CC != X86::COND_E && CC != X86::COND_NE)
17021     return SDValue();
17022
17023   SDValue Cmp = SetCC.getOperand(1);
17024   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17025       !X86::isZeroNode(Cmp.getOperand(1)) ||
17026       !Cmp.getOperand(0).getValueType().isInteger())
17027     return SDValue();
17028
17029   SDValue CmpOp0 = Cmp.getOperand(0);
17030   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17031                                DAG.getConstant(1, CmpOp0.getValueType()));
17032
17033   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17034   if (CC == X86::COND_NE)
17035     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17036                        DL, OtherVal.getValueType(), OtherVal,
17037                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17038   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17039                      DL, OtherVal.getValueType(), OtherVal,
17040                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17041 }
17042
17043 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17044 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17045                                  const X86Subtarget *Subtarget) {
17046   EVT VT = N->getValueType(0);
17047   SDValue Op0 = N->getOperand(0);
17048   SDValue Op1 = N->getOperand(1);
17049
17050   // Try to synthesize horizontal adds from adds of shuffles.
17051   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17052        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17053       isHorizontalBinOp(Op0, Op1, true))
17054     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17055
17056   return OptimizeConditionalInDecrement(N, DAG);
17057 }
17058
17059 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17060                                  const X86Subtarget *Subtarget) {
17061   SDValue Op0 = N->getOperand(0);
17062   SDValue Op1 = N->getOperand(1);
17063
17064   // X86 can't encode an immediate LHS of a sub. See if we can push the
17065   // negation into a preceding instruction.
17066   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17067     // If the RHS of the sub is a XOR with one use and a constant, invert the
17068     // immediate. Then add one to the LHS of the sub so we can turn
17069     // X-Y -> X+~Y+1, saving one register.
17070     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17071         isa<ConstantSDNode>(Op1.getOperand(1))) {
17072       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17073       EVT VT = Op0.getValueType();
17074       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17075                                    Op1.getOperand(0),
17076                                    DAG.getConstant(~XorC, VT));
17077       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17078                          DAG.getConstant(C->getAPIntValue()+1, VT));
17079     }
17080   }
17081
17082   // Try to synthesize horizontal adds from adds of shuffles.
17083   EVT VT = N->getValueType(0);
17084   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17085        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17086       isHorizontalBinOp(Op0, Op1, true))
17087     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17088
17089   return OptimizeConditionalInDecrement(N, DAG);
17090 }
17091
17092 /// performVZEXTCombine - Performs build vector combines
17093 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17094                                         TargetLowering::DAGCombinerInfo &DCI,
17095                                         const X86Subtarget *Subtarget) {
17096   // (vzext (bitcast (vzext (x)) -> (vzext x)
17097   SDValue In = N->getOperand(0);
17098   while (In.getOpcode() == ISD::BITCAST)
17099     In = In.getOperand(0);
17100
17101   if (In.getOpcode() != X86ISD::VZEXT)
17102     return SDValue();
17103
17104   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
17105 }
17106
17107 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17108                                              DAGCombinerInfo &DCI) const {
17109   SelectionDAG &DAG = DCI.DAG;
17110   switch (N->getOpcode()) {
17111   default: break;
17112   case ISD::EXTRACT_VECTOR_ELT:
17113     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17114   case ISD::VSELECT:
17115   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17116   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17117   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17118   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17119   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17120   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17121   case ISD::SHL:
17122   case ISD::SRA:
17123   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17124   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17125   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17126   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17127   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17128   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17129   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17130   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17131   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17132   case X86ISD::FXOR:
17133   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17134   case X86ISD::FMIN:
17135   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17136   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17137   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17138   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17139   case ISD::ANY_EXTEND:
17140   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17141   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17142   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17143   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17144   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17145   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17146   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17147   case X86ISD::SHUFP:       // Handle all target specific shuffles
17148   case X86ISD::PALIGN:
17149   case X86ISD::UNPCKH:
17150   case X86ISD::UNPCKL:
17151   case X86ISD::MOVHLPS:
17152   case X86ISD::MOVLHPS:
17153   case X86ISD::PSHUFD:
17154   case X86ISD::PSHUFHW:
17155   case X86ISD::PSHUFLW:
17156   case X86ISD::MOVSS:
17157   case X86ISD::MOVSD:
17158   case X86ISD::VPERMILP:
17159   case X86ISD::VPERM2X128:
17160   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17161   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17162   }
17163
17164   return SDValue();
17165 }
17166
17167 /// isTypeDesirableForOp - Return true if the target has native support for
17168 /// the specified value type and it is 'desirable' to use the type for the
17169 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17170 /// instruction encodings are longer and some i16 instructions are slow.
17171 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17172   if (!isTypeLegal(VT))
17173     return false;
17174   if (VT != MVT::i16)
17175     return true;
17176
17177   switch (Opc) {
17178   default:
17179     return true;
17180   case ISD::LOAD:
17181   case ISD::SIGN_EXTEND:
17182   case ISD::ZERO_EXTEND:
17183   case ISD::ANY_EXTEND:
17184   case ISD::SHL:
17185   case ISD::SRL:
17186   case ISD::SUB:
17187   case ISD::ADD:
17188   case ISD::MUL:
17189   case ISD::AND:
17190   case ISD::OR:
17191   case ISD::XOR:
17192     return false;
17193   }
17194 }
17195
17196 /// IsDesirableToPromoteOp - This method query the target whether it is
17197 /// beneficial for dag combiner to promote the specified node. If true, it
17198 /// should return the desired promotion type by reference.
17199 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17200   EVT VT = Op.getValueType();
17201   if (VT != MVT::i16)
17202     return false;
17203
17204   bool Promote = false;
17205   bool Commute = false;
17206   switch (Op.getOpcode()) {
17207   default: break;
17208   case ISD::LOAD: {
17209     LoadSDNode *LD = cast<LoadSDNode>(Op);
17210     // If the non-extending load has a single use and it's not live out, then it
17211     // might be folded.
17212     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17213                                                      Op.hasOneUse()*/) {
17214       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17215              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17216         // The only case where we'd want to promote LOAD (rather then it being
17217         // promoted as an operand is when it's only use is liveout.
17218         if (UI->getOpcode() != ISD::CopyToReg)
17219           return false;
17220       }
17221     }
17222     Promote = true;
17223     break;
17224   }
17225   case ISD::SIGN_EXTEND:
17226   case ISD::ZERO_EXTEND:
17227   case ISD::ANY_EXTEND:
17228     Promote = true;
17229     break;
17230   case ISD::SHL:
17231   case ISD::SRL: {
17232     SDValue N0 = Op.getOperand(0);
17233     // Look out for (store (shl (load), x)).
17234     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17235       return false;
17236     Promote = true;
17237     break;
17238   }
17239   case ISD::ADD:
17240   case ISD::MUL:
17241   case ISD::AND:
17242   case ISD::OR:
17243   case ISD::XOR:
17244     Commute = true;
17245     // fallthrough
17246   case ISD::SUB: {
17247     SDValue N0 = Op.getOperand(0);
17248     SDValue N1 = Op.getOperand(1);
17249     if (!Commute && MayFoldLoad(N1))
17250       return false;
17251     // Avoid disabling potential load folding opportunities.
17252     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17253       return false;
17254     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17255       return false;
17256     Promote = true;
17257   }
17258   }
17259
17260   PVT = MVT::i32;
17261   return Promote;
17262 }
17263
17264 //===----------------------------------------------------------------------===//
17265 //                           X86 Inline Assembly Support
17266 //===----------------------------------------------------------------------===//
17267
17268 namespace {
17269   // Helper to match a string separated by whitespace.
17270   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17271     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17272
17273     for (unsigned i = 0, e = args.size(); i != e; ++i) {
17274       StringRef piece(*args[i]);
17275       if (!s.startswith(piece)) // Check if the piece matches.
17276         return false;
17277
17278       s = s.substr(piece.size());
17279       StringRef::size_type pos = s.find_first_not_of(" \t");
17280       if (pos == 0) // We matched a prefix.
17281         return false;
17282
17283       s = s.substr(pos);
17284     }
17285
17286     return s.empty();
17287   }
17288   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17289 }
17290
17291 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17292   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17293
17294   std::string AsmStr = IA->getAsmString();
17295
17296   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17297   if (!Ty || Ty->getBitWidth() % 16 != 0)
17298     return false;
17299
17300   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17301   SmallVector<StringRef, 4> AsmPieces;
17302   SplitString(AsmStr, AsmPieces, ";\n");
17303
17304   switch (AsmPieces.size()) {
17305   default: return false;
17306   case 1:
17307     // FIXME: this should verify that we are targeting a 486 or better.  If not,
17308     // we will turn this bswap into something that will be lowered to logical
17309     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
17310     // lower so don't worry about this.
17311     // bswap $0
17312     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17313         matchAsm(AsmPieces[0], "bswapl", "$0") ||
17314         matchAsm(AsmPieces[0], "bswapq", "$0") ||
17315         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17316         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17317         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17318       // No need to check constraints, nothing other than the equivalent of
17319       // "=r,0" would be valid here.
17320       return IntrinsicLowering::LowerToByteSwap(CI);
17321     }
17322
17323     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
17324     if (CI->getType()->isIntegerTy(16) &&
17325         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17326         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17327          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17328       AsmPieces.clear();
17329       const std::string &ConstraintsStr = IA->getConstraintString();
17330       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17331       std::sort(AsmPieces.begin(), AsmPieces.end());
17332       if (AsmPieces.size() == 4 &&
17333           AsmPieces[0] == "~{cc}" &&
17334           AsmPieces[1] == "~{dirflag}" &&
17335           AsmPieces[2] == "~{flags}" &&
17336           AsmPieces[3] == "~{fpsr}")
17337       return IntrinsicLowering::LowerToByteSwap(CI);
17338     }
17339     break;
17340   case 3:
17341     if (CI->getType()->isIntegerTy(32) &&
17342         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17343         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17344         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17345         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17346       AsmPieces.clear();
17347       const std::string &ConstraintsStr = IA->getConstraintString();
17348       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17349       std::sort(AsmPieces.begin(), AsmPieces.end());
17350       if (AsmPieces.size() == 4 &&
17351           AsmPieces[0] == "~{cc}" &&
17352           AsmPieces[1] == "~{dirflag}" &&
17353           AsmPieces[2] == "~{flags}" &&
17354           AsmPieces[3] == "~{fpsr}")
17355         return IntrinsicLowering::LowerToByteSwap(CI);
17356     }
17357
17358     if (CI->getType()->isIntegerTy(64)) {
17359       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17360       if (Constraints.size() >= 2 &&
17361           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17362           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17363         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
17364         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17365             matchAsm(AsmPieces[1], "bswap", "%edx") &&
17366             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17367           return IntrinsicLowering::LowerToByteSwap(CI);
17368       }
17369     }
17370     break;
17371   }
17372   return false;
17373 }
17374
17375 /// getConstraintType - Given a constraint letter, return the type of
17376 /// constraint it is for this target.
17377 X86TargetLowering::ConstraintType
17378 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17379   if (Constraint.size() == 1) {
17380     switch (Constraint[0]) {
17381     case 'R':
17382     case 'q':
17383     case 'Q':
17384     case 'f':
17385     case 't':
17386     case 'u':
17387     case 'y':
17388     case 'x':
17389     case 'Y':
17390     case 'l':
17391       return C_RegisterClass;
17392     case 'a':
17393     case 'b':
17394     case 'c':
17395     case 'd':
17396     case 'S':
17397     case 'D':
17398     case 'A':
17399       return C_Register;
17400     case 'I':
17401     case 'J':
17402     case 'K':
17403     case 'L':
17404     case 'M':
17405     case 'N':
17406     case 'G':
17407     case 'C':
17408     case 'e':
17409     case 'Z':
17410       return C_Other;
17411     default:
17412       break;
17413     }
17414   }
17415   return TargetLowering::getConstraintType(Constraint);
17416 }
17417
17418 /// Examine constraint type and operand type and determine a weight value.
17419 /// This object must already have been set up with the operand type
17420 /// and the current alternative constraint selected.
17421 TargetLowering::ConstraintWeight
17422   X86TargetLowering::getSingleConstraintMatchWeight(
17423     AsmOperandInfo &info, const char *constraint) const {
17424   ConstraintWeight weight = CW_Invalid;
17425   Value *CallOperandVal = info.CallOperandVal;
17426     // If we don't have a value, we can't do a match,
17427     // but allow it at the lowest weight.
17428   if (CallOperandVal == NULL)
17429     return CW_Default;
17430   Type *type = CallOperandVal->getType();
17431   // Look at the constraint type.
17432   switch (*constraint) {
17433   default:
17434     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17435   case 'R':
17436   case 'q':
17437   case 'Q':
17438   case 'a':
17439   case 'b':
17440   case 'c':
17441   case 'd':
17442   case 'S':
17443   case 'D':
17444   case 'A':
17445     if (CallOperandVal->getType()->isIntegerTy())
17446       weight = CW_SpecificReg;
17447     break;
17448   case 'f':
17449   case 't':
17450   case 'u':
17451       if (type->isFloatingPointTy())
17452         weight = CW_SpecificReg;
17453       break;
17454   case 'y':
17455       if (type->isX86_MMXTy() && Subtarget->hasMMX())
17456         weight = CW_SpecificReg;
17457       break;
17458   case 'x':
17459   case 'Y':
17460     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17461         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17462       weight = CW_Register;
17463     break;
17464   case 'I':
17465     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17466       if (C->getZExtValue() <= 31)
17467         weight = CW_Constant;
17468     }
17469     break;
17470   case 'J':
17471     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17472       if (C->getZExtValue() <= 63)
17473         weight = CW_Constant;
17474     }
17475     break;
17476   case 'K':
17477     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17478       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17479         weight = CW_Constant;
17480     }
17481     break;
17482   case 'L':
17483     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17484       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17485         weight = CW_Constant;
17486     }
17487     break;
17488   case 'M':
17489     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17490       if (C->getZExtValue() <= 3)
17491         weight = CW_Constant;
17492     }
17493     break;
17494   case 'N':
17495     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17496       if (C->getZExtValue() <= 0xff)
17497         weight = CW_Constant;
17498     }
17499     break;
17500   case 'G':
17501   case 'C':
17502     if (dyn_cast<ConstantFP>(CallOperandVal)) {
17503       weight = CW_Constant;
17504     }
17505     break;
17506   case 'e':
17507     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17508       if ((C->getSExtValue() >= -0x80000000LL) &&
17509           (C->getSExtValue() <= 0x7fffffffLL))
17510         weight = CW_Constant;
17511     }
17512     break;
17513   case 'Z':
17514     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17515       if (C->getZExtValue() <= 0xffffffff)
17516         weight = CW_Constant;
17517     }
17518     break;
17519   }
17520   return weight;
17521 }
17522
17523 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17524 /// with another that has more specific requirements based on the type of the
17525 /// corresponding operand.
17526 const char *X86TargetLowering::
17527 LowerXConstraint(EVT ConstraintVT) const {
17528   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17529   // 'f' like normal targets.
17530   if (ConstraintVT.isFloatingPoint()) {
17531     if (Subtarget->hasSSE2())
17532       return "Y";
17533     if (Subtarget->hasSSE1())
17534       return "x";
17535   }
17536
17537   return TargetLowering::LowerXConstraint(ConstraintVT);
17538 }
17539
17540 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17541 /// vector.  If it is invalid, don't add anything to Ops.
17542 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17543                                                      std::string &Constraint,
17544                                                      std::vector<SDValue>&Ops,
17545                                                      SelectionDAG &DAG) const {
17546   SDValue Result(0, 0);
17547
17548   // Only support length 1 constraints for now.
17549   if (Constraint.length() > 1) return;
17550
17551   char ConstraintLetter = Constraint[0];
17552   switch (ConstraintLetter) {
17553   default: break;
17554   case 'I':
17555     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17556       if (C->getZExtValue() <= 31) {
17557         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17558         break;
17559       }
17560     }
17561     return;
17562   case 'J':
17563     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17564       if (C->getZExtValue() <= 63) {
17565         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17566         break;
17567       }
17568     }
17569     return;
17570   case 'K':
17571     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17572       if (isInt<8>(C->getSExtValue())) {
17573         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17574         break;
17575       }
17576     }
17577     return;
17578   case 'N':
17579     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17580       if (C->getZExtValue() <= 255) {
17581         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17582         break;
17583       }
17584     }
17585     return;
17586   case 'e': {
17587     // 32-bit signed value
17588     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17589       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17590                                            C->getSExtValue())) {
17591         // Widen to 64 bits here to get it sign extended.
17592         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17593         break;
17594       }
17595     // FIXME gcc accepts some relocatable values here too, but only in certain
17596     // memory models; it's complicated.
17597     }
17598     return;
17599   }
17600   case 'Z': {
17601     // 32-bit unsigned value
17602     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17603       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17604                                            C->getZExtValue())) {
17605         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17606         break;
17607       }
17608     }
17609     // FIXME gcc accepts some relocatable values here too, but only in certain
17610     // memory models; it's complicated.
17611     return;
17612   }
17613   case 'i': {
17614     // Literal immediates are always ok.
17615     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17616       // Widen to 64 bits here to get it sign extended.
17617       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17618       break;
17619     }
17620
17621     // In any sort of PIC mode addresses need to be computed at runtime by
17622     // adding in a register or some sort of table lookup.  These can't
17623     // be used as immediates.
17624     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17625       return;
17626
17627     // If we are in non-pic codegen mode, we allow the address of a global (with
17628     // an optional displacement) to be used with 'i'.
17629     GlobalAddressSDNode *GA = 0;
17630     int64_t Offset = 0;
17631
17632     // Match either (GA), (GA+C), (GA+C1+C2), etc.
17633     while (1) {
17634       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17635         Offset += GA->getOffset();
17636         break;
17637       } else if (Op.getOpcode() == ISD::ADD) {
17638         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17639           Offset += C->getZExtValue();
17640           Op = Op.getOperand(0);
17641           continue;
17642         }
17643       } else if (Op.getOpcode() == ISD::SUB) {
17644         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17645           Offset += -C->getZExtValue();
17646           Op = Op.getOperand(0);
17647           continue;
17648         }
17649       }
17650
17651       // Otherwise, this isn't something we can handle, reject it.
17652       return;
17653     }
17654
17655     const GlobalValue *GV = GA->getGlobal();
17656     // If we require an extra load to get this address, as in PIC mode, we
17657     // can't accept it.
17658     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17659                                                         getTargetMachine())))
17660       return;
17661
17662     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17663                                         GA->getValueType(0), Offset);
17664     break;
17665   }
17666   }
17667
17668   if (Result.getNode()) {
17669     Ops.push_back(Result);
17670     return;
17671   }
17672   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17673 }
17674
17675 std::pair<unsigned, const TargetRegisterClass*>
17676 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17677                                                 EVT VT) const {
17678   // First, see if this is a constraint that directly corresponds to an LLVM
17679   // register class.
17680   if (Constraint.size() == 1) {
17681     // GCC Constraint Letters
17682     switch (Constraint[0]) {
17683     default: break;
17684       // TODO: Slight differences here in allocation order and leaving
17685       // RIP in the class. Do they matter any more here than they do
17686       // in the normal allocation?
17687     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17688       if (Subtarget->is64Bit()) {
17689         if (VT == MVT::i32 || VT == MVT::f32)
17690           return std::make_pair(0U, &X86::GR32RegClass);
17691         if (VT == MVT::i16)
17692           return std::make_pair(0U, &X86::GR16RegClass);
17693         if (VT == MVT::i8 || VT == MVT::i1)
17694           return std::make_pair(0U, &X86::GR8RegClass);
17695         if (VT == MVT::i64 || VT == MVT::f64)
17696           return std::make_pair(0U, &X86::GR64RegClass);
17697         break;
17698       }
17699       // 32-bit fallthrough
17700     case 'Q':   // Q_REGS
17701       if (VT == MVT::i32 || VT == MVT::f32)
17702         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17703       if (VT == MVT::i16)
17704         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17705       if (VT == MVT::i8 || VT == MVT::i1)
17706         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17707       if (VT == MVT::i64)
17708         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17709       break;
17710     case 'r':   // GENERAL_REGS
17711     case 'l':   // INDEX_REGS
17712       if (VT == MVT::i8 || VT == MVT::i1)
17713         return std::make_pair(0U, &X86::GR8RegClass);
17714       if (VT == MVT::i16)
17715         return std::make_pair(0U, &X86::GR16RegClass);
17716       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17717         return std::make_pair(0U, &X86::GR32RegClass);
17718       return std::make_pair(0U, &X86::GR64RegClass);
17719     case 'R':   // LEGACY_REGS
17720       if (VT == MVT::i8 || VT == MVT::i1)
17721         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17722       if (VT == MVT::i16)
17723         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17724       if (VT == MVT::i32 || !Subtarget->is64Bit())
17725         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17726       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17727     case 'f':  // FP Stack registers.
17728       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17729       // value to the correct fpstack register class.
17730       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17731         return std::make_pair(0U, &X86::RFP32RegClass);
17732       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17733         return std::make_pair(0U, &X86::RFP64RegClass);
17734       return std::make_pair(0U, &X86::RFP80RegClass);
17735     case 'y':   // MMX_REGS if MMX allowed.
17736       if (!Subtarget->hasMMX()) break;
17737       return std::make_pair(0U, &X86::VR64RegClass);
17738     case 'Y':   // SSE_REGS if SSE2 allowed
17739       if (!Subtarget->hasSSE2()) break;
17740       // FALL THROUGH.
17741     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17742       if (!Subtarget->hasSSE1()) break;
17743
17744       switch (VT.getSimpleVT().SimpleTy) {
17745       default: break;
17746       // Scalar SSE types.
17747       case MVT::f32:
17748       case MVT::i32:
17749         return std::make_pair(0U, &X86::FR32RegClass);
17750       case MVT::f64:
17751       case MVT::i64:
17752         return std::make_pair(0U, &X86::FR64RegClass);
17753       // Vector types.
17754       case MVT::v16i8:
17755       case MVT::v8i16:
17756       case MVT::v4i32:
17757       case MVT::v2i64:
17758       case MVT::v4f32:
17759       case MVT::v2f64:
17760         return std::make_pair(0U, &X86::VR128RegClass);
17761       // AVX types.
17762       case MVT::v32i8:
17763       case MVT::v16i16:
17764       case MVT::v8i32:
17765       case MVT::v4i64:
17766       case MVT::v8f32:
17767       case MVT::v4f64:
17768         return std::make_pair(0U, &X86::VR256RegClass);
17769       }
17770       break;
17771     }
17772   }
17773
17774   // Use the default implementation in TargetLowering to convert the register
17775   // constraint into a member of a register class.
17776   std::pair<unsigned, const TargetRegisterClass*> Res;
17777   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17778
17779   // Not found as a standard register?
17780   if (Res.second == 0) {
17781     // Map st(0) -> st(7) -> ST0
17782     if (Constraint.size() == 7 && Constraint[0] == '{' &&
17783         tolower(Constraint[1]) == 's' &&
17784         tolower(Constraint[2]) == 't' &&
17785         Constraint[3] == '(' &&
17786         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17787         Constraint[5] == ')' &&
17788         Constraint[6] == '}') {
17789
17790       Res.first = X86::ST0+Constraint[4]-'0';
17791       Res.second = &X86::RFP80RegClass;
17792       return Res;
17793     }
17794
17795     // GCC allows "st(0)" to be called just plain "st".
17796     if (StringRef("{st}").equals_lower(Constraint)) {
17797       Res.first = X86::ST0;
17798       Res.second = &X86::RFP80RegClass;
17799       return Res;
17800     }
17801
17802     // flags -> EFLAGS
17803     if (StringRef("{flags}").equals_lower(Constraint)) {
17804       Res.first = X86::EFLAGS;
17805       Res.second = &X86::CCRRegClass;
17806       return Res;
17807     }
17808
17809     // 'A' means EAX + EDX.
17810     if (Constraint == "A") {
17811       Res.first = X86::EAX;
17812       Res.second = &X86::GR32_ADRegClass;
17813       return Res;
17814     }
17815     return Res;
17816   }
17817
17818   // Otherwise, check to see if this is a register class of the wrong value
17819   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17820   // turn into {ax},{dx}.
17821   if (Res.second->hasType(VT))
17822     return Res;   // Correct type already, nothing to do.
17823
17824   // All of the single-register GCC register classes map their values onto
17825   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
17826   // really want an 8-bit or 32-bit register, map to the appropriate register
17827   // class and return the appropriate register.
17828   if (Res.second == &X86::GR16RegClass) {
17829     if (VT == MVT::i8) {
17830       unsigned DestReg = 0;
17831       switch (Res.first) {
17832       default: break;
17833       case X86::AX: DestReg = X86::AL; break;
17834       case X86::DX: DestReg = X86::DL; break;
17835       case X86::CX: DestReg = X86::CL; break;
17836       case X86::BX: DestReg = X86::BL; break;
17837       }
17838       if (DestReg) {
17839         Res.first = DestReg;
17840         Res.second = &X86::GR8RegClass;
17841       }
17842     } else if (VT == MVT::i32) {
17843       unsigned DestReg = 0;
17844       switch (Res.first) {
17845       default: break;
17846       case X86::AX: DestReg = X86::EAX; break;
17847       case X86::DX: DestReg = X86::EDX; break;
17848       case X86::CX: DestReg = X86::ECX; break;
17849       case X86::BX: DestReg = X86::EBX; break;
17850       case X86::SI: DestReg = X86::ESI; break;
17851       case X86::DI: DestReg = X86::EDI; break;
17852       case X86::BP: DestReg = X86::EBP; break;
17853       case X86::SP: DestReg = X86::ESP; break;
17854       }
17855       if (DestReg) {
17856         Res.first = DestReg;
17857         Res.second = &X86::GR32RegClass;
17858       }
17859     } else if (VT == MVT::i64) {
17860       unsigned DestReg = 0;
17861       switch (Res.first) {
17862       default: break;
17863       case X86::AX: DestReg = X86::RAX; break;
17864       case X86::DX: DestReg = X86::RDX; break;
17865       case X86::CX: DestReg = X86::RCX; break;
17866       case X86::BX: DestReg = X86::RBX; break;
17867       case X86::SI: DestReg = X86::RSI; break;
17868       case X86::DI: DestReg = X86::RDI; break;
17869       case X86::BP: DestReg = X86::RBP; break;
17870       case X86::SP: DestReg = X86::RSP; break;
17871       }
17872       if (DestReg) {
17873         Res.first = DestReg;
17874         Res.second = &X86::GR64RegClass;
17875       }
17876     }
17877   } else if (Res.second == &X86::FR32RegClass ||
17878              Res.second == &X86::FR64RegClass ||
17879              Res.second == &X86::VR128RegClass) {
17880     // Handle references to XMM physical registers that got mapped into the
17881     // wrong class.  This can happen with constraints like {xmm0} where the
17882     // target independent register mapper will just pick the first match it can
17883     // find, ignoring the required type.
17884
17885     if (VT == MVT::f32 || VT == MVT::i32)
17886       Res.second = &X86::FR32RegClass;
17887     else if (VT == MVT::f64 || VT == MVT::i64)
17888       Res.second = &X86::FR64RegClass;
17889     else if (X86::VR128RegClass.hasType(VT))
17890       Res.second = &X86::VR128RegClass;
17891     else if (X86::VR256RegClass.hasType(VT))
17892       Res.second = &X86::VR256RegClass;
17893   }
17894
17895   return Res;
17896 }
17897
17898 //===----------------------------------------------------------------------===//
17899 //
17900 // X86 cost model.
17901 //
17902 //===----------------------------------------------------------------------===//
17903
17904 struct X86CostTblEntry {
17905   int ISD;
17906   MVT Type;
17907   unsigned Cost;
17908 };
17909
17910 static int
17911 FindInTable(const X86CostTblEntry *Tbl, unsigned len, int ISD, MVT Ty) {
17912   for (unsigned int i = 0; i < len; ++i)
17913     if (Tbl[i].ISD == ISD && Tbl[i].Type == Ty)
17914       return i;
17915
17916   // Could not find an entry.
17917   return -1;
17918 }
17919
17920 struct X86TypeConversionCostTblEntry {
17921   int ISD;
17922   MVT Dst;
17923   MVT Src;
17924   unsigned Cost;
17925 };
17926
17927 static int
17928 FindInConvertTable(const X86TypeConversionCostTblEntry *Tbl, unsigned len,
17929                    int ISD, MVT Dst, MVT Src) {
17930   for (unsigned int i = 0; i < len; ++i)
17931     if (Tbl[i].ISD == ISD && Tbl[i].Src == Src && Tbl[i].Dst == Dst)
17932       return i;
17933
17934   // Could not find an entry.
17935   return -1;
17936 }
17937
17938 ScalarTargetTransformInfo::PopcntHwSupport
17939 X86ScalarTargetTransformImpl::getPopcntHwSupport(unsigned TyWidth) const {
17940   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
17941   const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17942
17943   // TODO: Currently the __builtin_popcount() implementation using SSE3
17944   //   instructions is inefficient. Once the problem is fixed, we should
17945   //   call ST.hasSSE3() instead of ST.hasSSE4().
17946   return ST.hasSSE41() ? Fast : None;
17947 }
17948
17949 unsigned
17950 X86VectorTargetTransformInfo::getArithmeticInstrCost(unsigned Opcode,
17951                                                      Type *Ty) const {
17952   // Legalize the type.
17953   std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Ty);
17954
17955   int ISD = InstructionOpcodeToISD(Opcode);
17956   assert(ISD && "Invalid opcode");
17957
17958   const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17959
17960   static const X86CostTblEntry AVX1CostTable[] = {
17961     // We don't have to scalarize unsupported ops. We can issue two half-sized
17962     // operations and we only need to extract the upper YMM half.
17963     // Two ops + 1 extract + 1 insert = 4.
17964     { ISD::MUL,     MVT::v8i32,    4 },
17965     { ISD::SUB,     MVT::v8i32,    4 },
17966     { ISD::ADD,     MVT::v8i32,    4 },
17967     { ISD::MUL,     MVT::v4i64,    4 },
17968     { ISD::SUB,     MVT::v4i64,    4 },
17969     { ISD::ADD,     MVT::v4i64,    4 },
17970     };
17971
17972   // Look for AVX1 lowering tricks.
17973   if (ST.hasAVX()) {
17974     int Idx = FindInTable(AVX1CostTable, array_lengthof(AVX1CostTable), ISD,
17975                           LT.second);
17976     if (Idx != -1)
17977       return LT.first * AVX1CostTable[Idx].Cost;
17978   }
17979   // Fallback to the default implementation.
17980   return VectorTargetTransformImpl::getArithmeticInstrCost(Opcode, Ty);
17981 }
17982
17983 unsigned
17984 X86VectorTargetTransformInfo::getMemoryOpCost(unsigned Opcode, Type *Src,
17985                                               unsigned Alignment,
17986                                               unsigned AddressSpace) const {
17987   // Legalize the type.
17988   std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Src);
17989   assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
17990          "Invalid Opcode");
17991
17992   const X86Subtarget &ST =
17993   TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17994
17995   // Each load/store unit costs 1.
17996   unsigned Cost = LT.first * 1;
17997
17998   // On Sandybridge 256bit load/stores are double pumped
17999   // (but not on Haswell).
18000   if (LT.second.getSizeInBits() > 128 && !ST.hasAVX2())
18001     Cost*=2;
18002
18003   return Cost;
18004 }
18005
18006 unsigned
18007 X86VectorTargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val,
18008                                                  unsigned Index) const {
18009   assert(Val->isVectorTy() && "This must be a vector type");
18010
18011   if (Index != -1U) {
18012     // Legalize the type.
18013     std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Val);
18014
18015     // This type is legalized to a scalar type.
18016     if (!LT.second.isVector())
18017       return 0;
18018
18019     // The type may be split. Normalize the index to the new type.
18020     unsigned Width = LT.second.getVectorNumElements();
18021     Index = Index % Width;
18022
18023     // Floating point scalars are already located in index #0.
18024     if (Val->getScalarType()->isFloatingPointTy() && Index == 0)
18025       return 0;
18026   }
18027
18028   return VectorTargetTransformImpl::getVectorInstrCost(Opcode, Val, Index);
18029 }
18030
18031 unsigned X86VectorTargetTransformInfo::getCmpSelInstrCost(unsigned Opcode,
18032                                                           Type *ValTy,
18033                                                           Type *CondTy) const {
18034   // Legalize the type.
18035   std::pair<unsigned, MVT> LT = getTypeLegalizationCost(ValTy);
18036
18037   MVT MTy = LT.second;
18038
18039   int ISD = InstructionOpcodeToISD(Opcode);
18040   assert(ISD && "Invalid opcode");
18041
18042   const X86Subtarget &ST =
18043   TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18044
18045   static const X86CostTblEntry SSE42CostTbl[] = {
18046     { ISD::SETCC,   MVT::v2f64,   1 },
18047     { ISD::SETCC,   MVT::v4f32,   1 },
18048     { ISD::SETCC,   MVT::v2i64,   1 },
18049     { ISD::SETCC,   MVT::v4i32,   1 },
18050     { ISD::SETCC,   MVT::v8i16,   1 },
18051     { ISD::SETCC,   MVT::v16i8,   1 },
18052   };
18053
18054   static const X86CostTblEntry AVX1CostTbl[] = {
18055     { ISD::SETCC,   MVT::v4f64,   1 },
18056     { ISD::SETCC,   MVT::v8f32,   1 },
18057     // AVX1 does not support 8-wide integer compare.
18058     { ISD::SETCC,   MVT::v4i64,   4 },
18059     { ISD::SETCC,   MVT::v8i32,   4 },
18060     { ISD::SETCC,   MVT::v16i16,  4 },
18061     { ISD::SETCC,   MVT::v32i8,   4 },
18062   };
18063
18064   static const X86CostTblEntry AVX2CostTbl[] = {
18065     { ISD::SETCC,   MVT::v4i64,   1 },
18066     { ISD::SETCC,   MVT::v8i32,   1 },
18067     { ISD::SETCC,   MVT::v16i16,  1 },
18068     { ISD::SETCC,   MVT::v32i8,   1 },
18069   };
18070
18071   if (ST.hasAVX2()) {
18072     int Idx = FindInTable(AVX2CostTbl, array_lengthof(AVX2CostTbl), ISD, MTy);
18073     if (Idx != -1)
18074       return LT.first * AVX2CostTbl[Idx].Cost;
18075   }
18076
18077   if (ST.hasAVX()) {
18078     int Idx = FindInTable(AVX1CostTbl, array_lengthof(AVX1CostTbl), ISD, MTy);
18079     if (Idx != -1)
18080       return LT.first * AVX1CostTbl[Idx].Cost;
18081   }
18082
18083   if (ST.hasSSE42()) {
18084     int Idx = FindInTable(SSE42CostTbl, array_lengthof(SSE42CostTbl), ISD, MTy);
18085     if (Idx != -1)
18086       return LT.first * SSE42CostTbl[Idx].Cost;
18087   }
18088
18089   return VectorTargetTransformImpl::getCmpSelInstrCost(Opcode, ValTy, CondTy);
18090 }
18091
18092 unsigned X86VectorTargetTransformInfo::getCastInstrCost(unsigned Opcode,
18093                                                         Type *Dst,
18094                                                         Type *Src) const {
18095   int ISD = InstructionOpcodeToISD(Opcode);
18096   assert(ISD && "Invalid opcode");
18097
18098   EVT SrcTy = TLI->getValueType(Src);
18099   EVT DstTy = TLI->getValueType(Dst);
18100
18101   if (!SrcTy.isSimple() || !DstTy.isSimple())
18102     return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);
18103
18104   const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18105
18106   static const X86TypeConversionCostTblEntry AVXConversionTbl[] = {
18107     { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
18108     { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
18109     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
18110     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
18111     { ISD::TRUNCATE,    MVT::v4i32, MVT::v4i64, 1 },
18112     { ISD::TRUNCATE,    MVT::v8i16, MVT::v8i32, 1 },
18113     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i8,  1 },
18114     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i8,  1 },
18115     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i8,  1 },
18116     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i8,  1 },
18117     { ISD::FP_TO_SINT,  MVT::v8i8,  MVT::v8f32, 1 },
18118     { ISD::FP_TO_SINT,  MVT::v4i8,  MVT::v4f32, 1 },
18119     { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i1,  6 },
18120     { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i1,  9 },
18121     { ISD::TRUNCATE,    MVT::v8i32, MVT::v8i64, 3 },
18122   };
18123
18124   if (ST.hasAVX()) {
18125     int Idx = FindInConvertTable(AVXConversionTbl,
18126                                  array_lengthof(AVXConversionTbl),
18127                                  ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT());
18128     if (Idx != -1)
18129       return AVXConversionTbl[Idx].Cost;
18130   }
18131
18132   return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);
18133 }
18134