Fix inconsistent usage of PALIGN and PALIGNR when referring to the same instruction.
[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/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/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     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1051     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1052   }
1053
1054   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1055     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1056     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1057     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1058     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1059     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1060     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1061
1062     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1063     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1064     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1065
1066     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1067     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1068     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1069     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1070     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1071     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1072     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1073     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1074     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1075     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1076     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1077     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1078
1079     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1080     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1081     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1082     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1083     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1084     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1085     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1086     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1087     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1088     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1089     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1090     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1091
1092     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1093     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1094
1095     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1096
1097     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1098     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1099     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1100
1101     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1102     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1103     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1104
1105     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1106
1107     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1108     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1109
1110     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1111     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1112
1113     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1114     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1115
1116     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1117
1118     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1119     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1120     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1121     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1122
1123     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1124     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1125     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1126
1127     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1128     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1129     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1130     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1131
1132     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1133     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1134     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1135     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1136     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1137     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1138
1139     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1140       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1141       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1142       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1143       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1144       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1145       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1146     }
1147
1148     if (Subtarget->hasInt256()) {
1149       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1150       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1151       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1152       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1153
1154       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1155       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1156       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1157       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1158
1159       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1160       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1161       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1162       // Don't lower v32i8 because there is no 128-bit byte mul
1163
1164       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1165
1166       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1167       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1168
1169       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1170       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1171
1172       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1173
1174       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1175     } else {
1176       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1177       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1178       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1179       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1180
1181       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1182       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1183       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1184       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1185
1186       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1187       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1188       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1189       // Don't lower v32i8 because there is no 128-bit byte mul
1190
1191       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1192       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1193
1194       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1195       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1196
1197       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1198     }
1199
1200     // Custom lower several nodes for 256-bit types.
1201     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1202              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1203       MVT VT = (MVT::SimpleValueType)i;
1204
1205       // Extract subvector is special because the value type
1206       // (result) is 128-bit but the source is 256-bit wide.
1207       if (VT.is128BitVector())
1208         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1209
1210       // Do not attempt to custom lower other non-256-bit vectors
1211       if (!VT.is256BitVector())
1212         continue;
1213
1214       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1215       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1216       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1217       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1218       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1219       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1220       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1221     }
1222
1223     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1224     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1225       MVT VT = (MVT::SimpleValueType)i;
1226
1227       // Do not attempt to promote non-256-bit vectors
1228       if (!VT.is256BitVector())
1229         continue;
1230
1231       setOperationAction(ISD::AND,    VT, Promote);
1232       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1233       setOperationAction(ISD::OR,     VT, Promote);
1234       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1235       setOperationAction(ISD::XOR,    VT, Promote);
1236       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1237       setOperationAction(ISD::LOAD,   VT, Promote);
1238       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1239       setOperationAction(ISD::SELECT, VT, Promote);
1240       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1241     }
1242   }
1243
1244   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1245   // of this type with custom code.
1246   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1247            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1248     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1249                        Custom);
1250   }
1251
1252   // We want to custom lower some of our intrinsics.
1253   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1254   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1255
1256   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1257   // handle type legalization for these operations here.
1258   //
1259   // FIXME: We really should do custom legalization for addition and
1260   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1261   // than generic legalization for 64-bit multiplication-with-overflow, though.
1262   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1263     // Add/Sub/Mul with overflow operations are custom lowered.
1264     MVT VT = IntVTs[i];
1265     setOperationAction(ISD::SADDO, VT, Custom);
1266     setOperationAction(ISD::UADDO, VT, Custom);
1267     setOperationAction(ISD::SSUBO, VT, Custom);
1268     setOperationAction(ISD::USUBO, VT, Custom);
1269     setOperationAction(ISD::SMULO, VT, Custom);
1270     setOperationAction(ISD::UMULO, VT, Custom);
1271   }
1272
1273   // There are no 8-bit 3-address imul/mul instructions
1274   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1275   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1276
1277   if (!Subtarget->is64Bit()) {
1278     // These libcalls are not available in 32-bit.
1279     setLibcallName(RTLIB::SHL_I128, 0);
1280     setLibcallName(RTLIB::SRL_I128, 0);
1281     setLibcallName(RTLIB::SRA_I128, 0);
1282   }
1283
1284   // We have target-specific dag combine patterns for the following nodes:
1285   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1286   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1287   setTargetDAGCombine(ISD::VSELECT);
1288   setTargetDAGCombine(ISD::SELECT);
1289   setTargetDAGCombine(ISD::SHL);
1290   setTargetDAGCombine(ISD::SRA);
1291   setTargetDAGCombine(ISD::SRL);
1292   setTargetDAGCombine(ISD::OR);
1293   setTargetDAGCombine(ISD::AND);
1294   setTargetDAGCombine(ISD::ADD);
1295   setTargetDAGCombine(ISD::FADD);
1296   setTargetDAGCombine(ISD::FSUB);
1297   setTargetDAGCombine(ISD::FMA);
1298   setTargetDAGCombine(ISD::SUB);
1299   setTargetDAGCombine(ISD::LOAD);
1300   setTargetDAGCombine(ISD::STORE);
1301   setTargetDAGCombine(ISD::ZERO_EXTEND);
1302   setTargetDAGCombine(ISD::ANY_EXTEND);
1303   setTargetDAGCombine(ISD::SIGN_EXTEND);
1304   setTargetDAGCombine(ISD::TRUNCATE);
1305   setTargetDAGCombine(ISD::SINT_TO_FP);
1306   setTargetDAGCombine(ISD::SETCC);
1307   if (Subtarget->is64Bit())
1308     setTargetDAGCombine(ISD::MUL);
1309   setTargetDAGCombine(ISD::XOR);
1310
1311   computeRegisterProperties();
1312
1313   // On Darwin, -Os means optimize for size without hurting performance,
1314   // do not reduce the limit.
1315   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1316   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1317   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1318   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1319   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1320   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1321   setPrefLoopAlignment(4); // 2^4 bytes.
1322   benefitFromCodePlacementOpt = true;
1323
1324   // Predictable cmov don't hurt on atom because it's in-order.
1325   predictableSelectIsExpensive = !Subtarget->isAtom();
1326
1327   setPrefFunctionAlignment(4); // 2^4 bytes.
1328 }
1329
1330 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1331   if (!VT.isVector()) return MVT::i8;
1332   return VT.changeVectorElementTypeToInteger();
1333 }
1334
1335 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1336 /// the desired ByVal argument alignment.
1337 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1338   if (MaxAlign == 16)
1339     return;
1340   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1341     if (VTy->getBitWidth() == 128)
1342       MaxAlign = 16;
1343   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1344     unsigned EltAlign = 0;
1345     getMaxByValAlign(ATy->getElementType(), EltAlign);
1346     if (EltAlign > MaxAlign)
1347       MaxAlign = EltAlign;
1348   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1349     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1350       unsigned EltAlign = 0;
1351       getMaxByValAlign(STy->getElementType(i), EltAlign);
1352       if (EltAlign > MaxAlign)
1353         MaxAlign = EltAlign;
1354       if (MaxAlign == 16)
1355         break;
1356     }
1357   }
1358 }
1359
1360 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1361 /// function arguments in the caller parameter area. For X86, aggregates
1362 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1363 /// are at 4-byte boundaries.
1364 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1365   if (Subtarget->is64Bit()) {
1366     // Max of 8 and alignment of type.
1367     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1368     if (TyAlign > 8)
1369       return TyAlign;
1370     return 8;
1371   }
1372
1373   unsigned Align = 4;
1374   if (Subtarget->hasSSE1())
1375     getMaxByValAlign(Ty, Align);
1376   return Align;
1377 }
1378
1379 /// getOptimalMemOpType - Returns the target specific optimal type for load
1380 /// and store operations as a result of memset, memcpy, and memmove
1381 /// lowering. If DstAlign is zero that means it's safe to destination
1382 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1383 /// means there isn't a need to check it against alignment requirement,
1384 /// probably because the source does not need to be loaded. If 'IsMemset' is
1385 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1386 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1387 /// source is constant so it does not need to be loaded.
1388 /// It returns EVT::Other if the type should be determined using generic
1389 /// target-independent logic.
1390 EVT
1391 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1392                                        unsigned DstAlign, unsigned SrcAlign,
1393                                        bool IsMemset, bool ZeroMemset,
1394                                        bool MemcpyStrSrc,
1395                                        MachineFunction &MF) const {
1396   const Function *F = MF.getFunction();
1397   if ((!IsMemset || ZeroMemset) &&
1398       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1399                                        Attribute::NoImplicitFloat)) {
1400     if (Size >= 16 &&
1401         (Subtarget->isUnalignedMemAccessFast() ||
1402          ((DstAlign == 0 || DstAlign >= 16) &&
1403           (SrcAlign == 0 || SrcAlign >= 16)))) {
1404       if (Size >= 32) {
1405         if (Subtarget->hasInt256())
1406           return MVT::v8i32;
1407         if (Subtarget->hasFp256())
1408           return MVT::v8f32;
1409       }
1410       if (Subtarget->hasSSE2())
1411         return MVT::v4i32;
1412       if (Subtarget->hasSSE1())
1413         return MVT::v4f32;
1414     } else if (!MemcpyStrSrc && Size >= 8 &&
1415                !Subtarget->is64Bit() &&
1416                Subtarget->hasSSE2()) {
1417       // Do not use f64 to lower memcpy if source is string constant. It's
1418       // better to use i32 to avoid the loads.
1419       return MVT::f64;
1420     }
1421   }
1422   if (Subtarget->is64Bit() && Size >= 8)
1423     return MVT::i64;
1424   return MVT::i32;
1425 }
1426
1427 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1428   if (VT == MVT::f32)
1429     return X86ScalarSSEf32;
1430   else if (VT == MVT::f64)
1431     return X86ScalarSSEf64;
1432   return true;
1433 }
1434
1435 bool
1436 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1437   if (Fast)
1438     *Fast = Subtarget->isUnalignedMemAccessFast();
1439   return true;
1440 }
1441
1442 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1443 /// current function.  The returned value is a member of the
1444 /// MachineJumpTableInfo::JTEntryKind enum.
1445 unsigned X86TargetLowering::getJumpTableEncoding() const {
1446   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1447   // symbol.
1448   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1449       Subtarget->isPICStyleGOT())
1450     return MachineJumpTableInfo::EK_Custom32;
1451
1452   // Otherwise, use the normal jump table encoding heuristics.
1453   return TargetLowering::getJumpTableEncoding();
1454 }
1455
1456 const MCExpr *
1457 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1458                                              const MachineBasicBlock *MBB,
1459                                              unsigned uid,MCContext &Ctx) const{
1460   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1461          Subtarget->isPICStyleGOT());
1462   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1463   // entries.
1464   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1465                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1466 }
1467
1468 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1469 /// jumptable.
1470 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1471                                                     SelectionDAG &DAG) const {
1472   if (!Subtarget->is64Bit())
1473     // This doesn't have DebugLoc associated with it, but is not really the
1474     // same as a Register.
1475     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1476   return Table;
1477 }
1478
1479 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1480 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1481 /// MCExpr.
1482 const MCExpr *X86TargetLowering::
1483 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1484                              MCContext &Ctx) const {
1485   // X86-64 uses RIP relative addressing based on the jump table label.
1486   if (Subtarget->isPICStyleRIPRel())
1487     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1488
1489   // Otherwise, the reference is relative to the PIC base.
1490   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1491 }
1492
1493 // FIXME: Why this routine is here? Move to RegInfo!
1494 std::pair<const TargetRegisterClass*, uint8_t>
1495 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1496   const TargetRegisterClass *RRC = 0;
1497   uint8_t Cost = 1;
1498   switch (VT.SimpleTy) {
1499   default:
1500     return TargetLowering::findRepresentativeClass(VT);
1501   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1502     RRC = Subtarget->is64Bit() ?
1503       (const TargetRegisterClass*)&X86::GR64RegClass :
1504       (const TargetRegisterClass*)&X86::GR32RegClass;
1505     break;
1506   case MVT::x86mmx:
1507     RRC = &X86::VR64RegClass;
1508     break;
1509   case MVT::f32: case MVT::f64:
1510   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1511   case MVT::v4f32: case MVT::v2f64:
1512   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1513   case MVT::v4f64:
1514     RRC = &X86::VR128RegClass;
1515     break;
1516   }
1517   return std::make_pair(RRC, Cost);
1518 }
1519
1520 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1521                                                unsigned &Offset) const {
1522   if (!Subtarget->isTargetLinux())
1523     return false;
1524
1525   if (Subtarget->is64Bit()) {
1526     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1527     Offset = 0x28;
1528     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1529       AddressSpace = 256;
1530     else
1531       AddressSpace = 257;
1532   } else {
1533     // %gs:0x14 on i386
1534     Offset = 0x14;
1535     AddressSpace = 256;
1536   }
1537   return true;
1538 }
1539
1540 //===----------------------------------------------------------------------===//
1541 //               Return Value Calling Convention Implementation
1542 //===----------------------------------------------------------------------===//
1543
1544 #include "X86GenCallingConv.inc"
1545
1546 bool
1547 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1548                                   MachineFunction &MF, bool isVarArg,
1549                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1550                         LLVMContext &Context) const {
1551   SmallVector<CCValAssign, 16> RVLocs;
1552   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1553                  RVLocs, Context);
1554   return CCInfo.CheckReturn(Outs, RetCC_X86);
1555 }
1556
1557 SDValue
1558 X86TargetLowering::LowerReturn(SDValue Chain,
1559                                CallingConv::ID CallConv, bool isVarArg,
1560                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1561                                const SmallVectorImpl<SDValue> &OutVals,
1562                                DebugLoc dl, SelectionDAG &DAG) const {
1563   MachineFunction &MF = DAG.getMachineFunction();
1564   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1565
1566   SmallVector<CCValAssign, 16> RVLocs;
1567   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1568                  RVLocs, *DAG.getContext());
1569   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1570
1571   // Add the regs to the liveout set for the function.
1572   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1573   for (unsigned i = 0; i != RVLocs.size(); ++i)
1574     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1575       MRI.addLiveOut(RVLocs[i].getLocReg());
1576
1577   SDValue Flag;
1578
1579   SmallVector<SDValue, 6> RetOps;
1580   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1581   // Operand #1 = Bytes To Pop
1582   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1583                    MVT::i16));
1584
1585   // Copy the result values into the output registers.
1586   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1587     CCValAssign &VA = RVLocs[i];
1588     assert(VA.isRegLoc() && "Can only return in registers!");
1589     SDValue ValToCopy = OutVals[i];
1590     EVT ValVT = ValToCopy.getValueType();
1591
1592     // Promote values to the appropriate types
1593     if (VA.getLocInfo() == CCValAssign::SExt)
1594       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1595     else if (VA.getLocInfo() == CCValAssign::ZExt)
1596       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1597     else if (VA.getLocInfo() == CCValAssign::AExt)
1598       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1599     else if (VA.getLocInfo() == CCValAssign::BCvt)
1600       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1601
1602     // If this is x86-64, and we disabled SSE, we can't return FP values,
1603     // or SSE or MMX vectors.
1604     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1605          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1606           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1607       report_fatal_error("SSE register return with SSE disabled");
1608     }
1609     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1610     // llvm-gcc has never done it right and no one has noticed, so this
1611     // should be OK for now.
1612     if (ValVT == MVT::f64 &&
1613         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1614       report_fatal_error("SSE2 register return with SSE2 disabled");
1615
1616     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1617     // the RET instruction and handled by the FP Stackifier.
1618     if (VA.getLocReg() == X86::ST0 ||
1619         VA.getLocReg() == X86::ST1) {
1620       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1621       // change the value to the FP stack register class.
1622       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1623         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1624       RetOps.push_back(ValToCopy);
1625       // Don't emit a copytoreg.
1626       continue;
1627     }
1628
1629     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1630     // which is returned in RAX / RDX.
1631     if (Subtarget->is64Bit()) {
1632       if (ValVT == MVT::x86mmx) {
1633         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1634           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1635           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1636                                   ValToCopy);
1637           // If we don't have SSE2 available, convert to v4f32 so the generated
1638           // register is legal.
1639           if (!Subtarget->hasSSE2())
1640             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1641         }
1642       }
1643     }
1644
1645     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1646     Flag = Chain.getValue(1);
1647   }
1648
1649   // The x86-64 ABIs require that for returning structs by value we copy
1650   // the sret argument into %rax/%eax (depending on ABI) for the return.
1651   // We saved the argument into a virtual register in the entry block,
1652   // so now we copy the value out and into %rax/%eax.
1653   if (Subtarget->is64Bit() &&
1654       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1655     MachineFunction &MF = DAG.getMachineFunction();
1656     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1657     unsigned Reg = FuncInfo->getSRetReturnReg();
1658     assert(Reg &&
1659            "SRetReturnReg should have been set in LowerFormalArguments().");
1660     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1661
1662     unsigned RetValReg = Subtarget->isTarget64BitILP32() ? X86::EAX : X86::RAX;
1663     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1664     Flag = Chain.getValue(1);
1665
1666     // RAX/EAX now acts like a return value.
1667     MRI.addLiveOut(RetValReg);
1668   }
1669
1670   RetOps[0] = Chain;  // Update chain.
1671
1672   // Add the flag if we have it.
1673   if (Flag.getNode())
1674     RetOps.push_back(Flag);
1675
1676   return DAG.getNode(X86ISD::RET_FLAG, dl,
1677                      MVT::Other, &RetOps[0], RetOps.size());
1678 }
1679
1680 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1681   if (N->getNumValues() != 1)
1682     return false;
1683   if (!N->hasNUsesOfValue(1, 0))
1684     return false;
1685
1686   SDValue TCChain = Chain;
1687   SDNode *Copy = *N->use_begin();
1688   if (Copy->getOpcode() == ISD::CopyToReg) {
1689     // If the copy has a glue operand, we conservatively assume it isn't safe to
1690     // perform a tail call.
1691     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1692       return false;
1693     TCChain = Copy->getOperand(0);
1694   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1695     return false;
1696
1697   bool HasRet = false;
1698   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1699        UI != UE; ++UI) {
1700     if (UI->getOpcode() != X86ISD::RET_FLAG)
1701       return false;
1702     HasRet = true;
1703   }
1704
1705   if (!HasRet)
1706     return false;
1707
1708   Chain = TCChain;
1709   return true;
1710 }
1711
1712 MVT
1713 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1714                                             ISD::NodeType ExtendKind) const {
1715   MVT ReturnMVT;
1716   // TODO: Is this also valid on 32-bit?
1717   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1718     ReturnMVT = MVT::i8;
1719   else
1720     ReturnMVT = MVT::i32;
1721
1722   MVT MinVT = getRegisterType(ReturnMVT);
1723   return VT.bitsLT(MinVT) ? MinVT : VT;
1724 }
1725
1726 /// LowerCallResult - Lower the result values of a call into the
1727 /// appropriate copies out of appropriate physical registers.
1728 ///
1729 SDValue
1730 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1731                                    CallingConv::ID CallConv, bool isVarArg,
1732                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1733                                    DebugLoc dl, SelectionDAG &DAG,
1734                                    SmallVectorImpl<SDValue> &InVals) const {
1735
1736   // Assign locations to each value returned by this call.
1737   SmallVector<CCValAssign, 16> RVLocs;
1738   bool Is64Bit = Subtarget->is64Bit();
1739   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1740                  getTargetMachine(), RVLocs, *DAG.getContext());
1741   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1742
1743   // Copy all of the result registers out of their specified physreg.
1744   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1745     CCValAssign &VA = RVLocs[i];
1746     EVT CopyVT = VA.getValVT();
1747
1748     // If this is x86-64, and we disabled SSE, we can't return FP values
1749     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1750         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1751       report_fatal_error("SSE register return with SSE disabled");
1752     }
1753
1754     SDValue Val;
1755
1756     // If this is a call to a function that returns an fp value on the floating
1757     // point stack, we must guarantee the value is popped from the stack, so
1758     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1759     // if the return value is not used. We use the FpPOP_RETVAL instruction
1760     // instead.
1761     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1762       // If we prefer to use the value in xmm registers, copy it out as f80 and
1763       // use a truncate to move it from fp stack reg to xmm reg.
1764       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1765       SDValue Ops[] = { Chain, InFlag };
1766       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1767                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1768       Val = Chain.getValue(0);
1769
1770       // Round the f80 to the right size, which also moves it to the appropriate
1771       // xmm register.
1772       if (CopyVT != VA.getValVT())
1773         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1774                           // This truncation won't change the value.
1775                           DAG.getIntPtrConstant(1));
1776     } else {
1777       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1778                                  CopyVT, InFlag).getValue(1);
1779       Val = Chain.getValue(0);
1780     }
1781     InFlag = Chain.getValue(2);
1782     InVals.push_back(Val);
1783   }
1784
1785   return Chain;
1786 }
1787
1788 //===----------------------------------------------------------------------===//
1789 //                C & StdCall & Fast Calling Convention implementation
1790 //===----------------------------------------------------------------------===//
1791 //  StdCall calling convention seems to be standard for many Windows' API
1792 //  routines and around. It differs from C calling convention just a little:
1793 //  callee should clean up the stack, not caller. Symbols should be also
1794 //  decorated in some fancy way :) It doesn't support any vector arguments.
1795 //  For info on fast calling convention see Fast Calling Convention (tail call)
1796 //  implementation LowerX86_32FastCCCallTo.
1797
1798 /// CallIsStructReturn - Determines whether a call uses struct return
1799 /// semantics.
1800 enum StructReturnType {
1801   NotStructReturn,
1802   RegStructReturn,
1803   StackStructReturn
1804 };
1805 static StructReturnType
1806 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1807   if (Outs.empty())
1808     return NotStructReturn;
1809
1810   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1811   if (!Flags.isSRet())
1812     return NotStructReturn;
1813   if (Flags.isInReg())
1814     return RegStructReturn;
1815   return StackStructReturn;
1816 }
1817
1818 /// ArgsAreStructReturn - Determines whether a function uses struct
1819 /// return semantics.
1820 static StructReturnType
1821 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1822   if (Ins.empty())
1823     return NotStructReturn;
1824
1825   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1826   if (!Flags.isSRet())
1827     return NotStructReturn;
1828   if (Flags.isInReg())
1829     return RegStructReturn;
1830   return StackStructReturn;
1831 }
1832
1833 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1834 /// by "Src" to address "Dst" with size and alignment information specified by
1835 /// the specific parameter attribute. The copy will be passed as a byval
1836 /// function parameter.
1837 static SDValue
1838 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1839                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1840                           DebugLoc dl) {
1841   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1842
1843   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1844                        /*isVolatile*/false, /*AlwaysInline=*/true,
1845                        MachinePointerInfo(), MachinePointerInfo());
1846 }
1847
1848 /// IsTailCallConvention - Return true if the calling convention is one that
1849 /// supports tail call optimization.
1850 static bool IsTailCallConvention(CallingConv::ID CC) {
1851   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1852           CC == CallingConv::HiPE);
1853 }
1854
1855 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1856   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1857     return false;
1858
1859   CallSite CS(CI);
1860   CallingConv::ID CalleeCC = CS.getCallingConv();
1861   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1862     return false;
1863
1864   return true;
1865 }
1866
1867 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1868 /// a tailcall target by changing its ABI.
1869 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1870                                    bool GuaranteedTailCallOpt) {
1871   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1872 }
1873
1874 SDValue
1875 X86TargetLowering::LowerMemArgument(SDValue Chain,
1876                                     CallingConv::ID CallConv,
1877                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1878                                     DebugLoc dl, SelectionDAG &DAG,
1879                                     const CCValAssign &VA,
1880                                     MachineFrameInfo *MFI,
1881                                     unsigned i) const {
1882   // Create the nodes corresponding to a load from this parameter slot.
1883   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1884   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1885                               getTargetMachine().Options.GuaranteedTailCallOpt);
1886   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1887   EVT ValVT;
1888
1889   // If value is passed by pointer we have address passed instead of the value
1890   // itself.
1891   if (VA.getLocInfo() == CCValAssign::Indirect)
1892     ValVT = VA.getLocVT();
1893   else
1894     ValVT = VA.getValVT();
1895
1896   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1897   // changed with more analysis.
1898   // In case of tail call optimization mark all arguments mutable. Since they
1899   // could be overwritten by lowering of arguments in case of a tail call.
1900   if (Flags.isByVal()) {
1901     unsigned Bytes = Flags.getByValSize();
1902     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1903     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1904     return DAG.getFrameIndex(FI, getPointerTy());
1905   } else {
1906     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1907                                     VA.getLocMemOffset(), isImmutable);
1908     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1909     return DAG.getLoad(ValVT, dl, Chain, FIN,
1910                        MachinePointerInfo::getFixedStack(FI),
1911                        false, false, false, 0);
1912   }
1913 }
1914
1915 SDValue
1916 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1917                                         CallingConv::ID CallConv,
1918                                         bool isVarArg,
1919                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1920                                         DebugLoc dl,
1921                                         SelectionDAG &DAG,
1922                                         SmallVectorImpl<SDValue> &InVals)
1923                                           const {
1924   MachineFunction &MF = DAG.getMachineFunction();
1925   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1926
1927   const Function* Fn = MF.getFunction();
1928   if (Fn->hasExternalLinkage() &&
1929       Subtarget->isTargetCygMing() &&
1930       Fn->getName() == "main")
1931     FuncInfo->setForceFramePointer(true);
1932
1933   MachineFrameInfo *MFI = MF.getFrameInfo();
1934   bool Is64Bit = Subtarget->is64Bit();
1935   bool IsWindows = Subtarget->isTargetWindows();
1936   bool IsWin64 = Subtarget->isTargetWin64();
1937
1938   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1939          "Var args not supported with calling convention fastcc, ghc or hipe");
1940
1941   // Assign locations to all of the incoming arguments.
1942   SmallVector<CCValAssign, 16> ArgLocs;
1943   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1944                  ArgLocs, *DAG.getContext());
1945
1946   // Allocate shadow area for Win64
1947   if (IsWin64) {
1948     CCInfo.AllocateStack(32, 8);
1949   }
1950
1951   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1952
1953   unsigned LastVal = ~0U;
1954   SDValue ArgValue;
1955   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1956     CCValAssign &VA = ArgLocs[i];
1957     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1958     // places.
1959     assert(VA.getValNo() != LastVal &&
1960            "Don't support value assigned to multiple locs yet");
1961     (void)LastVal;
1962     LastVal = VA.getValNo();
1963
1964     if (VA.isRegLoc()) {
1965       EVT RegVT = VA.getLocVT();
1966       const TargetRegisterClass *RC;
1967       if (RegVT == MVT::i32)
1968         RC = &X86::GR32RegClass;
1969       else if (Is64Bit && RegVT == MVT::i64)
1970         RC = &X86::GR64RegClass;
1971       else if (RegVT == MVT::f32)
1972         RC = &X86::FR32RegClass;
1973       else if (RegVT == MVT::f64)
1974         RC = &X86::FR64RegClass;
1975       else if (RegVT.is256BitVector())
1976         RC = &X86::VR256RegClass;
1977       else if (RegVT.is128BitVector())
1978         RC = &X86::VR128RegClass;
1979       else if (RegVT == MVT::x86mmx)
1980         RC = &X86::VR64RegClass;
1981       else
1982         llvm_unreachable("Unknown argument type!");
1983
1984       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1985       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1986
1987       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1988       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1989       // right size.
1990       if (VA.getLocInfo() == CCValAssign::SExt)
1991         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1992                                DAG.getValueType(VA.getValVT()));
1993       else if (VA.getLocInfo() == CCValAssign::ZExt)
1994         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1995                                DAG.getValueType(VA.getValVT()));
1996       else if (VA.getLocInfo() == CCValAssign::BCvt)
1997         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1998
1999       if (VA.isExtInLoc()) {
2000         // Handle MMX values passed in XMM regs.
2001         if (RegVT.isVector())
2002           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2003         else
2004           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2005       }
2006     } else {
2007       assert(VA.isMemLoc());
2008       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2009     }
2010
2011     // If value is passed via pointer - do a load.
2012     if (VA.getLocInfo() == CCValAssign::Indirect)
2013       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2014                              MachinePointerInfo(), false, false, false, 0);
2015
2016     InVals.push_back(ArgValue);
2017   }
2018
2019   // The x86-64 ABIs require that for returning structs by value we copy
2020   // the sret argument into %rax/%eax (depending on ABI) for the return.
2021   // Save the argument into a virtual register so that we can access it
2022   // from the return points.
2023   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2024     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2025     unsigned Reg = FuncInfo->getSRetReturnReg();
2026     if (!Reg) {
2027       MVT PtrTy = getPointerTy();
2028       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2029       FuncInfo->setSRetReturnReg(Reg);
2030     }
2031     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2032     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2033   }
2034
2035   unsigned StackSize = CCInfo.getNextStackOffset();
2036   // Align stack specially for tail calls.
2037   if (FuncIsMadeTailCallSafe(CallConv,
2038                              MF.getTarget().Options.GuaranteedTailCallOpt))
2039     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2040
2041   // If the function takes variable number of arguments, make a frame index for
2042   // the start of the first vararg value... for expansion of llvm.va_start.
2043   if (isVarArg) {
2044     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2045                     CallConv != CallingConv::X86_ThisCall)) {
2046       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2047     }
2048     if (Is64Bit) {
2049       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2050
2051       // FIXME: We should really autogenerate these arrays
2052       static const uint16_t GPR64ArgRegsWin64[] = {
2053         X86::RCX, X86::RDX, X86::R8,  X86::R9
2054       };
2055       static const uint16_t GPR64ArgRegs64Bit[] = {
2056         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2057       };
2058       static const uint16_t XMMArgRegs64Bit[] = {
2059         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2060         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2061       };
2062       const uint16_t *GPR64ArgRegs;
2063       unsigned NumXMMRegs = 0;
2064
2065       if (IsWin64) {
2066         // The XMM registers which might contain var arg parameters are shadowed
2067         // in their paired GPR.  So we only need to save the GPR to their home
2068         // slots.
2069         TotalNumIntRegs = 4;
2070         GPR64ArgRegs = GPR64ArgRegsWin64;
2071       } else {
2072         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2073         GPR64ArgRegs = GPR64ArgRegs64Bit;
2074
2075         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2076                                                 TotalNumXMMRegs);
2077       }
2078       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2079                                                        TotalNumIntRegs);
2080
2081       bool NoImplicitFloatOps = Fn->getAttributes().
2082         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2083       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2084              "SSE register cannot be used when SSE is disabled!");
2085       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2086                NoImplicitFloatOps) &&
2087              "SSE register cannot be used when SSE is disabled!");
2088       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2089           !Subtarget->hasSSE1())
2090         // Kernel mode asks for SSE to be disabled, so don't push them
2091         // on the stack.
2092         TotalNumXMMRegs = 0;
2093
2094       if (IsWin64) {
2095         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2096         // Get to the caller-allocated home save location.  Add 8 to account
2097         // for the return address.
2098         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2099         FuncInfo->setRegSaveFrameIndex(
2100           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2101         // Fixup to set vararg frame on shadow area (4 x i64).
2102         if (NumIntRegs < 4)
2103           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2104       } else {
2105         // For X86-64, if there are vararg parameters that are passed via
2106         // registers, then we must store them to their spots on the stack so
2107         // they may be loaded by deferencing the result of va_next.
2108         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2109         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2110         FuncInfo->setRegSaveFrameIndex(
2111           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2112                                false));
2113       }
2114
2115       // Store the integer parameter registers.
2116       SmallVector<SDValue, 8> MemOps;
2117       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2118                                         getPointerTy());
2119       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2120       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2121         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2122                                   DAG.getIntPtrConstant(Offset));
2123         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2124                                      &X86::GR64RegClass);
2125         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2126         SDValue Store =
2127           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2128                        MachinePointerInfo::getFixedStack(
2129                          FuncInfo->getRegSaveFrameIndex(), Offset),
2130                        false, false, 0);
2131         MemOps.push_back(Store);
2132         Offset += 8;
2133       }
2134
2135       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2136         // Now store the XMM (fp + vector) parameter registers.
2137         SmallVector<SDValue, 11> SaveXMMOps;
2138         SaveXMMOps.push_back(Chain);
2139
2140         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2141         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2142         SaveXMMOps.push_back(ALVal);
2143
2144         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2145                                FuncInfo->getRegSaveFrameIndex()));
2146         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2147                                FuncInfo->getVarArgsFPOffset()));
2148
2149         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2150           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2151                                        &X86::VR128RegClass);
2152           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2153           SaveXMMOps.push_back(Val);
2154         }
2155         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2156                                      MVT::Other,
2157                                      &SaveXMMOps[0], SaveXMMOps.size()));
2158       }
2159
2160       if (!MemOps.empty())
2161         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2162                             &MemOps[0], MemOps.size());
2163     }
2164   }
2165
2166   // Some CCs need callee pop.
2167   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2168                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2169     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2170   } else {
2171     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2172     // If this is an sret function, the return should pop the hidden pointer.
2173     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2174         argsAreStructReturn(Ins) == StackStructReturn)
2175       FuncInfo->setBytesToPopOnReturn(4);
2176   }
2177
2178   if (!Is64Bit) {
2179     // RegSaveFrameIndex is X86-64 only.
2180     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2181     if (CallConv == CallingConv::X86_FastCall ||
2182         CallConv == CallingConv::X86_ThisCall)
2183       // fastcc functions can't have varargs.
2184       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2185   }
2186
2187   FuncInfo->setArgumentStackSize(StackSize);
2188
2189   return Chain;
2190 }
2191
2192 SDValue
2193 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2194                                     SDValue StackPtr, SDValue Arg,
2195                                     DebugLoc dl, SelectionDAG &DAG,
2196                                     const CCValAssign &VA,
2197                                     ISD::ArgFlagsTy Flags) const {
2198   unsigned LocMemOffset = VA.getLocMemOffset();
2199   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2200   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2201   if (Flags.isByVal())
2202     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2203
2204   return DAG.getStore(Chain, dl, Arg, PtrOff,
2205                       MachinePointerInfo::getStack(LocMemOffset),
2206                       false, false, 0);
2207 }
2208
2209 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2210 /// optimization is performed and it is required.
2211 SDValue
2212 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2213                                            SDValue &OutRetAddr, SDValue Chain,
2214                                            bool IsTailCall, bool Is64Bit,
2215                                            int FPDiff, DebugLoc dl) const {
2216   // Adjust the Return address stack slot.
2217   EVT VT = getPointerTy();
2218   OutRetAddr = getReturnAddressFrameIndex(DAG);
2219
2220   // Load the "old" Return address.
2221   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2222                            false, false, false, 0);
2223   return SDValue(OutRetAddr.getNode(), 1);
2224 }
2225
2226 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2227 /// optimization is performed and it is required (FPDiff!=0).
2228 static SDValue
2229 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2230                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2231                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
2232   // Store the return address to the appropriate stack slot.
2233   if (!FPDiff) return Chain;
2234   // Calculate the new stack slot for the return address.
2235   int NewReturnAddrFI =
2236     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2237   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2238   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2239                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2240                        false, false, 0);
2241   return Chain;
2242 }
2243
2244 SDValue
2245 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2246                              SmallVectorImpl<SDValue> &InVals) const {
2247   SelectionDAG &DAG                     = CLI.DAG;
2248   DebugLoc &dl                          = CLI.DL;
2249   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2250   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2251   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2252   SDValue Chain                         = CLI.Chain;
2253   SDValue Callee                        = CLI.Callee;
2254   CallingConv::ID CallConv              = CLI.CallConv;
2255   bool &isTailCall                      = CLI.IsTailCall;
2256   bool isVarArg                         = CLI.IsVarArg;
2257
2258   MachineFunction &MF = DAG.getMachineFunction();
2259   bool Is64Bit        = Subtarget->is64Bit();
2260   bool IsWin64        = Subtarget->isTargetWin64();
2261   bool IsWindows      = Subtarget->isTargetWindows();
2262   StructReturnType SR = callIsStructReturn(Outs);
2263   bool IsSibcall      = false;
2264
2265   if (MF.getTarget().Options.DisableTailCalls)
2266     isTailCall = false;
2267
2268   if (isTailCall) {
2269     // Check if it's really possible to do a tail call.
2270     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2271                     isVarArg, SR != NotStructReturn,
2272                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2273                     Outs, OutVals, Ins, DAG);
2274
2275     // Sibcalls are automatically detected tailcalls which do not require
2276     // ABI changes.
2277     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2278       IsSibcall = true;
2279
2280     if (isTailCall)
2281       ++NumTailCalls;
2282   }
2283
2284   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2285          "Var args not supported with calling convention fastcc, ghc or hipe");
2286
2287   // Analyze operands of the call, assigning locations to each operand.
2288   SmallVector<CCValAssign, 16> ArgLocs;
2289   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2290                  ArgLocs, *DAG.getContext());
2291
2292   // Allocate shadow area for Win64
2293   if (IsWin64) {
2294     CCInfo.AllocateStack(32, 8);
2295   }
2296
2297   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2298
2299   // Get a count of how many bytes are to be pushed on the stack.
2300   unsigned NumBytes = CCInfo.getNextStackOffset();
2301   if (IsSibcall)
2302     // This is a sibcall. The memory operands are available in caller's
2303     // own caller's stack.
2304     NumBytes = 0;
2305   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2306            IsTailCallConvention(CallConv))
2307     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2308
2309   int FPDiff = 0;
2310   if (isTailCall && !IsSibcall) {
2311     // Lower arguments at fp - stackoffset + fpdiff.
2312     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2313     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2314
2315     FPDiff = NumBytesCallerPushed - NumBytes;
2316
2317     // Set the delta of movement of the returnaddr stackslot.
2318     // But only set if delta is greater than previous delta.
2319     if (FPDiff < X86Info->getTCReturnAddrDelta())
2320       X86Info->setTCReturnAddrDelta(FPDiff);
2321   }
2322
2323   if (!IsSibcall)
2324     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2325
2326   SDValue RetAddrFrIdx;
2327   // Load return address for tail calls.
2328   if (isTailCall && FPDiff)
2329     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2330                                     Is64Bit, FPDiff, dl);
2331
2332   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2333   SmallVector<SDValue, 8> MemOpChains;
2334   SDValue StackPtr;
2335
2336   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2337   // of tail call optimization arguments are handle later.
2338   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2339     CCValAssign &VA = ArgLocs[i];
2340     EVT RegVT = VA.getLocVT();
2341     SDValue Arg = OutVals[i];
2342     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2343     bool isByVal = Flags.isByVal();
2344
2345     // Promote the value if needed.
2346     switch (VA.getLocInfo()) {
2347     default: llvm_unreachable("Unknown loc info!");
2348     case CCValAssign::Full: break;
2349     case CCValAssign::SExt:
2350       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2351       break;
2352     case CCValAssign::ZExt:
2353       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2354       break;
2355     case CCValAssign::AExt:
2356       if (RegVT.is128BitVector()) {
2357         // Special case: passing MMX values in XMM registers.
2358         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2359         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2360         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2361       } else
2362         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2363       break;
2364     case CCValAssign::BCvt:
2365       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2366       break;
2367     case CCValAssign::Indirect: {
2368       // Store the argument.
2369       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2370       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2371       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2372                            MachinePointerInfo::getFixedStack(FI),
2373                            false, false, 0);
2374       Arg = SpillSlot;
2375       break;
2376     }
2377     }
2378
2379     if (VA.isRegLoc()) {
2380       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2381       if (isVarArg && IsWin64) {
2382         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2383         // shadow reg if callee is a varargs function.
2384         unsigned ShadowReg = 0;
2385         switch (VA.getLocReg()) {
2386         case X86::XMM0: ShadowReg = X86::RCX; break;
2387         case X86::XMM1: ShadowReg = X86::RDX; break;
2388         case X86::XMM2: ShadowReg = X86::R8; break;
2389         case X86::XMM3: ShadowReg = X86::R9; break;
2390         }
2391         if (ShadowReg)
2392           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2393       }
2394     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2395       assert(VA.isMemLoc());
2396       if (StackPtr.getNode() == 0)
2397         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2398                                       getPointerTy());
2399       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2400                                              dl, DAG, VA, Flags));
2401     }
2402   }
2403
2404   if (!MemOpChains.empty())
2405     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2406                         &MemOpChains[0], MemOpChains.size());
2407
2408   if (Subtarget->isPICStyleGOT()) {
2409     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2410     // GOT pointer.
2411     if (!isTailCall) {
2412       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2413                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2414     } else {
2415       // If we are tail calling and generating PIC/GOT style code load the
2416       // address of the callee into ECX. The value in ecx is used as target of
2417       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2418       // for tail calls on PIC/GOT architectures. Normally we would just put the
2419       // address of GOT into ebx and then call target@PLT. But for tail calls
2420       // ebx would be restored (since ebx is callee saved) before jumping to the
2421       // target@PLT.
2422
2423       // Note: The actual moving to ECX is done further down.
2424       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2425       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2426           !G->getGlobal()->hasProtectedVisibility())
2427         Callee = LowerGlobalAddress(Callee, DAG);
2428       else if (isa<ExternalSymbolSDNode>(Callee))
2429         Callee = LowerExternalSymbol(Callee, DAG);
2430     }
2431   }
2432
2433   if (Is64Bit && isVarArg && !IsWin64) {
2434     // From AMD64 ABI document:
2435     // For calls that may call functions that use varargs or stdargs
2436     // (prototype-less calls or calls to functions containing ellipsis (...) in
2437     // the declaration) %al is used as hidden argument to specify the number
2438     // of SSE registers used. The contents of %al do not need to match exactly
2439     // the number of registers, but must be an ubound on the number of SSE
2440     // registers used and is in the range 0 - 8 inclusive.
2441
2442     // Count the number of XMM registers allocated.
2443     static const uint16_t XMMArgRegs[] = {
2444       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2445       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2446     };
2447     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2448     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2449            && "SSE registers cannot be used when SSE is disabled");
2450
2451     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2452                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2453   }
2454
2455   // For tail calls lower the arguments to the 'real' stack slot.
2456   if (isTailCall) {
2457     // Force all the incoming stack arguments to be loaded from the stack
2458     // before any new outgoing arguments are stored to the stack, because the
2459     // outgoing stack slots may alias the incoming argument stack slots, and
2460     // the alias isn't otherwise explicit. This is slightly more conservative
2461     // than necessary, because it means that each store effectively depends
2462     // on every argument instead of just those arguments it would clobber.
2463     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2464
2465     SmallVector<SDValue, 8> MemOpChains2;
2466     SDValue FIN;
2467     int FI = 0;
2468     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2469       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2470         CCValAssign &VA = ArgLocs[i];
2471         if (VA.isRegLoc())
2472           continue;
2473         assert(VA.isMemLoc());
2474         SDValue Arg = OutVals[i];
2475         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2476         // Create frame index.
2477         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2478         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2479         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2480         FIN = DAG.getFrameIndex(FI, getPointerTy());
2481
2482         if (Flags.isByVal()) {
2483           // Copy relative to framepointer.
2484           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2485           if (StackPtr.getNode() == 0)
2486             StackPtr = DAG.getCopyFromReg(Chain, dl,
2487                                           RegInfo->getStackRegister(),
2488                                           getPointerTy());
2489           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2490
2491           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2492                                                            ArgChain,
2493                                                            Flags, DAG, dl));
2494         } else {
2495           // Store relative to framepointer.
2496           MemOpChains2.push_back(
2497             DAG.getStore(ArgChain, dl, Arg, FIN,
2498                          MachinePointerInfo::getFixedStack(FI),
2499                          false, false, 0));
2500         }
2501       }
2502     }
2503
2504     if (!MemOpChains2.empty())
2505       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2506                           &MemOpChains2[0], MemOpChains2.size());
2507
2508     // Store the return address to the appropriate stack slot.
2509     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2510                                      getPointerTy(), RegInfo->getSlotSize(),
2511                                      FPDiff, dl);
2512   }
2513
2514   // Build a sequence of copy-to-reg nodes chained together with token chain
2515   // and flag operands which copy the outgoing args into registers.
2516   SDValue InFlag;
2517   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2518     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2519                              RegsToPass[i].second, InFlag);
2520     InFlag = Chain.getValue(1);
2521   }
2522
2523   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2524     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2525     // In the 64-bit large code model, we have to make all calls
2526     // through a register, since the call instruction's 32-bit
2527     // pc-relative offset may not be large enough to hold the whole
2528     // address.
2529   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2530     // If the callee is a GlobalAddress node (quite common, every direct call
2531     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2532     // it.
2533
2534     // We should use extra load for direct calls to dllimported functions in
2535     // non-JIT mode.
2536     const GlobalValue *GV = G->getGlobal();
2537     if (!GV->hasDLLImportLinkage()) {
2538       unsigned char OpFlags = 0;
2539       bool ExtraLoad = false;
2540       unsigned WrapperKind = ISD::DELETED_NODE;
2541
2542       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2543       // external symbols most go through the PLT in PIC mode.  If the symbol
2544       // has hidden or protected visibility, or if it is static or local, then
2545       // we don't need to use the PLT - we can directly call it.
2546       if (Subtarget->isTargetELF() &&
2547           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2548           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2549         OpFlags = X86II::MO_PLT;
2550       } else if (Subtarget->isPICStyleStubAny() &&
2551                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2552                  (!Subtarget->getTargetTriple().isMacOSX() ||
2553                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2554         // PC-relative references to external symbols should go through $stub,
2555         // unless we're building with the leopard linker or later, which
2556         // automatically synthesizes these stubs.
2557         OpFlags = X86II::MO_DARWIN_STUB;
2558       } else if (Subtarget->isPICStyleRIPRel() &&
2559                  isa<Function>(GV) &&
2560                  cast<Function>(GV)->getAttributes().
2561                    hasAttribute(AttributeSet::FunctionIndex,
2562                                 Attribute::NonLazyBind)) {
2563         // If the function is marked as non-lazy, generate an indirect call
2564         // which loads from the GOT directly. This avoids runtime overhead
2565         // at the cost of eager binding (and one extra byte of encoding).
2566         OpFlags = X86II::MO_GOTPCREL;
2567         WrapperKind = X86ISD::WrapperRIP;
2568         ExtraLoad = true;
2569       }
2570
2571       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2572                                           G->getOffset(), OpFlags);
2573
2574       // Add a wrapper if needed.
2575       if (WrapperKind != ISD::DELETED_NODE)
2576         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2577       // Add extra indirection if needed.
2578       if (ExtraLoad)
2579         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2580                              MachinePointerInfo::getGOT(),
2581                              false, false, false, 0);
2582     }
2583   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2584     unsigned char OpFlags = 0;
2585
2586     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2587     // external symbols should go through the PLT.
2588     if (Subtarget->isTargetELF() &&
2589         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2590       OpFlags = X86II::MO_PLT;
2591     } else if (Subtarget->isPICStyleStubAny() &&
2592                (!Subtarget->getTargetTriple().isMacOSX() ||
2593                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2594       // PC-relative references to external symbols should go through $stub,
2595       // unless we're building with the leopard linker or later, which
2596       // automatically synthesizes these stubs.
2597       OpFlags = X86II::MO_DARWIN_STUB;
2598     }
2599
2600     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2601                                          OpFlags);
2602   }
2603
2604   // Returns a chain & a flag for retval copy to use.
2605   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2606   SmallVector<SDValue, 8> Ops;
2607
2608   if (!IsSibcall && isTailCall) {
2609     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2610                            DAG.getIntPtrConstant(0, true), InFlag);
2611     InFlag = Chain.getValue(1);
2612   }
2613
2614   Ops.push_back(Chain);
2615   Ops.push_back(Callee);
2616
2617   if (isTailCall)
2618     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2619
2620   // Add argument registers to the end of the list so that they are known live
2621   // into the call.
2622   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2623     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2624                                   RegsToPass[i].second.getValueType()));
2625
2626   // Add a register mask operand representing the call-preserved registers.
2627   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2628   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2629   assert(Mask && "Missing call preserved mask for calling convention");
2630   Ops.push_back(DAG.getRegisterMask(Mask));
2631
2632   if (InFlag.getNode())
2633     Ops.push_back(InFlag);
2634
2635   if (isTailCall) {
2636     // We used to do:
2637     //// If this is the first return lowered for this function, add the regs
2638     //// to the liveout set for the function.
2639     // This isn't right, although it's probably harmless on x86; liveouts
2640     // should be computed from returns not tail calls.  Consider a void
2641     // function making a tail call to a function returning int.
2642     return DAG.getNode(X86ISD::TC_RETURN, dl,
2643                        NodeTys, &Ops[0], Ops.size());
2644   }
2645
2646   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2647   InFlag = Chain.getValue(1);
2648
2649   // Create the CALLSEQ_END node.
2650   unsigned NumBytesForCalleeToPush;
2651   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2652                        getTargetMachine().Options.GuaranteedTailCallOpt))
2653     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2654   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2655            SR == StackStructReturn)
2656     // If this is a call to a struct-return function, the callee
2657     // pops the hidden struct pointer, so we have to push it back.
2658     // This is common for Darwin/X86, Linux & Mingw32 targets.
2659     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2660     NumBytesForCalleeToPush = 4;
2661   else
2662     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2663
2664   // Returns a flag for retval copy to use.
2665   if (!IsSibcall) {
2666     Chain = DAG.getCALLSEQ_END(Chain,
2667                                DAG.getIntPtrConstant(NumBytes, true),
2668                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2669                                                      true),
2670                                InFlag);
2671     InFlag = Chain.getValue(1);
2672   }
2673
2674   // Handle result values, copying them out of physregs into vregs that we
2675   // return.
2676   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2677                          Ins, dl, DAG, InVals);
2678 }
2679
2680 //===----------------------------------------------------------------------===//
2681 //                Fast Calling Convention (tail call) implementation
2682 //===----------------------------------------------------------------------===//
2683
2684 //  Like std call, callee cleans arguments, convention except that ECX is
2685 //  reserved for storing the tail called function address. Only 2 registers are
2686 //  free for argument passing (inreg). Tail call optimization is performed
2687 //  provided:
2688 //                * tailcallopt is enabled
2689 //                * caller/callee are fastcc
2690 //  On X86_64 architecture with GOT-style position independent code only local
2691 //  (within module) calls are supported at the moment.
2692 //  To keep the stack aligned according to platform abi the function
2693 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2694 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2695 //  If a tail called function callee has more arguments than the caller the
2696 //  caller needs to make sure that there is room to move the RETADDR to. This is
2697 //  achieved by reserving an area the size of the argument delta right after the
2698 //  original REtADDR, but before the saved framepointer or the spilled registers
2699 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2700 //  stack layout:
2701 //    arg1
2702 //    arg2
2703 //    RETADDR
2704 //    [ new RETADDR
2705 //      move area ]
2706 //    (possible EBP)
2707 //    ESI
2708 //    EDI
2709 //    local1 ..
2710
2711 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2712 /// for a 16 byte align requirement.
2713 unsigned
2714 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2715                                                SelectionDAG& DAG) const {
2716   MachineFunction &MF = DAG.getMachineFunction();
2717   const TargetMachine &TM = MF.getTarget();
2718   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2719   unsigned StackAlignment = TFI.getStackAlignment();
2720   uint64_t AlignMask = StackAlignment - 1;
2721   int64_t Offset = StackSize;
2722   unsigned SlotSize = RegInfo->getSlotSize();
2723   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2724     // Number smaller than 12 so just add the difference.
2725     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2726   } else {
2727     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2728     Offset = ((~AlignMask) & Offset) + StackAlignment +
2729       (StackAlignment-SlotSize);
2730   }
2731   return Offset;
2732 }
2733
2734 /// MatchingStackOffset - Return true if the given stack call argument is
2735 /// already available in the same position (relatively) of the caller's
2736 /// incoming argument stack.
2737 static
2738 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2739                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2740                          const X86InstrInfo *TII) {
2741   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2742   int FI = INT_MAX;
2743   if (Arg.getOpcode() == ISD::CopyFromReg) {
2744     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2745     if (!TargetRegisterInfo::isVirtualRegister(VR))
2746       return false;
2747     MachineInstr *Def = MRI->getVRegDef(VR);
2748     if (!Def)
2749       return false;
2750     if (!Flags.isByVal()) {
2751       if (!TII->isLoadFromStackSlot(Def, FI))
2752         return false;
2753     } else {
2754       unsigned Opcode = Def->getOpcode();
2755       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2756           Def->getOperand(1).isFI()) {
2757         FI = Def->getOperand(1).getIndex();
2758         Bytes = Flags.getByValSize();
2759       } else
2760         return false;
2761     }
2762   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2763     if (Flags.isByVal())
2764       // ByVal argument is passed in as a pointer but it's now being
2765       // dereferenced. e.g.
2766       // define @foo(%struct.X* %A) {
2767       //   tail call @bar(%struct.X* byval %A)
2768       // }
2769       return false;
2770     SDValue Ptr = Ld->getBasePtr();
2771     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2772     if (!FINode)
2773       return false;
2774     FI = FINode->getIndex();
2775   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2776     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2777     FI = FINode->getIndex();
2778     Bytes = Flags.getByValSize();
2779   } else
2780     return false;
2781
2782   assert(FI != INT_MAX);
2783   if (!MFI->isFixedObjectIndex(FI))
2784     return false;
2785   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2786 }
2787
2788 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2789 /// for tail call optimization. Targets which want to do tail call
2790 /// optimization should implement this function.
2791 bool
2792 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2793                                                      CallingConv::ID CalleeCC,
2794                                                      bool isVarArg,
2795                                                      bool isCalleeStructRet,
2796                                                      bool isCallerStructRet,
2797                                                      Type *RetTy,
2798                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2799                                     const SmallVectorImpl<SDValue> &OutVals,
2800                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2801                                                      SelectionDAG& DAG) const {
2802   if (!IsTailCallConvention(CalleeCC) &&
2803       CalleeCC != CallingConv::C)
2804     return false;
2805
2806   // If -tailcallopt is specified, make fastcc functions tail-callable.
2807   const MachineFunction &MF = DAG.getMachineFunction();
2808   const Function *CallerF = DAG.getMachineFunction().getFunction();
2809
2810   // If the function return type is x86_fp80 and the callee return type is not,
2811   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2812   // perform a tailcall optimization here.
2813   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2814     return false;
2815
2816   CallingConv::ID CallerCC = CallerF->getCallingConv();
2817   bool CCMatch = CallerCC == CalleeCC;
2818
2819   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2820     if (IsTailCallConvention(CalleeCC) && CCMatch)
2821       return true;
2822     return false;
2823   }
2824
2825   // Look for obvious safe cases to perform tail call optimization that do not
2826   // require ABI changes. This is what gcc calls sibcall.
2827
2828   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2829   // emit a special epilogue.
2830   if (RegInfo->needsStackRealignment(MF))
2831     return false;
2832
2833   // Also avoid sibcall optimization if either caller or callee uses struct
2834   // return semantics.
2835   if (isCalleeStructRet || isCallerStructRet)
2836     return false;
2837
2838   // An stdcall caller is expected to clean up its arguments; the callee
2839   // isn't going to do that.
2840   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2841     return false;
2842
2843   // Do not sibcall optimize vararg calls unless all arguments are passed via
2844   // registers.
2845   if (isVarArg && !Outs.empty()) {
2846
2847     // Optimizing for varargs on Win64 is unlikely to be safe without
2848     // additional testing.
2849     if (Subtarget->isTargetWin64())
2850       return false;
2851
2852     SmallVector<CCValAssign, 16> ArgLocs;
2853     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2854                    getTargetMachine(), ArgLocs, *DAG.getContext());
2855
2856     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2857     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2858       if (!ArgLocs[i].isRegLoc())
2859         return false;
2860   }
2861
2862   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2863   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2864   // this into a sibcall.
2865   bool Unused = false;
2866   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2867     if (!Ins[i].Used) {
2868       Unused = true;
2869       break;
2870     }
2871   }
2872   if (Unused) {
2873     SmallVector<CCValAssign, 16> RVLocs;
2874     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2875                    getTargetMachine(), RVLocs, *DAG.getContext());
2876     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2877     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2878       CCValAssign &VA = RVLocs[i];
2879       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2880         return false;
2881     }
2882   }
2883
2884   // If the calling conventions do not match, then we'd better make sure the
2885   // results are returned in the same way as what the caller expects.
2886   if (!CCMatch) {
2887     SmallVector<CCValAssign, 16> RVLocs1;
2888     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2889                     getTargetMachine(), RVLocs1, *DAG.getContext());
2890     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2891
2892     SmallVector<CCValAssign, 16> RVLocs2;
2893     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2894                     getTargetMachine(), RVLocs2, *DAG.getContext());
2895     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2896
2897     if (RVLocs1.size() != RVLocs2.size())
2898       return false;
2899     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2900       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2901         return false;
2902       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2903         return false;
2904       if (RVLocs1[i].isRegLoc()) {
2905         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2906           return false;
2907       } else {
2908         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2909           return false;
2910       }
2911     }
2912   }
2913
2914   // If the callee takes no arguments then go on to check the results of the
2915   // call.
2916   if (!Outs.empty()) {
2917     // Check if stack adjustment is needed. For now, do not do this if any
2918     // argument is passed on the stack.
2919     SmallVector<CCValAssign, 16> ArgLocs;
2920     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2921                    getTargetMachine(), ArgLocs, *DAG.getContext());
2922
2923     // Allocate shadow area for Win64
2924     if (Subtarget->isTargetWin64()) {
2925       CCInfo.AllocateStack(32, 8);
2926     }
2927
2928     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2929     if (CCInfo.getNextStackOffset()) {
2930       MachineFunction &MF = DAG.getMachineFunction();
2931       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2932         return false;
2933
2934       // Check if the arguments are already laid out in the right way as
2935       // the caller's fixed stack objects.
2936       MachineFrameInfo *MFI = MF.getFrameInfo();
2937       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2938       const X86InstrInfo *TII =
2939         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2940       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2941         CCValAssign &VA = ArgLocs[i];
2942         SDValue Arg = OutVals[i];
2943         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2944         if (VA.getLocInfo() == CCValAssign::Indirect)
2945           return false;
2946         if (!VA.isRegLoc()) {
2947           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2948                                    MFI, MRI, TII))
2949             return false;
2950         }
2951       }
2952     }
2953
2954     // If the tailcall address may be in a register, then make sure it's
2955     // possible to register allocate for it. In 32-bit, the call address can
2956     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2957     // callee-saved registers are restored. These happen to be the same
2958     // registers used to pass 'inreg' arguments so watch out for those.
2959     if (!Subtarget->is64Bit() &&
2960         !isa<GlobalAddressSDNode>(Callee) &&
2961         !isa<ExternalSymbolSDNode>(Callee)) {
2962       unsigned NumInRegs = 0;
2963       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2964         CCValAssign &VA = ArgLocs[i];
2965         if (!VA.isRegLoc())
2966           continue;
2967         unsigned Reg = VA.getLocReg();
2968         switch (Reg) {
2969         default: break;
2970         case X86::EAX: case X86::EDX: case X86::ECX:
2971           if (++NumInRegs == 3)
2972             return false;
2973           break;
2974         }
2975       }
2976     }
2977   }
2978
2979   return true;
2980 }
2981
2982 FastISel *
2983 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2984                                   const TargetLibraryInfo *libInfo) const {
2985   return X86::createFastISel(funcInfo, libInfo);
2986 }
2987
2988 //===----------------------------------------------------------------------===//
2989 //                           Other Lowering Hooks
2990 //===----------------------------------------------------------------------===//
2991
2992 static bool MayFoldLoad(SDValue Op) {
2993   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2994 }
2995
2996 static bool MayFoldIntoStore(SDValue Op) {
2997   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2998 }
2999
3000 static bool isTargetShuffle(unsigned Opcode) {
3001   switch(Opcode) {
3002   default: return false;
3003   case X86ISD::PSHUFD:
3004   case X86ISD::PSHUFHW:
3005   case X86ISD::PSHUFLW:
3006   case X86ISD::SHUFP:
3007   case X86ISD::PALIGNR:
3008   case X86ISD::MOVLHPS:
3009   case X86ISD::MOVLHPD:
3010   case X86ISD::MOVHLPS:
3011   case X86ISD::MOVLPS:
3012   case X86ISD::MOVLPD:
3013   case X86ISD::MOVSHDUP:
3014   case X86ISD::MOVSLDUP:
3015   case X86ISD::MOVDDUP:
3016   case X86ISD::MOVSS:
3017   case X86ISD::MOVSD:
3018   case X86ISD::UNPCKL:
3019   case X86ISD::UNPCKH:
3020   case X86ISD::VPERMILP:
3021   case X86ISD::VPERM2X128:
3022   case X86ISD::VPERMI:
3023     return true;
3024   }
3025 }
3026
3027 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3028                                     SDValue V1, SelectionDAG &DAG) {
3029   switch(Opc) {
3030   default: llvm_unreachable("Unknown x86 shuffle node");
3031   case X86ISD::MOVSHDUP:
3032   case X86ISD::MOVSLDUP:
3033   case X86ISD::MOVDDUP:
3034     return DAG.getNode(Opc, dl, VT, V1);
3035   }
3036 }
3037
3038 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3039                                     SDValue V1, unsigned TargetMask,
3040                                     SelectionDAG &DAG) {
3041   switch(Opc) {
3042   default: llvm_unreachable("Unknown x86 shuffle node");
3043   case X86ISD::PSHUFD:
3044   case X86ISD::PSHUFHW:
3045   case X86ISD::PSHUFLW:
3046   case X86ISD::VPERMILP:
3047   case X86ISD::VPERMI:
3048     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3049   }
3050 }
3051
3052 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3053                                     SDValue V1, SDValue V2, unsigned TargetMask,
3054                                     SelectionDAG &DAG) {
3055   switch(Opc) {
3056   default: llvm_unreachable("Unknown x86 shuffle node");
3057   case X86ISD::PALIGNR:
3058   case X86ISD::SHUFP:
3059   case X86ISD::VPERM2X128:
3060     return DAG.getNode(Opc, dl, VT, V1, V2,
3061                        DAG.getConstant(TargetMask, MVT::i8));
3062   }
3063 }
3064
3065 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3066                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3067   switch(Opc) {
3068   default: llvm_unreachable("Unknown x86 shuffle node");
3069   case X86ISD::MOVLHPS:
3070   case X86ISD::MOVLHPD:
3071   case X86ISD::MOVHLPS:
3072   case X86ISD::MOVLPS:
3073   case X86ISD::MOVLPD:
3074   case X86ISD::MOVSS:
3075   case X86ISD::MOVSD:
3076   case X86ISD::UNPCKL:
3077   case X86ISD::UNPCKH:
3078     return DAG.getNode(Opc, dl, VT, V1, V2);
3079   }
3080 }
3081
3082 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3083   MachineFunction &MF = DAG.getMachineFunction();
3084   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3085   int ReturnAddrIndex = FuncInfo->getRAIndex();
3086
3087   if (ReturnAddrIndex == 0) {
3088     // Set up a frame object for the return address.
3089     unsigned SlotSize = RegInfo->getSlotSize();
3090     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3091                                                            false);
3092     FuncInfo->setRAIndex(ReturnAddrIndex);
3093   }
3094
3095   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3096 }
3097
3098 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3099                                        bool hasSymbolicDisplacement) {
3100   // Offset should fit into 32 bit immediate field.
3101   if (!isInt<32>(Offset))
3102     return false;
3103
3104   // If we don't have a symbolic displacement - we don't have any extra
3105   // restrictions.
3106   if (!hasSymbolicDisplacement)
3107     return true;
3108
3109   // FIXME: Some tweaks might be needed for medium code model.
3110   if (M != CodeModel::Small && M != CodeModel::Kernel)
3111     return false;
3112
3113   // For small code model we assume that latest object is 16MB before end of 31
3114   // bits boundary. We may also accept pretty large negative constants knowing
3115   // that all objects are in the positive half of address space.
3116   if (M == CodeModel::Small && Offset < 16*1024*1024)
3117     return true;
3118
3119   // For kernel code model we know that all object resist in the negative half
3120   // of 32bits address space. We may not accept negative offsets, since they may
3121   // be just off and we may accept pretty large positive ones.
3122   if (M == CodeModel::Kernel && Offset > 0)
3123     return true;
3124
3125   return false;
3126 }
3127
3128 /// isCalleePop - Determines whether the callee is required to pop its
3129 /// own arguments. Callee pop is necessary to support tail calls.
3130 bool X86::isCalleePop(CallingConv::ID CallingConv,
3131                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3132   if (IsVarArg)
3133     return false;
3134
3135   switch (CallingConv) {
3136   default:
3137     return false;
3138   case CallingConv::X86_StdCall:
3139     return !is64Bit;
3140   case CallingConv::X86_FastCall:
3141     return !is64Bit;
3142   case CallingConv::X86_ThisCall:
3143     return !is64Bit;
3144   case CallingConv::Fast:
3145     return TailCallOpt;
3146   case CallingConv::GHC:
3147     return TailCallOpt;
3148   case CallingConv::HiPE:
3149     return TailCallOpt;
3150   }
3151 }
3152
3153 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3154 /// specific condition code, returning the condition code and the LHS/RHS of the
3155 /// comparison to make.
3156 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3157                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3158   if (!isFP) {
3159     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3160       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3161         // X > -1   -> X == 0, jump !sign.
3162         RHS = DAG.getConstant(0, RHS.getValueType());
3163         return X86::COND_NS;
3164       }
3165       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3166         // X < 0   -> X == 0, jump on sign.
3167         return X86::COND_S;
3168       }
3169       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3170         // X < 1   -> X <= 0
3171         RHS = DAG.getConstant(0, RHS.getValueType());
3172         return X86::COND_LE;
3173       }
3174     }
3175
3176     switch (SetCCOpcode) {
3177     default: llvm_unreachable("Invalid integer condition!");
3178     case ISD::SETEQ:  return X86::COND_E;
3179     case ISD::SETGT:  return X86::COND_G;
3180     case ISD::SETGE:  return X86::COND_GE;
3181     case ISD::SETLT:  return X86::COND_L;
3182     case ISD::SETLE:  return X86::COND_LE;
3183     case ISD::SETNE:  return X86::COND_NE;
3184     case ISD::SETULT: return X86::COND_B;
3185     case ISD::SETUGT: return X86::COND_A;
3186     case ISD::SETULE: return X86::COND_BE;
3187     case ISD::SETUGE: return X86::COND_AE;
3188     }
3189   }
3190
3191   // First determine if it is required or is profitable to flip the operands.
3192
3193   // If LHS is a foldable load, but RHS is not, flip the condition.
3194   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3195       !ISD::isNON_EXTLoad(RHS.getNode())) {
3196     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3197     std::swap(LHS, RHS);
3198   }
3199
3200   switch (SetCCOpcode) {
3201   default: break;
3202   case ISD::SETOLT:
3203   case ISD::SETOLE:
3204   case ISD::SETUGT:
3205   case ISD::SETUGE:
3206     std::swap(LHS, RHS);
3207     break;
3208   }
3209
3210   // On a floating point condition, the flags are set as follows:
3211   // ZF  PF  CF   op
3212   //  0 | 0 | 0 | X > Y
3213   //  0 | 0 | 1 | X < Y
3214   //  1 | 0 | 0 | X == Y
3215   //  1 | 1 | 1 | unordered
3216   switch (SetCCOpcode) {
3217   default: llvm_unreachable("Condcode should be pre-legalized away");
3218   case ISD::SETUEQ:
3219   case ISD::SETEQ:   return X86::COND_E;
3220   case ISD::SETOLT:              // flipped
3221   case ISD::SETOGT:
3222   case ISD::SETGT:   return X86::COND_A;
3223   case ISD::SETOLE:              // flipped
3224   case ISD::SETOGE:
3225   case ISD::SETGE:   return X86::COND_AE;
3226   case ISD::SETUGT:              // flipped
3227   case ISD::SETULT:
3228   case ISD::SETLT:   return X86::COND_B;
3229   case ISD::SETUGE:              // flipped
3230   case ISD::SETULE:
3231   case ISD::SETLE:   return X86::COND_BE;
3232   case ISD::SETONE:
3233   case ISD::SETNE:   return X86::COND_NE;
3234   case ISD::SETUO:   return X86::COND_P;
3235   case ISD::SETO:    return X86::COND_NP;
3236   case ISD::SETOEQ:
3237   case ISD::SETUNE:  return X86::COND_INVALID;
3238   }
3239 }
3240
3241 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3242 /// code. Current x86 isa includes the following FP cmov instructions:
3243 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3244 static bool hasFPCMov(unsigned X86CC) {
3245   switch (X86CC) {
3246   default:
3247     return false;
3248   case X86::COND_B:
3249   case X86::COND_BE:
3250   case X86::COND_E:
3251   case X86::COND_P:
3252   case X86::COND_A:
3253   case X86::COND_AE:
3254   case X86::COND_NE:
3255   case X86::COND_NP:
3256     return true;
3257   }
3258 }
3259
3260 /// isFPImmLegal - Returns true if the target can instruction select the
3261 /// specified FP immediate natively. If false, the legalizer will
3262 /// materialize the FP immediate as a load from a constant pool.
3263 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3264   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3265     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3266       return true;
3267   }
3268   return false;
3269 }
3270
3271 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3272 /// the specified range (L, H].
3273 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3274   return (Val < 0) || (Val >= Low && Val < Hi);
3275 }
3276
3277 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3278 /// specified value.
3279 static bool isUndefOrEqual(int Val, int CmpVal) {
3280   return (Val < 0 || Val == CmpVal);
3281 }
3282
3283 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3284 /// from position Pos and ending in Pos+Size, falls within the specified
3285 /// sequential range (L, L+Pos]. or is undef.
3286 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3287                                        unsigned Pos, unsigned Size, int Low) {
3288   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3289     if (!isUndefOrEqual(Mask[i], Low))
3290       return false;
3291   return true;
3292 }
3293
3294 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3295 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3296 /// the second operand.
3297 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3298   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3299     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3300   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3301     return (Mask[0] < 2 && Mask[1] < 2);
3302   return false;
3303 }
3304
3305 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3306 /// is suitable for input to PSHUFHW.
3307 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3308   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3309     return false;
3310
3311   // Lower quadword copied in order or undef.
3312   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3313     return false;
3314
3315   // Upper quadword shuffled.
3316   for (unsigned i = 4; i != 8; ++i)
3317     if (!isUndefOrInRange(Mask[i], 4, 8))
3318       return false;
3319
3320   if (VT == MVT::v16i16) {
3321     // Lower quadword copied in order or undef.
3322     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3323       return false;
3324
3325     // Upper quadword shuffled.
3326     for (unsigned i = 12; i != 16; ++i)
3327       if (!isUndefOrInRange(Mask[i], 12, 16))
3328         return false;
3329   }
3330
3331   return true;
3332 }
3333
3334 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3335 /// is suitable for input to PSHUFLW.
3336 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3337   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3338     return false;
3339
3340   // Upper quadword copied in order.
3341   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3342     return false;
3343
3344   // Lower quadword shuffled.
3345   for (unsigned i = 0; i != 4; ++i)
3346     if (!isUndefOrInRange(Mask[i], 0, 4))
3347       return false;
3348
3349   if (VT == MVT::v16i16) {
3350     // Upper quadword copied in order.
3351     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3352       return false;
3353
3354     // Lower quadword shuffled.
3355     for (unsigned i = 8; i != 12; ++i)
3356       if (!isUndefOrInRange(Mask[i], 8, 12))
3357         return false;
3358   }
3359
3360   return true;
3361 }
3362
3363 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3364 /// is suitable for input to PALIGNR.
3365 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3366                           const X86Subtarget *Subtarget) {
3367   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3368       (VT.is256BitVector() && !Subtarget->hasInt256()))
3369     return false;
3370
3371   unsigned NumElts = VT.getVectorNumElements();
3372   unsigned NumLanes = VT.getSizeInBits()/128;
3373   unsigned NumLaneElts = NumElts/NumLanes;
3374
3375   // Do not handle 64-bit element shuffles with palignr.
3376   if (NumLaneElts == 2)
3377     return false;
3378
3379   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3380     unsigned i;
3381     for (i = 0; i != NumLaneElts; ++i) {
3382       if (Mask[i+l] >= 0)
3383         break;
3384     }
3385
3386     // Lane is all undef, go to next lane
3387     if (i == NumLaneElts)
3388       continue;
3389
3390     int Start = Mask[i+l];
3391
3392     // Make sure its in this lane in one of the sources
3393     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3394         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3395       return false;
3396
3397     // If not lane 0, then we must match lane 0
3398     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3399       return false;
3400
3401     // Correct second source to be contiguous with first source
3402     if (Start >= (int)NumElts)
3403       Start -= NumElts - NumLaneElts;
3404
3405     // Make sure we're shifting in the right direction.
3406     if (Start <= (int)(i+l))
3407       return false;
3408
3409     Start -= i;
3410
3411     // Check the rest of the elements to see if they are consecutive.
3412     for (++i; i != NumLaneElts; ++i) {
3413       int Idx = Mask[i+l];
3414
3415       // Make sure its in this lane
3416       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3417           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3418         return false;
3419
3420       // If not lane 0, then we must match lane 0
3421       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3422         return false;
3423
3424       if (Idx >= (int)NumElts)
3425         Idx -= NumElts - NumLaneElts;
3426
3427       if (!isUndefOrEqual(Idx, Start+i))
3428         return false;
3429
3430     }
3431   }
3432
3433   return true;
3434 }
3435
3436 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3437 /// the two vector operands have swapped position.
3438 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3439                                      unsigned NumElems) {
3440   for (unsigned i = 0; i != NumElems; ++i) {
3441     int idx = Mask[i];
3442     if (idx < 0)
3443       continue;
3444     else if (idx < (int)NumElems)
3445       Mask[i] = idx + NumElems;
3446     else
3447       Mask[i] = idx - NumElems;
3448   }
3449 }
3450
3451 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3452 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3453 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3454 /// reverse of what x86 shuffles want.
3455 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3456                         bool Commuted = false) {
3457   if (!HasFp256 && VT.is256BitVector())
3458     return false;
3459
3460   unsigned NumElems = VT.getVectorNumElements();
3461   unsigned NumLanes = VT.getSizeInBits()/128;
3462   unsigned NumLaneElems = NumElems/NumLanes;
3463
3464   if (NumLaneElems != 2 && NumLaneElems != 4)
3465     return false;
3466
3467   // VSHUFPSY divides the resulting vector into 4 chunks.
3468   // The sources are also splitted into 4 chunks, and each destination
3469   // chunk must come from a different source chunk.
3470   //
3471   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3472   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3473   //
3474   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3475   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3476   //
3477   // VSHUFPDY divides the resulting vector into 4 chunks.
3478   // The sources are also splitted into 4 chunks, and each destination
3479   // chunk must come from a different source chunk.
3480   //
3481   //  SRC1 =>      X3       X2       X1       X0
3482   //  SRC2 =>      Y3       Y2       Y1       Y0
3483   //
3484   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3485   //
3486   unsigned HalfLaneElems = NumLaneElems/2;
3487   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3488     for (unsigned i = 0; i != NumLaneElems; ++i) {
3489       int Idx = Mask[i+l];
3490       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3491       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3492         return false;
3493       // For VSHUFPSY, the mask of the second half must be the same as the
3494       // first but with the appropriate offsets. This works in the same way as
3495       // VPERMILPS works with masks.
3496       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3497         continue;
3498       if (!isUndefOrEqual(Idx, Mask[i]+l))
3499         return false;
3500     }
3501   }
3502
3503   return true;
3504 }
3505
3506 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3507 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3508 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3509   if (!VT.is128BitVector())
3510     return false;
3511
3512   unsigned NumElems = VT.getVectorNumElements();
3513
3514   if (NumElems != 4)
3515     return false;
3516
3517   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3518   return isUndefOrEqual(Mask[0], 6) &&
3519          isUndefOrEqual(Mask[1], 7) &&
3520          isUndefOrEqual(Mask[2], 2) &&
3521          isUndefOrEqual(Mask[3], 3);
3522 }
3523
3524 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3525 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3526 /// <2, 3, 2, 3>
3527 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3528   if (!VT.is128BitVector())
3529     return false;
3530
3531   unsigned NumElems = VT.getVectorNumElements();
3532
3533   if (NumElems != 4)
3534     return false;
3535
3536   return isUndefOrEqual(Mask[0], 2) &&
3537          isUndefOrEqual(Mask[1], 3) &&
3538          isUndefOrEqual(Mask[2], 2) &&
3539          isUndefOrEqual(Mask[3], 3);
3540 }
3541
3542 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3543 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3544 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3545   if (!VT.is128BitVector())
3546     return false;
3547
3548   unsigned NumElems = VT.getVectorNumElements();
3549
3550   if (NumElems != 2 && NumElems != 4)
3551     return false;
3552
3553   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3554     if (!isUndefOrEqual(Mask[i], i + NumElems))
3555       return false;
3556
3557   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3558     if (!isUndefOrEqual(Mask[i], i))
3559       return false;
3560
3561   return true;
3562 }
3563
3564 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3565 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3566 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3567   if (!VT.is128BitVector())
3568     return false;
3569
3570   unsigned NumElems = VT.getVectorNumElements();
3571
3572   if (NumElems != 2 && NumElems != 4)
3573     return false;
3574
3575   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3576     if (!isUndefOrEqual(Mask[i], i))
3577       return false;
3578
3579   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3580     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3581       return false;
3582
3583   return true;
3584 }
3585
3586 //
3587 // Some special combinations that can be optimized.
3588 //
3589 static
3590 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3591                                SelectionDAG &DAG) {
3592   MVT VT = SVOp->getValueType(0).getSimpleVT();
3593   DebugLoc dl = SVOp->getDebugLoc();
3594
3595   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3596     return SDValue();
3597
3598   ArrayRef<int> Mask = SVOp->getMask();
3599
3600   // These are the special masks that may be optimized.
3601   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3602   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3603   bool MatchEvenMask = true;
3604   bool MatchOddMask  = true;
3605   for (int i=0; i<8; ++i) {
3606     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3607       MatchEvenMask = false;
3608     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3609       MatchOddMask = false;
3610   }
3611
3612   if (!MatchEvenMask && !MatchOddMask)
3613     return SDValue();
3614
3615   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3616
3617   SDValue Op0 = SVOp->getOperand(0);
3618   SDValue Op1 = SVOp->getOperand(1);
3619
3620   if (MatchEvenMask) {
3621     // Shift the second operand right to 32 bits.
3622     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3623     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3624   } else {
3625     // Shift the first operand left to 32 bits.
3626     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3627     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3628   }
3629   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3630   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3631 }
3632
3633 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3634 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3635 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3636                          bool HasInt256, bool V2IsSplat = false) {
3637   unsigned NumElts = VT.getVectorNumElements();
3638
3639   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3640          "Unsupported vector type for unpckh");
3641
3642   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3643       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3644     return false;
3645
3646   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3647   // independently on 128-bit lanes.
3648   unsigned NumLanes = VT.getSizeInBits()/128;
3649   unsigned NumLaneElts = NumElts/NumLanes;
3650
3651   for (unsigned l = 0; l != NumLanes; ++l) {
3652     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3653          i != (l+1)*NumLaneElts;
3654          i += 2, ++j) {
3655       int BitI  = Mask[i];
3656       int BitI1 = Mask[i+1];
3657       if (!isUndefOrEqual(BitI, j))
3658         return false;
3659       if (V2IsSplat) {
3660         if (!isUndefOrEqual(BitI1, NumElts))
3661           return false;
3662       } else {
3663         if (!isUndefOrEqual(BitI1, j + NumElts))
3664           return false;
3665       }
3666     }
3667   }
3668
3669   return true;
3670 }
3671
3672 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3673 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3674 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3675                          bool HasInt256, bool V2IsSplat = false) {
3676   unsigned NumElts = VT.getVectorNumElements();
3677
3678   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3679          "Unsupported vector type for unpckh");
3680
3681   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3682       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3683     return false;
3684
3685   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3686   // independently on 128-bit lanes.
3687   unsigned NumLanes = VT.getSizeInBits()/128;
3688   unsigned NumLaneElts = NumElts/NumLanes;
3689
3690   for (unsigned l = 0; l != NumLanes; ++l) {
3691     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3692          i != (l+1)*NumLaneElts; i += 2, ++j) {
3693       int BitI  = Mask[i];
3694       int BitI1 = Mask[i+1];
3695       if (!isUndefOrEqual(BitI, j))
3696         return false;
3697       if (V2IsSplat) {
3698         if (isUndefOrEqual(BitI1, NumElts))
3699           return false;
3700       } else {
3701         if (!isUndefOrEqual(BitI1, j+NumElts))
3702           return false;
3703       }
3704     }
3705   }
3706   return true;
3707 }
3708
3709 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3710 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3711 /// <0, 0, 1, 1>
3712 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3713   unsigned NumElts = VT.getVectorNumElements();
3714   bool Is256BitVec = VT.is256BitVector();
3715
3716   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3717          "Unsupported vector type for unpckh");
3718
3719   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3720       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3721     return false;
3722
3723   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3724   // FIXME: Need a better way to get rid of this, there's no latency difference
3725   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3726   // the former later. We should also remove the "_undef" special mask.
3727   if (NumElts == 4 && Is256BitVec)
3728     return false;
3729
3730   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3731   // independently on 128-bit lanes.
3732   unsigned NumLanes = VT.getSizeInBits()/128;
3733   unsigned NumLaneElts = NumElts/NumLanes;
3734
3735   for (unsigned l = 0; l != NumLanes; ++l) {
3736     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3737          i != (l+1)*NumLaneElts;
3738          i += 2, ++j) {
3739       int BitI  = Mask[i];
3740       int BitI1 = Mask[i+1];
3741
3742       if (!isUndefOrEqual(BitI, j))
3743         return false;
3744       if (!isUndefOrEqual(BitI1, j))
3745         return false;
3746     }
3747   }
3748
3749   return true;
3750 }
3751
3752 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3753 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3754 /// <2, 2, 3, 3>
3755 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3756   unsigned NumElts = VT.getVectorNumElements();
3757
3758   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3759          "Unsupported vector type for unpckh");
3760
3761   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3762       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3763     return false;
3764
3765   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3766   // independently on 128-bit lanes.
3767   unsigned NumLanes = VT.getSizeInBits()/128;
3768   unsigned NumLaneElts = NumElts/NumLanes;
3769
3770   for (unsigned l = 0; l != NumLanes; ++l) {
3771     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3772          i != (l+1)*NumLaneElts; i += 2, ++j) {
3773       int BitI  = Mask[i];
3774       int BitI1 = Mask[i+1];
3775       if (!isUndefOrEqual(BitI, j))
3776         return false;
3777       if (!isUndefOrEqual(BitI1, j))
3778         return false;
3779     }
3780   }
3781   return true;
3782 }
3783
3784 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3785 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3786 /// MOVSD, and MOVD, i.e. setting the lowest element.
3787 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3788   if (VT.getVectorElementType().getSizeInBits() < 32)
3789     return false;
3790   if (!VT.is128BitVector())
3791     return false;
3792
3793   unsigned NumElts = VT.getVectorNumElements();
3794
3795   if (!isUndefOrEqual(Mask[0], NumElts))
3796     return false;
3797
3798   for (unsigned i = 1; i != NumElts; ++i)
3799     if (!isUndefOrEqual(Mask[i], i))
3800       return false;
3801
3802   return true;
3803 }
3804
3805 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3806 /// as permutations between 128-bit chunks or halves. As an example: this
3807 /// shuffle bellow:
3808 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3809 /// The first half comes from the second half of V1 and the second half from the
3810 /// the second half of V2.
3811 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3812   if (!HasFp256 || !VT.is256BitVector())
3813     return false;
3814
3815   // The shuffle result is divided into half A and half B. In total the two
3816   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3817   // B must come from C, D, E or F.
3818   unsigned HalfSize = VT.getVectorNumElements()/2;
3819   bool MatchA = false, MatchB = false;
3820
3821   // Check if A comes from one of C, D, E, F.
3822   for (unsigned Half = 0; Half != 4; ++Half) {
3823     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3824       MatchA = true;
3825       break;
3826     }
3827   }
3828
3829   // Check if B comes from one of C, D, E, F.
3830   for (unsigned Half = 0; Half != 4; ++Half) {
3831     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3832       MatchB = true;
3833       break;
3834     }
3835   }
3836
3837   return MatchA && MatchB;
3838 }
3839
3840 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3841 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3842 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3843   MVT VT = SVOp->getValueType(0).getSimpleVT();
3844
3845   unsigned HalfSize = VT.getVectorNumElements()/2;
3846
3847   unsigned FstHalf = 0, SndHalf = 0;
3848   for (unsigned i = 0; i < HalfSize; ++i) {
3849     if (SVOp->getMaskElt(i) > 0) {
3850       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3851       break;
3852     }
3853   }
3854   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3855     if (SVOp->getMaskElt(i) > 0) {
3856       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3857       break;
3858     }
3859   }
3860
3861   return (FstHalf | (SndHalf << 4));
3862 }
3863
3864 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3865 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3866 /// Note that VPERMIL mask matching is different depending whether theunderlying
3867 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3868 /// to the same elements of the low, but to the higher half of the source.
3869 /// In VPERMILPD the two lanes could be shuffled independently of each other
3870 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3871 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3872   if (!HasFp256)
3873     return false;
3874
3875   unsigned NumElts = VT.getVectorNumElements();
3876   // Only match 256-bit with 32/64-bit types
3877   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3878     return false;
3879
3880   unsigned NumLanes = VT.getSizeInBits()/128;
3881   unsigned LaneSize = NumElts/NumLanes;
3882   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3883     for (unsigned i = 0; i != LaneSize; ++i) {
3884       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3885         return false;
3886       if (NumElts != 8 || l == 0)
3887         continue;
3888       // VPERMILPS handling
3889       if (Mask[i] < 0)
3890         continue;
3891       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3892         return false;
3893     }
3894   }
3895
3896   return true;
3897 }
3898
3899 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3900 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3901 /// element of vector 2 and the other elements to come from vector 1 in order.
3902 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3903                                bool V2IsSplat = false, bool V2IsUndef = false) {
3904   if (!VT.is128BitVector())
3905     return false;
3906
3907   unsigned NumOps = VT.getVectorNumElements();
3908   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3909     return false;
3910
3911   if (!isUndefOrEqual(Mask[0], 0))
3912     return false;
3913
3914   for (unsigned i = 1; i != NumOps; ++i)
3915     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3916           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3917           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3918       return false;
3919
3920   return true;
3921 }
3922
3923 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3924 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3925 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3926 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3927                            const X86Subtarget *Subtarget) {
3928   if (!Subtarget->hasSSE3())
3929     return false;
3930
3931   unsigned NumElems = VT.getVectorNumElements();
3932
3933   if ((VT.is128BitVector() && NumElems != 4) ||
3934       (VT.is256BitVector() && NumElems != 8))
3935     return false;
3936
3937   // "i+1" is the value the indexed mask element must have
3938   for (unsigned i = 0; i != NumElems; i += 2)
3939     if (!isUndefOrEqual(Mask[i], i+1) ||
3940         !isUndefOrEqual(Mask[i+1], i+1))
3941       return false;
3942
3943   return true;
3944 }
3945
3946 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3947 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3948 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3949 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3950                            const X86Subtarget *Subtarget) {
3951   if (!Subtarget->hasSSE3())
3952     return false;
3953
3954   unsigned NumElems = VT.getVectorNumElements();
3955
3956   if ((VT.is128BitVector() && NumElems != 4) ||
3957       (VT.is256BitVector() && NumElems != 8))
3958     return false;
3959
3960   // "i" is the value the indexed mask element must have
3961   for (unsigned i = 0; i != NumElems; i += 2)
3962     if (!isUndefOrEqual(Mask[i], i) ||
3963         !isUndefOrEqual(Mask[i+1], i))
3964       return false;
3965
3966   return true;
3967 }
3968
3969 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3970 /// specifies a shuffle of elements that is suitable for input to 256-bit
3971 /// version of MOVDDUP.
3972 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3973   if (!HasFp256 || !VT.is256BitVector())
3974     return false;
3975
3976   unsigned NumElts = VT.getVectorNumElements();
3977   if (NumElts != 4)
3978     return false;
3979
3980   for (unsigned i = 0; i != NumElts/2; ++i)
3981     if (!isUndefOrEqual(Mask[i], 0))
3982       return false;
3983   for (unsigned i = NumElts/2; i != NumElts; ++i)
3984     if (!isUndefOrEqual(Mask[i], NumElts/2))
3985       return false;
3986   return true;
3987 }
3988
3989 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3990 /// specifies a shuffle of elements that is suitable for input to 128-bit
3991 /// version of MOVDDUP.
3992 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3993   if (!VT.is128BitVector())
3994     return false;
3995
3996   unsigned e = VT.getVectorNumElements() / 2;
3997   for (unsigned i = 0; i != e; ++i)
3998     if (!isUndefOrEqual(Mask[i], i))
3999       return false;
4000   for (unsigned i = 0; i != e; ++i)
4001     if (!isUndefOrEqual(Mask[e+i], i))
4002       return false;
4003   return true;
4004 }
4005
4006 /// isVEXTRACTF128Index - Return true if the specified
4007 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4008 /// suitable for input to VEXTRACTF128.
4009 bool X86::isVEXTRACTF128Index(SDNode *N) {
4010   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4011     return false;
4012
4013   // The index should be aligned on a 128-bit boundary.
4014   uint64_t Index =
4015     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4016
4017   MVT VT = N->getValueType(0).getSimpleVT();
4018   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4019   bool Result = (Index * ElSize) % 128 == 0;
4020
4021   return Result;
4022 }
4023
4024 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4025 /// operand specifies a subvector insert that is suitable for input to
4026 /// VINSERTF128.
4027 bool X86::isVINSERTF128Index(SDNode *N) {
4028   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4029     return false;
4030
4031   // The index should be aligned on a 128-bit boundary.
4032   uint64_t Index =
4033     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4034
4035   MVT VT = N->getValueType(0).getSimpleVT();
4036   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4037   bool Result = (Index * ElSize) % 128 == 0;
4038
4039   return Result;
4040 }
4041
4042 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4043 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4044 /// Handles 128-bit and 256-bit.
4045 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4046   MVT VT = N->getValueType(0).getSimpleVT();
4047
4048   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4049          "Unsupported vector type for PSHUF/SHUFP");
4050
4051   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4052   // independently on 128-bit lanes.
4053   unsigned NumElts = VT.getVectorNumElements();
4054   unsigned NumLanes = VT.getSizeInBits()/128;
4055   unsigned NumLaneElts = NumElts/NumLanes;
4056
4057   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4058          "Only supports 2 or 4 elements per lane");
4059
4060   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4061   unsigned Mask = 0;
4062   for (unsigned i = 0; i != NumElts; ++i) {
4063     int Elt = N->getMaskElt(i);
4064     if (Elt < 0) continue;
4065     Elt &= NumLaneElts - 1;
4066     unsigned ShAmt = (i << Shift) % 8;
4067     Mask |= Elt << ShAmt;
4068   }
4069
4070   return Mask;
4071 }
4072
4073 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4074 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4075 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4076   MVT VT = N->getValueType(0).getSimpleVT();
4077
4078   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4079          "Unsupported vector type for PSHUFHW");
4080
4081   unsigned NumElts = VT.getVectorNumElements();
4082
4083   unsigned Mask = 0;
4084   for (unsigned l = 0; l != NumElts; l += 8) {
4085     // 8 nodes per lane, but we only care about the last 4.
4086     for (unsigned i = 0; i < 4; ++i) {
4087       int Elt = N->getMaskElt(l+i+4);
4088       if (Elt < 0) continue;
4089       Elt &= 0x3; // only 2-bits.
4090       Mask |= Elt << (i * 2);
4091     }
4092   }
4093
4094   return Mask;
4095 }
4096
4097 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4098 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4099 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4100   MVT VT = N->getValueType(0).getSimpleVT();
4101
4102   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4103          "Unsupported vector type for PSHUFHW");
4104
4105   unsigned NumElts = VT.getVectorNumElements();
4106
4107   unsigned Mask = 0;
4108   for (unsigned l = 0; l != NumElts; l += 8) {
4109     // 8 nodes per lane, but we only care about the first 4.
4110     for (unsigned i = 0; i < 4; ++i) {
4111       int Elt = N->getMaskElt(l+i);
4112       if (Elt < 0) continue;
4113       Elt &= 0x3; // only 2-bits
4114       Mask |= Elt << (i * 2);
4115     }
4116   }
4117
4118   return Mask;
4119 }
4120
4121 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4122 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4123 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4124   MVT VT = SVOp->getValueType(0).getSimpleVT();
4125   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4126
4127   unsigned NumElts = VT.getVectorNumElements();
4128   unsigned NumLanes = VT.getSizeInBits()/128;
4129   unsigned NumLaneElts = NumElts/NumLanes;
4130
4131   int Val = 0;
4132   unsigned i;
4133   for (i = 0; i != NumElts; ++i) {
4134     Val = SVOp->getMaskElt(i);
4135     if (Val >= 0)
4136       break;
4137   }
4138   if (Val >= (int)NumElts)
4139     Val -= NumElts - NumLaneElts;
4140
4141   assert(Val - i > 0 && "PALIGNR imm should be positive");
4142   return (Val - i) * EltSize;
4143 }
4144
4145 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4146 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4147 /// instructions.
4148 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4149   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4150     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4151
4152   uint64_t Index =
4153     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4154
4155   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4156   MVT ElVT = VecVT.getVectorElementType();
4157
4158   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4159   return Index / NumElemsPerChunk;
4160 }
4161
4162 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4163 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4164 /// instructions.
4165 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4166   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4167     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4168
4169   uint64_t Index =
4170     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4171
4172   MVT VecVT = N->getValueType(0).getSimpleVT();
4173   MVT ElVT = VecVT.getVectorElementType();
4174
4175   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4176   return Index / NumElemsPerChunk;
4177 }
4178
4179 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4180 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4181 /// Handles 256-bit.
4182 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4183   MVT VT = N->getValueType(0).getSimpleVT();
4184
4185   unsigned NumElts = VT.getVectorNumElements();
4186
4187   assert((VT.is256BitVector() && NumElts == 4) &&
4188          "Unsupported vector type for VPERMQ/VPERMPD");
4189
4190   unsigned Mask = 0;
4191   for (unsigned i = 0; i != NumElts; ++i) {
4192     int Elt = N->getMaskElt(i);
4193     if (Elt < 0)
4194       continue;
4195     Mask |= Elt << (i*2);
4196   }
4197
4198   return Mask;
4199 }
4200 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4201 /// constant +0.0.
4202 bool X86::isZeroNode(SDValue Elt) {
4203   return ((isa<ConstantSDNode>(Elt) &&
4204            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4205           (isa<ConstantFPSDNode>(Elt) &&
4206            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4207 }
4208
4209 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4210 /// their permute mask.
4211 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4212                                     SelectionDAG &DAG) {
4213   MVT VT = SVOp->getValueType(0).getSimpleVT();
4214   unsigned NumElems = VT.getVectorNumElements();
4215   SmallVector<int, 8> MaskVec;
4216
4217   for (unsigned i = 0; i != NumElems; ++i) {
4218     int Idx = SVOp->getMaskElt(i);
4219     if (Idx >= 0) {
4220       if (Idx < (int)NumElems)
4221         Idx += NumElems;
4222       else
4223         Idx -= NumElems;
4224     }
4225     MaskVec.push_back(Idx);
4226   }
4227   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4228                               SVOp->getOperand(0), &MaskVec[0]);
4229 }
4230
4231 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4232 /// match movhlps. The lower half elements should come from upper half of
4233 /// V1 (and in order), and the upper half elements should come from the upper
4234 /// half of V2 (and in order).
4235 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4236   if (!VT.is128BitVector())
4237     return false;
4238   if (VT.getVectorNumElements() != 4)
4239     return false;
4240   for (unsigned i = 0, e = 2; i != e; ++i)
4241     if (!isUndefOrEqual(Mask[i], i+2))
4242       return false;
4243   for (unsigned i = 2; i != 4; ++i)
4244     if (!isUndefOrEqual(Mask[i], i+4))
4245       return false;
4246   return true;
4247 }
4248
4249 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4250 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4251 /// required.
4252 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4253   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4254     return false;
4255   N = N->getOperand(0).getNode();
4256   if (!ISD::isNON_EXTLoad(N))
4257     return false;
4258   if (LD)
4259     *LD = cast<LoadSDNode>(N);
4260   return true;
4261 }
4262
4263 // Test whether the given value is a vector value which will be legalized
4264 // into a load.
4265 static bool WillBeConstantPoolLoad(SDNode *N) {
4266   if (N->getOpcode() != ISD::BUILD_VECTOR)
4267     return false;
4268
4269   // Check for any non-constant elements.
4270   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4271     switch (N->getOperand(i).getNode()->getOpcode()) {
4272     case ISD::UNDEF:
4273     case ISD::ConstantFP:
4274     case ISD::Constant:
4275       break;
4276     default:
4277       return false;
4278     }
4279
4280   // Vectors of all-zeros and all-ones are materialized with special
4281   // instructions rather than being loaded.
4282   return !ISD::isBuildVectorAllZeros(N) &&
4283          !ISD::isBuildVectorAllOnes(N);
4284 }
4285
4286 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4287 /// match movlp{s|d}. The lower half elements should come from lower half of
4288 /// V1 (and in order), and the upper half elements should come from the upper
4289 /// half of V2 (and in order). And since V1 will become the source of the
4290 /// MOVLP, it must be either a vector load or a scalar load to vector.
4291 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4292                                ArrayRef<int> Mask, EVT VT) {
4293   if (!VT.is128BitVector())
4294     return false;
4295
4296   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4297     return false;
4298   // Is V2 is a vector load, don't do this transformation. We will try to use
4299   // load folding shufps op.
4300   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4301     return false;
4302
4303   unsigned NumElems = VT.getVectorNumElements();
4304
4305   if (NumElems != 2 && NumElems != 4)
4306     return false;
4307   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4308     if (!isUndefOrEqual(Mask[i], i))
4309       return false;
4310   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4311     if (!isUndefOrEqual(Mask[i], i+NumElems))
4312       return false;
4313   return true;
4314 }
4315
4316 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4317 /// all the same.
4318 static bool isSplatVector(SDNode *N) {
4319   if (N->getOpcode() != ISD::BUILD_VECTOR)
4320     return false;
4321
4322   SDValue SplatValue = N->getOperand(0);
4323   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4324     if (N->getOperand(i) != SplatValue)
4325       return false;
4326   return true;
4327 }
4328
4329 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4330 /// to an zero vector.
4331 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4332 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4333   SDValue V1 = N->getOperand(0);
4334   SDValue V2 = N->getOperand(1);
4335   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4336   for (unsigned i = 0; i != NumElems; ++i) {
4337     int Idx = N->getMaskElt(i);
4338     if (Idx >= (int)NumElems) {
4339       unsigned Opc = V2.getOpcode();
4340       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4341         continue;
4342       if (Opc != ISD::BUILD_VECTOR ||
4343           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4344         return false;
4345     } else if (Idx >= 0) {
4346       unsigned Opc = V1.getOpcode();
4347       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4348         continue;
4349       if (Opc != ISD::BUILD_VECTOR ||
4350           !X86::isZeroNode(V1.getOperand(Idx)))
4351         return false;
4352     }
4353   }
4354   return true;
4355 }
4356
4357 /// getZeroVector - Returns a vector of specified type with all zero elements.
4358 ///
4359 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4360                              SelectionDAG &DAG, DebugLoc dl) {
4361   assert(VT.isVector() && "Expected a vector type");
4362
4363   // Always build SSE zero vectors as <4 x i32> bitcasted
4364   // to their dest type. This ensures they get CSE'd.
4365   SDValue Vec;
4366   if (VT.is128BitVector()) {  // SSE
4367     if (Subtarget->hasSSE2()) {  // SSE2
4368       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4369       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4370     } else { // SSE1
4371       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4372       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4373     }
4374   } else if (VT.is256BitVector()) { // AVX
4375     if (Subtarget->hasInt256()) { // AVX2
4376       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4377       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4378       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4379     } else {
4380       // 256-bit logic and arithmetic instructions in AVX are all
4381       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4382       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4383       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4384       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4385     }
4386   } else
4387     llvm_unreachable("Unexpected vector type");
4388
4389   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4390 }
4391
4392 /// getOnesVector - Returns a vector of specified type with all bits set.
4393 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4394 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4395 /// Then bitcast to their original type, ensuring they get CSE'd.
4396 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4397                              DebugLoc dl) {
4398   assert(VT.isVector() && "Expected a vector type");
4399
4400   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4401   SDValue Vec;
4402   if (VT.is256BitVector()) {
4403     if (HasInt256) { // AVX2
4404       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4405       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4406     } else { // AVX
4407       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4408       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4409     }
4410   } else if (VT.is128BitVector()) {
4411     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4412   } else
4413     llvm_unreachable("Unexpected vector type");
4414
4415   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4416 }
4417
4418 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4419 /// that point to V2 points to its first element.
4420 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4421   for (unsigned i = 0; i != NumElems; ++i) {
4422     if (Mask[i] > (int)NumElems) {
4423       Mask[i] = NumElems;
4424     }
4425   }
4426 }
4427
4428 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4429 /// operation of specified width.
4430 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4431                        SDValue V2) {
4432   unsigned NumElems = VT.getVectorNumElements();
4433   SmallVector<int, 8> Mask;
4434   Mask.push_back(NumElems);
4435   for (unsigned i = 1; i != NumElems; ++i)
4436     Mask.push_back(i);
4437   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4438 }
4439
4440 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4441 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4442                           SDValue V2) {
4443   unsigned NumElems = VT.getVectorNumElements();
4444   SmallVector<int, 8> Mask;
4445   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4446     Mask.push_back(i);
4447     Mask.push_back(i + NumElems);
4448   }
4449   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4450 }
4451
4452 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4453 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4454                           SDValue V2) {
4455   unsigned NumElems = VT.getVectorNumElements();
4456   SmallVector<int, 8> Mask;
4457   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4458     Mask.push_back(i + Half);
4459     Mask.push_back(i + NumElems + Half);
4460   }
4461   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4462 }
4463
4464 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4465 // a generic shuffle instruction because the target has no such instructions.
4466 // Generate shuffles which repeat i16 and i8 several times until they can be
4467 // represented by v4f32 and then be manipulated by target suported shuffles.
4468 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4469   EVT VT = V.getValueType();
4470   int NumElems = VT.getVectorNumElements();
4471   DebugLoc dl = V.getDebugLoc();
4472
4473   while (NumElems > 4) {
4474     if (EltNo < NumElems/2) {
4475       V = getUnpackl(DAG, dl, VT, V, V);
4476     } else {
4477       V = getUnpackh(DAG, dl, VT, V, V);
4478       EltNo -= NumElems/2;
4479     }
4480     NumElems >>= 1;
4481   }
4482   return V;
4483 }
4484
4485 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4486 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4487   EVT VT = V.getValueType();
4488   DebugLoc dl = V.getDebugLoc();
4489
4490   if (VT.is128BitVector()) {
4491     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4492     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4493     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4494                              &SplatMask[0]);
4495   } else if (VT.is256BitVector()) {
4496     // To use VPERMILPS to splat scalars, the second half of indicies must
4497     // refer to the higher part, which is a duplication of the lower one,
4498     // because VPERMILPS can only handle in-lane permutations.
4499     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4500                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4501
4502     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4503     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4504                              &SplatMask[0]);
4505   } else
4506     llvm_unreachable("Vector size not supported");
4507
4508   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4509 }
4510
4511 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4512 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4513   EVT SrcVT = SV->getValueType(0);
4514   SDValue V1 = SV->getOperand(0);
4515   DebugLoc dl = SV->getDebugLoc();
4516
4517   int EltNo = SV->getSplatIndex();
4518   int NumElems = SrcVT.getVectorNumElements();
4519   bool Is256BitVec = SrcVT.is256BitVector();
4520
4521   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4522          "Unknown how to promote splat for type");
4523
4524   // Extract the 128-bit part containing the splat element and update
4525   // the splat element index when it refers to the higher register.
4526   if (Is256BitVec) {
4527     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4528     if (EltNo >= NumElems/2)
4529       EltNo -= NumElems/2;
4530   }
4531
4532   // All i16 and i8 vector types can't be used directly by a generic shuffle
4533   // instruction because the target has no such instruction. Generate shuffles
4534   // which repeat i16 and i8 several times until they fit in i32, and then can
4535   // be manipulated by target suported shuffles.
4536   EVT EltVT = SrcVT.getVectorElementType();
4537   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4538     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4539
4540   // Recreate the 256-bit vector and place the same 128-bit vector
4541   // into the low and high part. This is necessary because we want
4542   // to use VPERM* to shuffle the vectors
4543   if (Is256BitVec) {
4544     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4545   }
4546
4547   return getLegalSplat(DAG, V1, EltNo);
4548 }
4549
4550 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4551 /// vector of zero or undef vector.  This produces a shuffle where the low
4552 /// element of V2 is swizzled into the zero/undef vector, landing at element
4553 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4554 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4555                                            bool IsZero,
4556                                            const X86Subtarget *Subtarget,
4557                                            SelectionDAG &DAG) {
4558   EVT VT = V2.getValueType();
4559   SDValue V1 = IsZero
4560     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4561   unsigned NumElems = VT.getVectorNumElements();
4562   SmallVector<int, 16> MaskVec;
4563   for (unsigned i = 0; i != NumElems; ++i)
4564     // If this is the insertion idx, put the low elt of V2 here.
4565     MaskVec.push_back(i == Idx ? NumElems : i);
4566   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4567 }
4568
4569 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4570 /// target specific opcode. Returns true if the Mask could be calculated.
4571 /// Sets IsUnary to true if only uses one source.
4572 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4573                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4574   unsigned NumElems = VT.getVectorNumElements();
4575   SDValue ImmN;
4576
4577   IsUnary = false;
4578   switch(N->getOpcode()) {
4579   case X86ISD::SHUFP:
4580     ImmN = N->getOperand(N->getNumOperands()-1);
4581     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4582     break;
4583   case X86ISD::UNPCKH:
4584     DecodeUNPCKHMask(VT, Mask);
4585     break;
4586   case X86ISD::UNPCKL:
4587     DecodeUNPCKLMask(VT, Mask);
4588     break;
4589   case X86ISD::MOVHLPS:
4590     DecodeMOVHLPSMask(NumElems, Mask);
4591     break;
4592   case X86ISD::MOVLHPS:
4593     DecodeMOVLHPSMask(NumElems, Mask);
4594     break;
4595   case X86ISD::PALIGNR:
4596     ImmN = N->getOperand(N->getNumOperands()-1);
4597     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4598     break;
4599   case X86ISD::PSHUFD:
4600   case X86ISD::VPERMILP:
4601     ImmN = N->getOperand(N->getNumOperands()-1);
4602     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4603     IsUnary = true;
4604     break;
4605   case X86ISD::PSHUFHW:
4606     ImmN = N->getOperand(N->getNumOperands()-1);
4607     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4608     IsUnary = true;
4609     break;
4610   case X86ISD::PSHUFLW:
4611     ImmN = N->getOperand(N->getNumOperands()-1);
4612     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4613     IsUnary = true;
4614     break;
4615   case X86ISD::VPERMI:
4616     ImmN = N->getOperand(N->getNumOperands()-1);
4617     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4618     IsUnary = true;
4619     break;
4620   case X86ISD::MOVSS:
4621   case X86ISD::MOVSD: {
4622     // The index 0 always comes from the first element of the second source,
4623     // this is why MOVSS and MOVSD are used in the first place. The other
4624     // elements come from the other positions of the first source vector
4625     Mask.push_back(NumElems);
4626     for (unsigned i = 1; i != NumElems; ++i) {
4627       Mask.push_back(i);
4628     }
4629     break;
4630   }
4631   case X86ISD::VPERM2X128:
4632     ImmN = N->getOperand(N->getNumOperands()-1);
4633     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4634     if (Mask.empty()) return false;
4635     break;
4636   case X86ISD::MOVDDUP:
4637   case X86ISD::MOVLHPD:
4638   case X86ISD::MOVLPD:
4639   case X86ISD::MOVLPS:
4640   case X86ISD::MOVSHDUP:
4641   case X86ISD::MOVSLDUP:
4642     // Not yet implemented
4643     return false;
4644   default: llvm_unreachable("unknown target shuffle node");
4645   }
4646
4647   return true;
4648 }
4649
4650 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4651 /// element of the result of the vector shuffle.
4652 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4653                                    unsigned Depth) {
4654   if (Depth == 6)
4655     return SDValue();  // Limit search depth.
4656
4657   SDValue V = SDValue(N, 0);
4658   EVT VT = V.getValueType();
4659   unsigned Opcode = V.getOpcode();
4660
4661   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4662   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4663     int Elt = SV->getMaskElt(Index);
4664
4665     if (Elt < 0)
4666       return DAG.getUNDEF(VT.getVectorElementType());
4667
4668     unsigned NumElems = VT.getVectorNumElements();
4669     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4670                                          : SV->getOperand(1);
4671     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4672   }
4673
4674   // Recurse into target specific vector shuffles to find scalars.
4675   if (isTargetShuffle(Opcode)) {
4676     MVT ShufVT = V.getValueType().getSimpleVT();
4677     unsigned NumElems = ShufVT.getVectorNumElements();
4678     SmallVector<int, 16> ShuffleMask;
4679     bool IsUnary;
4680
4681     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4682       return SDValue();
4683
4684     int Elt = ShuffleMask[Index];
4685     if (Elt < 0)
4686       return DAG.getUNDEF(ShufVT.getVectorElementType());
4687
4688     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4689                                          : N->getOperand(1);
4690     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4691                                Depth+1);
4692   }
4693
4694   // Actual nodes that may contain scalar elements
4695   if (Opcode == ISD::BITCAST) {
4696     V = V.getOperand(0);
4697     EVT SrcVT = V.getValueType();
4698     unsigned NumElems = VT.getVectorNumElements();
4699
4700     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4701       return SDValue();
4702   }
4703
4704   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4705     return (Index == 0) ? V.getOperand(0)
4706                         : DAG.getUNDEF(VT.getVectorElementType());
4707
4708   if (V.getOpcode() == ISD::BUILD_VECTOR)
4709     return V.getOperand(Index);
4710
4711   return SDValue();
4712 }
4713
4714 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4715 /// shuffle operation which come from a consecutively from a zero. The
4716 /// search can start in two different directions, from left or right.
4717 static
4718 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4719                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4720   unsigned i;
4721   for (i = 0; i != NumElems; ++i) {
4722     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4723     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4724     if (!(Elt.getNode() &&
4725          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4726       break;
4727   }
4728
4729   return i;
4730 }
4731
4732 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4733 /// correspond consecutively to elements from one of the vector operands,
4734 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4735 static
4736 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4737                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4738                               unsigned NumElems, unsigned &OpNum) {
4739   bool SeenV1 = false;
4740   bool SeenV2 = false;
4741
4742   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4743     int Idx = SVOp->getMaskElt(i);
4744     // Ignore undef indicies
4745     if (Idx < 0)
4746       continue;
4747
4748     if (Idx < (int)NumElems)
4749       SeenV1 = true;
4750     else
4751       SeenV2 = true;
4752
4753     // Only accept consecutive elements from the same vector
4754     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4755       return false;
4756   }
4757
4758   OpNum = SeenV1 ? 0 : 1;
4759   return true;
4760 }
4761
4762 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4763 /// logical left shift of a vector.
4764 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4765                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4766   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4767   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4768               false /* check zeros from right */, DAG);
4769   unsigned OpSrc;
4770
4771   if (!NumZeros)
4772     return false;
4773
4774   // Considering the elements in the mask that are not consecutive zeros,
4775   // check if they consecutively come from only one of the source vectors.
4776   //
4777   //               V1 = {X, A, B, C}     0
4778   //                         \  \  \    /
4779   //   vector_shuffle V1, V2 <1, 2, 3, X>
4780   //
4781   if (!isShuffleMaskConsecutive(SVOp,
4782             0,                   // Mask Start Index
4783             NumElems-NumZeros,   // Mask End Index(exclusive)
4784             NumZeros,            // Where to start looking in the src vector
4785             NumElems,            // Number of elements in vector
4786             OpSrc))              // Which source operand ?
4787     return false;
4788
4789   isLeft = false;
4790   ShAmt = NumZeros;
4791   ShVal = SVOp->getOperand(OpSrc);
4792   return true;
4793 }
4794
4795 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4796 /// logical left shift of a vector.
4797 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4798                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4799   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4800   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4801               true /* check zeros from left */, DAG);
4802   unsigned OpSrc;
4803
4804   if (!NumZeros)
4805     return false;
4806
4807   // Considering the elements in the mask that are not consecutive zeros,
4808   // check if they consecutively come from only one of the source vectors.
4809   //
4810   //                           0    { A, B, X, X } = V2
4811   //                          / \    /  /
4812   //   vector_shuffle V1, V2 <X, X, 4, 5>
4813   //
4814   if (!isShuffleMaskConsecutive(SVOp,
4815             NumZeros,     // Mask Start Index
4816             NumElems,     // Mask End Index(exclusive)
4817             0,            // Where to start looking in the src vector
4818             NumElems,     // Number of elements in vector
4819             OpSrc))       // Which source operand ?
4820     return false;
4821
4822   isLeft = true;
4823   ShAmt = NumZeros;
4824   ShVal = SVOp->getOperand(OpSrc);
4825   return true;
4826 }
4827
4828 /// isVectorShift - Returns true if the shuffle can be implemented as a
4829 /// logical left or right shift of a vector.
4830 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4831                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4832   // Although the logic below support any bitwidth size, there are no
4833   // shift instructions which handle more than 128-bit vectors.
4834   if (!SVOp->getValueType(0).is128BitVector())
4835     return false;
4836
4837   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4838       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4839     return true;
4840
4841   return false;
4842 }
4843
4844 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4845 ///
4846 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4847                                        unsigned NumNonZero, unsigned NumZero,
4848                                        SelectionDAG &DAG,
4849                                        const X86Subtarget* Subtarget,
4850                                        const TargetLowering &TLI) {
4851   if (NumNonZero > 8)
4852     return SDValue();
4853
4854   DebugLoc dl = Op.getDebugLoc();
4855   SDValue V(0, 0);
4856   bool First = true;
4857   for (unsigned i = 0; i < 16; ++i) {
4858     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4859     if (ThisIsNonZero && First) {
4860       if (NumZero)
4861         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4862       else
4863         V = DAG.getUNDEF(MVT::v8i16);
4864       First = false;
4865     }
4866
4867     if ((i & 1) != 0) {
4868       SDValue ThisElt(0, 0), LastElt(0, 0);
4869       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4870       if (LastIsNonZero) {
4871         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4872                               MVT::i16, Op.getOperand(i-1));
4873       }
4874       if (ThisIsNonZero) {
4875         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4876         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4877                               ThisElt, DAG.getConstant(8, MVT::i8));
4878         if (LastIsNonZero)
4879           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4880       } else
4881         ThisElt = LastElt;
4882
4883       if (ThisElt.getNode())
4884         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4885                         DAG.getIntPtrConstant(i/2));
4886     }
4887   }
4888
4889   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4890 }
4891
4892 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4893 ///
4894 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4895                                      unsigned NumNonZero, unsigned NumZero,
4896                                      SelectionDAG &DAG,
4897                                      const X86Subtarget* Subtarget,
4898                                      const TargetLowering &TLI) {
4899   if (NumNonZero > 4)
4900     return SDValue();
4901
4902   DebugLoc dl = Op.getDebugLoc();
4903   SDValue V(0, 0);
4904   bool First = true;
4905   for (unsigned i = 0; i < 8; ++i) {
4906     bool isNonZero = (NonZeros & (1 << i)) != 0;
4907     if (isNonZero) {
4908       if (First) {
4909         if (NumZero)
4910           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4911         else
4912           V = DAG.getUNDEF(MVT::v8i16);
4913         First = false;
4914       }
4915       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4916                       MVT::v8i16, V, Op.getOperand(i),
4917                       DAG.getIntPtrConstant(i));
4918     }
4919   }
4920
4921   return V;
4922 }
4923
4924 /// getVShift - Return a vector logical shift node.
4925 ///
4926 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4927                          unsigned NumBits, SelectionDAG &DAG,
4928                          const TargetLowering &TLI, DebugLoc dl) {
4929   assert(VT.is128BitVector() && "Unknown type for VShift");
4930   EVT ShVT = MVT::v2i64;
4931   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4932   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4933   return DAG.getNode(ISD::BITCAST, dl, VT,
4934                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4935                              DAG.getConstant(NumBits,
4936                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4937 }
4938
4939 SDValue
4940 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4941                                           SelectionDAG &DAG) const {
4942
4943   // Check if the scalar load can be widened into a vector load. And if
4944   // the address is "base + cst" see if the cst can be "absorbed" into
4945   // the shuffle mask.
4946   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4947     SDValue Ptr = LD->getBasePtr();
4948     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4949       return SDValue();
4950     EVT PVT = LD->getValueType(0);
4951     if (PVT != MVT::i32 && PVT != MVT::f32)
4952       return SDValue();
4953
4954     int FI = -1;
4955     int64_t Offset = 0;
4956     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4957       FI = FINode->getIndex();
4958       Offset = 0;
4959     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4960                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4961       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4962       Offset = Ptr.getConstantOperandVal(1);
4963       Ptr = Ptr.getOperand(0);
4964     } else {
4965       return SDValue();
4966     }
4967
4968     // FIXME: 256-bit vector instructions don't require a strict alignment,
4969     // improve this code to support it better.
4970     unsigned RequiredAlign = VT.getSizeInBits()/8;
4971     SDValue Chain = LD->getChain();
4972     // Make sure the stack object alignment is at least 16 or 32.
4973     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4974     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4975       if (MFI->isFixedObjectIndex(FI)) {
4976         // Can't change the alignment. FIXME: It's possible to compute
4977         // the exact stack offset and reference FI + adjust offset instead.
4978         // If someone *really* cares about this. That's the way to implement it.
4979         return SDValue();
4980       } else {
4981         MFI->setObjectAlignment(FI, RequiredAlign);
4982       }
4983     }
4984
4985     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4986     // Ptr + (Offset & ~15).
4987     if (Offset < 0)
4988       return SDValue();
4989     if ((Offset % RequiredAlign) & 3)
4990       return SDValue();
4991     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4992     if (StartOffset)
4993       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4994                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4995
4996     int EltNo = (Offset - StartOffset) >> 2;
4997     unsigned NumElems = VT.getVectorNumElements();
4998
4999     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5000     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5001                              LD->getPointerInfo().getWithOffset(StartOffset),
5002                              false, false, false, 0);
5003
5004     SmallVector<int, 8> Mask;
5005     for (unsigned i = 0; i != NumElems; ++i)
5006       Mask.push_back(EltNo);
5007
5008     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5009   }
5010
5011   return SDValue();
5012 }
5013
5014 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5015 /// vector of type 'VT', see if the elements can be replaced by a single large
5016 /// load which has the same value as a build_vector whose operands are 'elts'.
5017 ///
5018 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5019 ///
5020 /// FIXME: we'd also like to handle the case where the last elements are zero
5021 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5022 /// There's even a handy isZeroNode for that purpose.
5023 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5024                                         DebugLoc &DL, SelectionDAG &DAG) {
5025   EVT EltVT = VT.getVectorElementType();
5026   unsigned NumElems = Elts.size();
5027
5028   LoadSDNode *LDBase = NULL;
5029   unsigned LastLoadedElt = -1U;
5030
5031   // For each element in the initializer, see if we've found a load or an undef.
5032   // If we don't find an initial load element, or later load elements are
5033   // non-consecutive, bail out.
5034   for (unsigned i = 0; i < NumElems; ++i) {
5035     SDValue Elt = Elts[i];
5036
5037     if (!Elt.getNode() ||
5038         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5039       return SDValue();
5040     if (!LDBase) {
5041       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5042         return SDValue();
5043       LDBase = cast<LoadSDNode>(Elt.getNode());
5044       LastLoadedElt = i;
5045       continue;
5046     }
5047     if (Elt.getOpcode() == ISD::UNDEF)
5048       continue;
5049
5050     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5051     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5052       return SDValue();
5053     LastLoadedElt = i;
5054   }
5055
5056   // If we have found an entire vector of loads and undefs, then return a large
5057   // load of the entire vector width starting at the base pointer.  If we found
5058   // consecutive loads for the low half, generate a vzext_load node.
5059   if (LastLoadedElt == NumElems - 1) {
5060     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5061       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5062                          LDBase->getPointerInfo(),
5063                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5064                          LDBase->isInvariant(), 0);
5065     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5066                        LDBase->getPointerInfo(),
5067                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5068                        LDBase->isInvariant(), LDBase->getAlignment());
5069   }
5070   if (NumElems == 4 && LastLoadedElt == 1 &&
5071       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5072     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5073     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5074     SDValue ResNode =
5075         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5076                                 LDBase->getPointerInfo(),
5077                                 LDBase->getAlignment(),
5078                                 false/*isVolatile*/, true/*ReadMem*/,
5079                                 false/*WriteMem*/);
5080
5081     // Make sure the newly-created LOAD is in the same position as LDBase in
5082     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5083     // update uses of LDBase's output chain to use the TokenFactor.
5084     if (LDBase->hasAnyUseOfValue(1)) {
5085       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5086                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5087       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5088       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5089                              SDValue(ResNode.getNode(), 1));
5090     }
5091
5092     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5093   }
5094   return SDValue();
5095 }
5096
5097 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5098 /// to generate a splat value for the following cases:
5099 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5100 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5101 /// a scalar load, or a constant.
5102 /// The VBROADCAST node is returned when a pattern is found,
5103 /// or SDValue() otherwise.
5104 SDValue
5105 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5106   if (!Subtarget->hasFp256())
5107     return SDValue();
5108
5109   MVT VT = Op.getValueType().getSimpleVT();
5110   DebugLoc dl = Op.getDebugLoc();
5111
5112   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5113          "Unsupported vector type for broadcast.");
5114
5115   SDValue Ld;
5116   bool ConstSplatVal;
5117
5118   switch (Op.getOpcode()) {
5119     default:
5120       // Unknown pattern found.
5121       return SDValue();
5122
5123     case ISD::BUILD_VECTOR: {
5124       // The BUILD_VECTOR node must be a splat.
5125       if (!isSplatVector(Op.getNode()))
5126         return SDValue();
5127
5128       Ld = Op.getOperand(0);
5129       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5130                      Ld.getOpcode() == ISD::ConstantFP);
5131
5132       // The suspected load node has several users. Make sure that all
5133       // of its users are from the BUILD_VECTOR node.
5134       // Constants may have multiple users.
5135       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5136         return SDValue();
5137       break;
5138     }
5139
5140     case ISD::VECTOR_SHUFFLE: {
5141       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5142
5143       // Shuffles must have a splat mask where the first element is
5144       // broadcasted.
5145       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5146         return SDValue();
5147
5148       SDValue Sc = Op.getOperand(0);
5149       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5150           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5151
5152         if (!Subtarget->hasInt256())
5153           return SDValue();
5154
5155         // Use the register form of the broadcast instruction available on AVX2.
5156         if (VT.is256BitVector())
5157           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5158         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5159       }
5160
5161       Ld = Sc.getOperand(0);
5162       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5163                        Ld.getOpcode() == ISD::ConstantFP);
5164
5165       // The scalar_to_vector node and the suspected
5166       // load node must have exactly one user.
5167       // Constants may have multiple users.
5168       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5169         return SDValue();
5170       break;
5171     }
5172   }
5173
5174   bool Is256 = VT.is256BitVector();
5175
5176   // Handle the broadcasting a single constant scalar from the constant pool
5177   // into a vector. On Sandybridge it is still better to load a constant vector
5178   // from the constant pool and not to broadcast it from a scalar.
5179   if (ConstSplatVal && Subtarget->hasInt256()) {
5180     EVT CVT = Ld.getValueType();
5181     assert(!CVT.isVector() && "Must not broadcast a vector type");
5182     unsigned ScalarSize = CVT.getSizeInBits();
5183
5184     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5185       const Constant *C = 0;
5186       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5187         C = CI->getConstantIntValue();
5188       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5189         C = CF->getConstantFPValue();
5190
5191       assert(C && "Invalid constant type");
5192
5193       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5194       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5195       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5196                        MachinePointerInfo::getConstantPool(),
5197                        false, false, false, Alignment);
5198
5199       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5200     }
5201   }
5202
5203   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5204   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5205
5206   // Handle AVX2 in-register broadcasts.
5207   if (!IsLoad && Subtarget->hasInt256() &&
5208       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5209     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5210
5211   // The scalar source must be a normal load.
5212   if (!IsLoad)
5213     return SDValue();
5214
5215   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5216     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5217
5218   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5219   // double since there is no vbroadcastsd xmm
5220   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5221     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5222       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5223   }
5224
5225   // Unsupported broadcast.
5226   return SDValue();
5227 }
5228
5229 SDValue
5230 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5231   EVT VT = Op.getValueType();
5232
5233   // Skip if insert_vec_elt is not supported.
5234   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5235     return SDValue();
5236
5237   DebugLoc DL = Op.getDebugLoc();
5238   unsigned NumElems = Op.getNumOperands();
5239
5240   SDValue VecIn1;
5241   SDValue VecIn2;
5242   SmallVector<unsigned, 4> InsertIndices;
5243   SmallVector<int, 8> Mask(NumElems, -1);
5244
5245   for (unsigned i = 0; i != NumElems; ++i) {
5246     unsigned Opc = Op.getOperand(i).getOpcode();
5247
5248     if (Opc == ISD::UNDEF)
5249       continue;
5250
5251     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5252       // Quit if more than 1 elements need inserting.
5253       if (InsertIndices.size() > 1)
5254         return SDValue();
5255
5256       InsertIndices.push_back(i);
5257       continue;
5258     }
5259
5260     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5261     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5262
5263     // Quit if extracted from vector of different type.
5264     if (ExtractedFromVec.getValueType() != VT)
5265       return SDValue();
5266
5267     // Quit if non-constant index.
5268     if (!isa<ConstantSDNode>(ExtIdx))
5269       return SDValue();
5270
5271     if (VecIn1.getNode() == 0)
5272       VecIn1 = ExtractedFromVec;
5273     else if (VecIn1 != ExtractedFromVec) {
5274       if (VecIn2.getNode() == 0)
5275         VecIn2 = ExtractedFromVec;
5276       else if (VecIn2 != ExtractedFromVec)
5277         // Quit if more than 2 vectors to shuffle
5278         return SDValue();
5279     }
5280
5281     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5282
5283     if (ExtractedFromVec == VecIn1)
5284       Mask[i] = Idx;
5285     else if (ExtractedFromVec == VecIn2)
5286       Mask[i] = Idx + NumElems;
5287   }
5288
5289   if (VecIn1.getNode() == 0)
5290     return SDValue();
5291
5292   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5293   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5294   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5295     unsigned Idx = InsertIndices[i];
5296     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5297                      DAG.getIntPtrConstant(Idx));
5298   }
5299
5300   return NV;
5301 }
5302
5303 SDValue
5304 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5305   DebugLoc dl = Op.getDebugLoc();
5306
5307   MVT VT = Op.getValueType().getSimpleVT();
5308   MVT ExtVT = VT.getVectorElementType();
5309   unsigned NumElems = Op.getNumOperands();
5310
5311   // Vectors containing all zeros can be matched by pxor and xorps later
5312   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5313     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5314     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5315     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5316       return Op;
5317
5318     return getZeroVector(VT, Subtarget, DAG, dl);
5319   }
5320
5321   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5322   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5323   // vpcmpeqd on 256-bit vectors.
5324   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5325     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5326       return Op;
5327
5328     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5329   }
5330
5331   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5332   if (Broadcast.getNode())
5333     return Broadcast;
5334
5335   unsigned EVTBits = ExtVT.getSizeInBits();
5336
5337   unsigned NumZero  = 0;
5338   unsigned NumNonZero = 0;
5339   unsigned NonZeros = 0;
5340   bool IsAllConstants = true;
5341   SmallSet<SDValue, 8> Values;
5342   for (unsigned i = 0; i < NumElems; ++i) {
5343     SDValue Elt = Op.getOperand(i);
5344     if (Elt.getOpcode() == ISD::UNDEF)
5345       continue;
5346     Values.insert(Elt);
5347     if (Elt.getOpcode() != ISD::Constant &&
5348         Elt.getOpcode() != ISD::ConstantFP)
5349       IsAllConstants = false;
5350     if (X86::isZeroNode(Elt))
5351       NumZero++;
5352     else {
5353       NonZeros |= (1 << i);
5354       NumNonZero++;
5355     }
5356   }
5357
5358   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5359   if (NumNonZero == 0)
5360     return DAG.getUNDEF(VT);
5361
5362   // Special case for single non-zero, non-undef, element.
5363   if (NumNonZero == 1) {
5364     unsigned Idx = CountTrailingZeros_32(NonZeros);
5365     SDValue Item = Op.getOperand(Idx);
5366
5367     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5368     // the value are obviously zero, truncate the value to i32 and do the
5369     // insertion that way.  Only do this if the value is non-constant or if the
5370     // value is a constant being inserted into element 0.  It is cheaper to do
5371     // a constant pool load than it is to do a movd + shuffle.
5372     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5373         (!IsAllConstants || Idx == 0)) {
5374       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5375         // Handle SSE only.
5376         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5377         EVT VecVT = MVT::v4i32;
5378         unsigned VecElts = 4;
5379
5380         // Truncate the value (which may itself be a constant) to i32, and
5381         // convert it to a vector with movd (S2V+shuffle to zero extend).
5382         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5383         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5384         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5385
5386         // Now we have our 32-bit value zero extended in the low element of
5387         // a vector.  If Idx != 0, swizzle it into place.
5388         if (Idx != 0) {
5389           SmallVector<int, 4> Mask;
5390           Mask.push_back(Idx);
5391           for (unsigned i = 1; i != VecElts; ++i)
5392             Mask.push_back(i);
5393           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5394                                       &Mask[0]);
5395         }
5396         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5397       }
5398     }
5399
5400     // If we have a constant or non-constant insertion into the low element of
5401     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5402     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5403     // depending on what the source datatype is.
5404     if (Idx == 0) {
5405       if (NumZero == 0)
5406         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5407
5408       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5409           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5410         if (VT.is256BitVector()) {
5411           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5412           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5413                              Item, DAG.getIntPtrConstant(0));
5414         }
5415         assert(VT.is128BitVector() && "Expected an SSE value type!");
5416         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5417         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5418         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5419       }
5420
5421       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5422         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5423         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5424         if (VT.is256BitVector()) {
5425           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5426           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5427         } else {
5428           assert(VT.is128BitVector() && "Expected an SSE value type!");
5429           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5430         }
5431         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5432       }
5433     }
5434
5435     // Is it a vector logical left shift?
5436     if (NumElems == 2 && Idx == 1 &&
5437         X86::isZeroNode(Op.getOperand(0)) &&
5438         !X86::isZeroNode(Op.getOperand(1))) {
5439       unsigned NumBits = VT.getSizeInBits();
5440       return getVShift(true, VT,
5441                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5442                                    VT, Op.getOperand(1)),
5443                        NumBits/2, DAG, *this, dl);
5444     }
5445
5446     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5447       return SDValue();
5448
5449     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5450     // is a non-constant being inserted into an element other than the low one,
5451     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5452     // movd/movss) to move this into the low element, then shuffle it into
5453     // place.
5454     if (EVTBits == 32) {
5455       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5456
5457       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5458       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5459       SmallVector<int, 8> MaskVec;
5460       for (unsigned i = 0; i != NumElems; ++i)
5461         MaskVec.push_back(i == Idx ? 0 : 1);
5462       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5463     }
5464   }
5465
5466   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5467   if (Values.size() == 1) {
5468     if (EVTBits == 32) {
5469       // Instead of a shuffle like this:
5470       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5471       // Check if it's possible to issue this instead.
5472       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5473       unsigned Idx = CountTrailingZeros_32(NonZeros);
5474       SDValue Item = Op.getOperand(Idx);
5475       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5476         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5477     }
5478     return SDValue();
5479   }
5480
5481   // A vector full of immediates; various special cases are already
5482   // handled, so this is best done with a single constant-pool load.
5483   if (IsAllConstants)
5484     return SDValue();
5485
5486   // For AVX-length vectors, build the individual 128-bit pieces and use
5487   // shuffles to put them in place.
5488   if (VT.is256BitVector()) {
5489     SmallVector<SDValue, 32> V;
5490     for (unsigned i = 0; i != NumElems; ++i)
5491       V.push_back(Op.getOperand(i));
5492
5493     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5494
5495     // Build both the lower and upper subvector.
5496     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5497     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5498                                 NumElems/2);
5499
5500     // Recreate the wider vector with the lower and upper part.
5501     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5502   }
5503
5504   // Let legalizer expand 2-wide build_vectors.
5505   if (EVTBits == 64) {
5506     if (NumNonZero == 1) {
5507       // One half is zero or undef.
5508       unsigned Idx = CountTrailingZeros_32(NonZeros);
5509       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5510                                  Op.getOperand(Idx));
5511       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5512     }
5513     return SDValue();
5514   }
5515
5516   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5517   if (EVTBits == 8 && NumElems == 16) {
5518     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5519                                         Subtarget, *this);
5520     if (V.getNode()) return V;
5521   }
5522
5523   if (EVTBits == 16 && NumElems == 8) {
5524     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5525                                       Subtarget, *this);
5526     if (V.getNode()) return V;
5527   }
5528
5529   // If element VT is == 32 bits, turn it into a number of shuffles.
5530   SmallVector<SDValue, 8> V(NumElems);
5531   if (NumElems == 4 && NumZero > 0) {
5532     for (unsigned i = 0; i < 4; ++i) {
5533       bool isZero = !(NonZeros & (1 << i));
5534       if (isZero)
5535         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5536       else
5537         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5538     }
5539
5540     for (unsigned i = 0; i < 2; ++i) {
5541       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5542         default: break;
5543         case 0:
5544           V[i] = V[i*2];  // Must be a zero vector.
5545           break;
5546         case 1:
5547           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5548           break;
5549         case 2:
5550           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5551           break;
5552         case 3:
5553           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5554           break;
5555       }
5556     }
5557
5558     bool Reverse1 = (NonZeros & 0x3) == 2;
5559     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5560     int MaskVec[] = {
5561       Reverse1 ? 1 : 0,
5562       Reverse1 ? 0 : 1,
5563       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5564       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5565     };
5566     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5567   }
5568
5569   if (Values.size() > 1 && VT.is128BitVector()) {
5570     // Check for a build vector of consecutive loads.
5571     for (unsigned i = 0; i < NumElems; ++i)
5572       V[i] = Op.getOperand(i);
5573
5574     // Check for elements which are consecutive loads.
5575     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5576     if (LD.getNode())
5577       return LD;
5578
5579     // Check for a build vector from mostly shuffle plus few inserting.
5580     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5581     if (Sh.getNode())
5582       return Sh;
5583
5584     // For SSE 4.1, use insertps to put the high elements into the low element.
5585     if (getSubtarget()->hasSSE41()) {
5586       SDValue Result;
5587       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5588         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5589       else
5590         Result = DAG.getUNDEF(VT);
5591
5592       for (unsigned i = 1; i < NumElems; ++i) {
5593         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5594         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5595                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5596       }
5597       return Result;
5598     }
5599
5600     // Otherwise, expand into a number of unpckl*, start by extending each of
5601     // our (non-undef) elements to the full vector width with the element in the
5602     // bottom slot of the vector (which generates no code for SSE).
5603     for (unsigned i = 0; i < NumElems; ++i) {
5604       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5605         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5606       else
5607         V[i] = DAG.getUNDEF(VT);
5608     }
5609
5610     // Next, we iteratively mix elements, e.g. for v4f32:
5611     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5612     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5613     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5614     unsigned EltStride = NumElems >> 1;
5615     while (EltStride != 0) {
5616       for (unsigned i = 0; i < EltStride; ++i) {
5617         // If V[i+EltStride] is undef and this is the first round of mixing,
5618         // then it is safe to just drop this shuffle: V[i] is already in the
5619         // right place, the one element (since it's the first round) being
5620         // inserted as undef can be dropped.  This isn't safe for successive
5621         // rounds because they will permute elements within both vectors.
5622         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5623             EltStride == NumElems/2)
5624           continue;
5625
5626         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5627       }
5628       EltStride >>= 1;
5629     }
5630     return V[0];
5631   }
5632   return SDValue();
5633 }
5634
5635 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5636 // to create 256-bit vectors from two other 128-bit ones.
5637 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5638   DebugLoc dl = Op.getDebugLoc();
5639   MVT ResVT = Op.getValueType().getSimpleVT();
5640
5641   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5642
5643   SDValue V1 = Op.getOperand(0);
5644   SDValue V2 = Op.getOperand(1);
5645   unsigned NumElems = ResVT.getVectorNumElements();
5646
5647   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5648 }
5649
5650 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5651   assert(Op.getNumOperands() == 2);
5652
5653   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5654   // from two other 128-bit ones.
5655   return LowerAVXCONCAT_VECTORS(Op, DAG);
5656 }
5657
5658 // Try to lower a shuffle node into a simple blend instruction.
5659 static SDValue
5660 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5661                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5662   SDValue V1 = SVOp->getOperand(0);
5663   SDValue V2 = SVOp->getOperand(1);
5664   DebugLoc dl = SVOp->getDebugLoc();
5665   MVT VT = SVOp->getValueType(0).getSimpleVT();
5666   MVT EltVT = VT.getVectorElementType();
5667   unsigned NumElems = VT.getVectorNumElements();
5668
5669   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5670     return SDValue();
5671   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5672     return SDValue();
5673
5674   // Check the mask for BLEND and build the value.
5675   unsigned MaskValue = 0;
5676   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5677   unsigned NumLanes = (NumElems-1)/8 + 1;
5678   unsigned NumElemsInLane = NumElems / NumLanes;
5679
5680   // Blend for v16i16 should be symetric for the both lanes.
5681   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5682
5683     int SndLaneEltIdx = (NumLanes == 2) ?
5684       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5685     int EltIdx = SVOp->getMaskElt(i);
5686
5687     if ((EltIdx < 0 || EltIdx == (int)i) &&
5688         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5689       continue;
5690
5691     if (((unsigned)EltIdx == (i + NumElems)) &&
5692         (SndLaneEltIdx < 0 ||
5693          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5694       MaskValue |= (1<<i);
5695     else
5696       return SDValue();
5697   }
5698
5699   // Convert i32 vectors to floating point if it is not AVX2.
5700   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5701   MVT BlendVT = VT;
5702   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5703     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5704                                NumElems);
5705     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5706     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5707   }
5708
5709   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5710                             DAG.getConstant(MaskValue, MVT::i32));
5711   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5712 }
5713
5714 // v8i16 shuffles - Prefer shuffles in the following order:
5715 // 1. [all]   pshuflw, pshufhw, optional move
5716 // 2. [ssse3] 1 x pshufb
5717 // 3. [ssse3] 2 x pshufb + 1 x por
5718 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5719 static SDValue
5720 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5721                          SelectionDAG &DAG) {
5722   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5723   SDValue V1 = SVOp->getOperand(0);
5724   SDValue V2 = SVOp->getOperand(1);
5725   DebugLoc dl = SVOp->getDebugLoc();
5726   SmallVector<int, 8> MaskVals;
5727
5728   // Determine if more than 1 of the words in each of the low and high quadwords
5729   // of the result come from the same quadword of one of the two inputs.  Undef
5730   // mask values count as coming from any quadword, for better codegen.
5731   unsigned LoQuad[] = { 0, 0, 0, 0 };
5732   unsigned HiQuad[] = { 0, 0, 0, 0 };
5733   std::bitset<4> InputQuads;
5734   for (unsigned i = 0; i < 8; ++i) {
5735     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5736     int EltIdx = SVOp->getMaskElt(i);
5737     MaskVals.push_back(EltIdx);
5738     if (EltIdx < 0) {
5739       ++Quad[0];
5740       ++Quad[1];
5741       ++Quad[2];
5742       ++Quad[3];
5743       continue;
5744     }
5745     ++Quad[EltIdx / 4];
5746     InputQuads.set(EltIdx / 4);
5747   }
5748
5749   int BestLoQuad = -1;
5750   unsigned MaxQuad = 1;
5751   for (unsigned i = 0; i < 4; ++i) {
5752     if (LoQuad[i] > MaxQuad) {
5753       BestLoQuad = i;
5754       MaxQuad = LoQuad[i];
5755     }
5756   }
5757
5758   int BestHiQuad = -1;
5759   MaxQuad = 1;
5760   for (unsigned i = 0; i < 4; ++i) {
5761     if (HiQuad[i] > MaxQuad) {
5762       BestHiQuad = i;
5763       MaxQuad = HiQuad[i];
5764     }
5765   }
5766
5767   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5768   // of the two input vectors, shuffle them into one input vector so only a
5769   // single pshufb instruction is necessary. If There are more than 2 input
5770   // quads, disable the next transformation since it does not help SSSE3.
5771   bool V1Used = InputQuads[0] || InputQuads[1];
5772   bool V2Used = InputQuads[2] || InputQuads[3];
5773   if (Subtarget->hasSSSE3()) {
5774     if (InputQuads.count() == 2 && V1Used && V2Used) {
5775       BestLoQuad = InputQuads[0] ? 0 : 1;
5776       BestHiQuad = InputQuads[2] ? 2 : 3;
5777     }
5778     if (InputQuads.count() > 2) {
5779       BestLoQuad = -1;
5780       BestHiQuad = -1;
5781     }
5782   }
5783
5784   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5785   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5786   // words from all 4 input quadwords.
5787   SDValue NewV;
5788   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5789     int MaskV[] = {
5790       BestLoQuad < 0 ? 0 : BestLoQuad,
5791       BestHiQuad < 0 ? 1 : BestHiQuad
5792     };
5793     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5794                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5795                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5796     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5797
5798     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5799     // source words for the shuffle, to aid later transformations.
5800     bool AllWordsInNewV = true;
5801     bool InOrder[2] = { true, true };
5802     for (unsigned i = 0; i != 8; ++i) {
5803       int idx = MaskVals[i];
5804       if (idx != (int)i)
5805         InOrder[i/4] = false;
5806       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5807         continue;
5808       AllWordsInNewV = false;
5809       break;
5810     }
5811
5812     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5813     if (AllWordsInNewV) {
5814       for (int i = 0; i != 8; ++i) {
5815         int idx = MaskVals[i];
5816         if (idx < 0)
5817           continue;
5818         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5819         if ((idx != i) && idx < 4)
5820           pshufhw = false;
5821         if ((idx != i) && idx > 3)
5822           pshuflw = false;
5823       }
5824       V1 = NewV;
5825       V2Used = false;
5826       BestLoQuad = 0;
5827       BestHiQuad = 1;
5828     }
5829
5830     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5831     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5832     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5833       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5834       unsigned TargetMask = 0;
5835       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5836                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5837       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5838       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5839                              getShufflePSHUFLWImmediate(SVOp);
5840       V1 = NewV.getOperand(0);
5841       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5842     }
5843   }
5844
5845   // Promote splats to a larger type which usually leads to more efficient code.
5846   // FIXME: Is this true if pshufb is available?
5847   if (SVOp->isSplat())
5848     return PromoteSplat(SVOp, DAG);
5849
5850   // If we have SSSE3, and all words of the result are from 1 input vector,
5851   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5852   // is present, fall back to case 4.
5853   if (Subtarget->hasSSSE3()) {
5854     SmallVector<SDValue,16> pshufbMask;
5855
5856     // If we have elements from both input vectors, set the high bit of the
5857     // shuffle mask element to zero out elements that come from V2 in the V1
5858     // mask, and elements that come from V1 in the V2 mask, so that the two
5859     // results can be OR'd together.
5860     bool TwoInputs = V1Used && V2Used;
5861     for (unsigned i = 0; i != 8; ++i) {
5862       int EltIdx = MaskVals[i] * 2;
5863       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5864       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5865       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5866       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5867     }
5868     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5869     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5870                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5871                                  MVT::v16i8, &pshufbMask[0], 16));
5872     if (!TwoInputs)
5873       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5874
5875     // Calculate the shuffle mask for the second input, shuffle it, and
5876     // OR it with the first shuffled input.
5877     pshufbMask.clear();
5878     for (unsigned i = 0; i != 8; ++i) {
5879       int EltIdx = MaskVals[i] * 2;
5880       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5881       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5882       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5883       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5884     }
5885     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5886     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5887                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5888                                  MVT::v16i8, &pshufbMask[0], 16));
5889     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5890     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5891   }
5892
5893   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5894   // and update MaskVals with new element order.
5895   std::bitset<8> InOrder;
5896   if (BestLoQuad >= 0) {
5897     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5898     for (int i = 0; i != 4; ++i) {
5899       int idx = MaskVals[i];
5900       if (idx < 0) {
5901         InOrder.set(i);
5902       } else if ((idx / 4) == BestLoQuad) {
5903         MaskV[i] = idx & 3;
5904         InOrder.set(i);
5905       }
5906     }
5907     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5908                                 &MaskV[0]);
5909
5910     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5911       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5912       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5913                                   NewV.getOperand(0),
5914                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5915     }
5916   }
5917
5918   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5919   // and update MaskVals with the new element order.
5920   if (BestHiQuad >= 0) {
5921     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5922     for (unsigned i = 4; i != 8; ++i) {
5923       int idx = MaskVals[i];
5924       if (idx < 0) {
5925         InOrder.set(i);
5926       } else if ((idx / 4) == BestHiQuad) {
5927         MaskV[i] = (idx & 3) + 4;
5928         InOrder.set(i);
5929       }
5930     }
5931     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5932                                 &MaskV[0]);
5933
5934     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5935       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5936       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5937                                   NewV.getOperand(0),
5938                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5939     }
5940   }
5941
5942   // In case BestHi & BestLo were both -1, which means each quadword has a word
5943   // from each of the four input quadwords, calculate the InOrder bitvector now
5944   // before falling through to the insert/extract cleanup.
5945   if (BestLoQuad == -1 && BestHiQuad == -1) {
5946     NewV = V1;
5947     for (int i = 0; i != 8; ++i)
5948       if (MaskVals[i] < 0 || MaskVals[i] == i)
5949         InOrder.set(i);
5950   }
5951
5952   // The other elements are put in the right place using pextrw and pinsrw.
5953   for (unsigned i = 0; i != 8; ++i) {
5954     if (InOrder[i])
5955       continue;
5956     int EltIdx = MaskVals[i];
5957     if (EltIdx < 0)
5958       continue;
5959     SDValue ExtOp = (EltIdx < 8) ?
5960       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5961                   DAG.getIntPtrConstant(EltIdx)) :
5962       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5963                   DAG.getIntPtrConstant(EltIdx - 8));
5964     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5965                        DAG.getIntPtrConstant(i));
5966   }
5967   return NewV;
5968 }
5969
5970 // v16i8 shuffles - Prefer shuffles in the following order:
5971 // 1. [ssse3] 1 x pshufb
5972 // 2. [ssse3] 2 x pshufb + 1 x por
5973 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5974 static
5975 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5976                                  SelectionDAG &DAG,
5977                                  const X86TargetLowering &TLI) {
5978   SDValue V1 = SVOp->getOperand(0);
5979   SDValue V2 = SVOp->getOperand(1);
5980   DebugLoc dl = SVOp->getDebugLoc();
5981   ArrayRef<int> MaskVals = SVOp->getMask();
5982
5983   // Promote splats to a larger type which usually leads to more efficient code.
5984   // FIXME: Is this true if pshufb is available?
5985   if (SVOp->isSplat())
5986     return PromoteSplat(SVOp, DAG);
5987
5988   // If we have SSSE3, case 1 is generated when all result bytes come from
5989   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5990   // present, fall back to case 3.
5991
5992   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5993   if (TLI.getSubtarget()->hasSSSE3()) {
5994     SmallVector<SDValue,16> pshufbMask;
5995
5996     // If all result elements are from one input vector, then only translate
5997     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5998     //
5999     // Otherwise, we have elements from both input vectors, and must zero out
6000     // elements that come from V2 in the first mask, and V1 in the second mask
6001     // so that we can OR them together.
6002     for (unsigned i = 0; i != 16; ++i) {
6003       int EltIdx = MaskVals[i];
6004       if (EltIdx < 0 || EltIdx >= 16)
6005         EltIdx = 0x80;
6006       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6007     }
6008     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6009                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6010                                  MVT::v16i8, &pshufbMask[0], 16));
6011
6012     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6013     // the 2nd operand if it's undefined or zero.
6014     if (V2.getOpcode() == ISD::UNDEF ||
6015         ISD::isBuildVectorAllZeros(V2.getNode()))
6016       return V1;
6017
6018     // Calculate the shuffle mask for the second input, shuffle it, and
6019     // OR it with the first shuffled input.
6020     pshufbMask.clear();
6021     for (unsigned i = 0; i != 16; ++i) {
6022       int EltIdx = MaskVals[i];
6023       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6024       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6025     }
6026     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6027                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6028                                  MVT::v16i8, &pshufbMask[0], 16));
6029     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6030   }
6031
6032   // No SSSE3 - Calculate in place words and then fix all out of place words
6033   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6034   // the 16 different words that comprise the two doublequadword input vectors.
6035   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6036   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6037   SDValue NewV = V1;
6038   for (int i = 0; i != 8; ++i) {
6039     int Elt0 = MaskVals[i*2];
6040     int Elt1 = MaskVals[i*2+1];
6041
6042     // This word of the result is all undef, skip it.
6043     if (Elt0 < 0 && Elt1 < 0)
6044       continue;
6045
6046     // This word of the result is already in the correct place, skip it.
6047     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6048       continue;
6049
6050     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6051     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6052     SDValue InsElt;
6053
6054     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6055     // using a single extract together, load it and store it.
6056     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6057       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6058                            DAG.getIntPtrConstant(Elt1 / 2));
6059       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6060                         DAG.getIntPtrConstant(i));
6061       continue;
6062     }
6063
6064     // If Elt1 is defined, extract it from the appropriate source.  If the
6065     // source byte is not also odd, shift the extracted word left 8 bits
6066     // otherwise clear the bottom 8 bits if we need to do an or.
6067     if (Elt1 >= 0) {
6068       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6069                            DAG.getIntPtrConstant(Elt1 / 2));
6070       if ((Elt1 & 1) == 0)
6071         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6072                              DAG.getConstant(8,
6073                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6074       else if (Elt0 >= 0)
6075         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6076                              DAG.getConstant(0xFF00, MVT::i16));
6077     }
6078     // If Elt0 is defined, extract it from the appropriate source.  If the
6079     // source byte is not also even, shift the extracted word right 8 bits. If
6080     // Elt1 was also defined, OR the extracted values together before
6081     // inserting them in the result.
6082     if (Elt0 >= 0) {
6083       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6084                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6085       if ((Elt0 & 1) != 0)
6086         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6087                               DAG.getConstant(8,
6088                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6089       else if (Elt1 >= 0)
6090         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6091                              DAG.getConstant(0x00FF, MVT::i16));
6092       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6093                          : InsElt0;
6094     }
6095     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6096                        DAG.getIntPtrConstant(i));
6097   }
6098   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6099 }
6100
6101 // v32i8 shuffles - Translate to VPSHUFB if possible.
6102 static
6103 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6104                                  const X86Subtarget *Subtarget,
6105                                  SelectionDAG &DAG) {
6106   MVT VT = SVOp->getValueType(0).getSimpleVT();
6107   SDValue V1 = SVOp->getOperand(0);
6108   SDValue V2 = SVOp->getOperand(1);
6109   DebugLoc dl = SVOp->getDebugLoc();
6110   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6111
6112   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6113   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6114   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6115
6116   // VPSHUFB may be generated if
6117   // (1) one of input vector is undefined or zeroinitializer.
6118   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6119   // And (2) the mask indexes don't cross the 128-bit lane.
6120   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6121       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6122     return SDValue();
6123
6124   if (V1IsAllZero && !V2IsAllZero) {
6125     CommuteVectorShuffleMask(MaskVals, 32);
6126     V1 = V2;
6127   }
6128   SmallVector<SDValue, 32> pshufbMask;
6129   for (unsigned i = 0; i != 32; i++) {
6130     int EltIdx = MaskVals[i];
6131     if (EltIdx < 0 || EltIdx >= 32)
6132       EltIdx = 0x80;
6133     else {
6134       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6135         // Cross lane is not allowed.
6136         return SDValue();
6137       EltIdx &= 0xf;
6138     }
6139     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6140   }
6141   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6142                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6143                                   MVT::v32i8, &pshufbMask[0], 32));
6144 }
6145
6146 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6147 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6148 /// done when every pair / quad of shuffle mask elements point to elements in
6149 /// the right sequence. e.g.
6150 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6151 static
6152 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6153                                  SelectionDAG &DAG) {
6154   MVT VT = SVOp->getValueType(0).getSimpleVT();
6155   DebugLoc dl = SVOp->getDebugLoc();
6156   unsigned NumElems = VT.getVectorNumElements();
6157   MVT NewVT;
6158   unsigned Scale;
6159   switch (VT.SimpleTy) {
6160   default: llvm_unreachable("Unexpected!");
6161   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6162   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6163   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6164   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6165   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6166   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6167   }
6168
6169   SmallVector<int, 8> MaskVec;
6170   for (unsigned i = 0; i != NumElems; i += Scale) {
6171     int StartIdx = -1;
6172     for (unsigned j = 0; j != Scale; ++j) {
6173       int EltIdx = SVOp->getMaskElt(i+j);
6174       if (EltIdx < 0)
6175         continue;
6176       if (StartIdx < 0)
6177         StartIdx = (EltIdx / Scale);
6178       if (EltIdx != (int)(StartIdx*Scale + j))
6179         return SDValue();
6180     }
6181     MaskVec.push_back(StartIdx);
6182   }
6183
6184   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6185   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6186   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6187 }
6188
6189 /// getVZextMovL - Return a zero-extending vector move low node.
6190 ///
6191 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6192                             SDValue SrcOp, SelectionDAG &DAG,
6193                             const X86Subtarget *Subtarget, DebugLoc dl) {
6194   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6195     LoadSDNode *LD = NULL;
6196     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6197       LD = dyn_cast<LoadSDNode>(SrcOp);
6198     if (!LD) {
6199       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6200       // instead.
6201       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6202       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6203           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6204           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6205           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6206         // PR2108
6207         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6208         return DAG.getNode(ISD::BITCAST, dl, VT,
6209                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6210                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6211                                                    OpVT,
6212                                                    SrcOp.getOperand(0)
6213                                                           .getOperand(0))));
6214       }
6215     }
6216   }
6217
6218   return DAG.getNode(ISD::BITCAST, dl, VT,
6219                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6220                                  DAG.getNode(ISD::BITCAST, dl,
6221                                              OpVT, SrcOp)));
6222 }
6223
6224 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6225 /// which could not be matched by any known target speficic shuffle
6226 static SDValue
6227 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6228
6229   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6230   if (NewOp.getNode())
6231     return NewOp;
6232
6233   MVT VT = SVOp->getValueType(0).getSimpleVT();
6234
6235   unsigned NumElems = VT.getVectorNumElements();
6236   unsigned NumLaneElems = NumElems / 2;
6237
6238   DebugLoc dl = SVOp->getDebugLoc();
6239   MVT EltVT = VT.getVectorElementType();
6240   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6241   SDValue Output[2];
6242
6243   SmallVector<int, 16> Mask;
6244   for (unsigned l = 0; l < 2; ++l) {
6245     // Build a shuffle mask for the output, discovering on the fly which
6246     // input vectors to use as shuffle operands (recorded in InputUsed).
6247     // If building a suitable shuffle vector proves too hard, then bail
6248     // out with UseBuildVector set.
6249     bool UseBuildVector = false;
6250     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6251     unsigned LaneStart = l * NumLaneElems;
6252     for (unsigned i = 0; i != NumLaneElems; ++i) {
6253       // The mask element.  This indexes into the input.
6254       int Idx = SVOp->getMaskElt(i+LaneStart);
6255       if (Idx < 0) {
6256         // the mask element does not index into any input vector.
6257         Mask.push_back(-1);
6258         continue;
6259       }
6260
6261       // The input vector this mask element indexes into.
6262       int Input = Idx / NumLaneElems;
6263
6264       // Turn the index into an offset from the start of the input vector.
6265       Idx -= Input * NumLaneElems;
6266
6267       // Find or create a shuffle vector operand to hold this input.
6268       unsigned OpNo;
6269       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6270         if (InputUsed[OpNo] == Input)
6271           // This input vector is already an operand.
6272           break;
6273         if (InputUsed[OpNo] < 0) {
6274           // Create a new operand for this input vector.
6275           InputUsed[OpNo] = Input;
6276           break;
6277         }
6278       }
6279
6280       if (OpNo >= array_lengthof(InputUsed)) {
6281         // More than two input vectors used!  Give up on trying to create a
6282         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6283         UseBuildVector = true;
6284         break;
6285       }
6286
6287       // Add the mask index for the new shuffle vector.
6288       Mask.push_back(Idx + OpNo * NumLaneElems);
6289     }
6290
6291     if (UseBuildVector) {
6292       SmallVector<SDValue, 16> SVOps;
6293       for (unsigned i = 0; i != NumLaneElems; ++i) {
6294         // The mask element.  This indexes into the input.
6295         int Idx = SVOp->getMaskElt(i+LaneStart);
6296         if (Idx < 0) {
6297           SVOps.push_back(DAG.getUNDEF(EltVT));
6298           continue;
6299         }
6300
6301         // The input vector this mask element indexes into.
6302         int Input = Idx / NumElems;
6303
6304         // Turn the index into an offset from the start of the input vector.
6305         Idx -= Input * NumElems;
6306
6307         // Extract the vector element by hand.
6308         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6309                                     SVOp->getOperand(Input),
6310                                     DAG.getIntPtrConstant(Idx)));
6311       }
6312
6313       // Construct the output using a BUILD_VECTOR.
6314       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6315                               SVOps.size());
6316     } else if (InputUsed[0] < 0) {
6317       // No input vectors were used! The result is undefined.
6318       Output[l] = DAG.getUNDEF(NVT);
6319     } else {
6320       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6321                                         (InputUsed[0] % 2) * NumLaneElems,
6322                                         DAG, dl);
6323       // If only one input was used, use an undefined vector for the other.
6324       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6325         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6326                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6327       // At least one input vector was used. Create a new shuffle vector.
6328       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6329     }
6330
6331     Mask.clear();
6332   }
6333
6334   // Concatenate the result back
6335   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6336 }
6337
6338 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6339 /// 4 elements, and match them with several different shuffle types.
6340 static SDValue
6341 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6342   SDValue V1 = SVOp->getOperand(0);
6343   SDValue V2 = SVOp->getOperand(1);
6344   DebugLoc dl = SVOp->getDebugLoc();
6345   MVT VT = SVOp->getValueType(0).getSimpleVT();
6346
6347   assert(VT.is128BitVector() && "Unsupported vector size");
6348
6349   std::pair<int, int> Locs[4];
6350   int Mask1[] = { -1, -1, -1, -1 };
6351   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6352
6353   unsigned NumHi = 0;
6354   unsigned NumLo = 0;
6355   for (unsigned i = 0; i != 4; ++i) {
6356     int Idx = PermMask[i];
6357     if (Idx < 0) {
6358       Locs[i] = std::make_pair(-1, -1);
6359     } else {
6360       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6361       if (Idx < 4) {
6362         Locs[i] = std::make_pair(0, NumLo);
6363         Mask1[NumLo] = Idx;
6364         NumLo++;
6365       } else {
6366         Locs[i] = std::make_pair(1, NumHi);
6367         if (2+NumHi < 4)
6368           Mask1[2+NumHi] = Idx;
6369         NumHi++;
6370       }
6371     }
6372   }
6373
6374   if (NumLo <= 2 && NumHi <= 2) {
6375     // If no more than two elements come from either vector. This can be
6376     // implemented with two shuffles. First shuffle gather the elements.
6377     // The second shuffle, which takes the first shuffle as both of its
6378     // vector operands, put the elements into the right order.
6379     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6380
6381     int Mask2[] = { -1, -1, -1, -1 };
6382
6383     for (unsigned i = 0; i != 4; ++i)
6384       if (Locs[i].first != -1) {
6385         unsigned Idx = (i < 2) ? 0 : 4;
6386         Idx += Locs[i].first * 2 + Locs[i].second;
6387         Mask2[i] = Idx;
6388       }
6389
6390     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6391   }
6392
6393   if (NumLo == 3 || NumHi == 3) {
6394     // Otherwise, we must have three elements from one vector, call it X, and
6395     // one element from the other, call it Y.  First, use a shufps to build an
6396     // intermediate vector with the one element from Y and the element from X
6397     // that will be in the same half in the final destination (the indexes don't
6398     // matter). Then, use a shufps to build the final vector, taking the half
6399     // containing the element from Y from the intermediate, and the other half
6400     // from X.
6401     if (NumHi == 3) {
6402       // Normalize it so the 3 elements come from V1.
6403       CommuteVectorShuffleMask(PermMask, 4);
6404       std::swap(V1, V2);
6405     }
6406
6407     // Find the element from V2.
6408     unsigned HiIndex;
6409     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6410       int Val = PermMask[HiIndex];
6411       if (Val < 0)
6412         continue;
6413       if (Val >= 4)
6414         break;
6415     }
6416
6417     Mask1[0] = PermMask[HiIndex];
6418     Mask1[1] = -1;
6419     Mask1[2] = PermMask[HiIndex^1];
6420     Mask1[3] = -1;
6421     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6422
6423     if (HiIndex >= 2) {
6424       Mask1[0] = PermMask[0];
6425       Mask1[1] = PermMask[1];
6426       Mask1[2] = HiIndex & 1 ? 6 : 4;
6427       Mask1[3] = HiIndex & 1 ? 4 : 6;
6428       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6429     }
6430
6431     Mask1[0] = HiIndex & 1 ? 2 : 0;
6432     Mask1[1] = HiIndex & 1 ? 0 : 2;
6433     Mask1[2] = PermMask[2];
6434     Mask1[3] = PermMask[3];
6435     if (Mask1[2] >= 0)
6436       Mask1[2] += 4;
6437     if (Mask1[3] >= 0)
6438       Mask1[3] += 4;
6439     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6440   }
6441
6442   // Break it into (shuffle shuffle_hi, shuffle_lo).
6443   int LoMask[] = { -1, -1, -1, -1 };
6444   int HiMask[] = { -1, -1, -1, -1 };
6445
6446   int *MaskPtr = LoMask;
6447   unsigned MaskIdx = 0;
6448   unsigned LoIdx = 0;
6449   unsigned HiIdx = 2;
6450   for (unsigned i = 0; i != 4; ++i) {
6451     if (i == 2) {
6452       MaskPtr = HiMask;
6453       MaskIdx = 1;
6454       LoIdx = 0;
6455       HiIdx = 2;
6456     }
6457     int Idx = PermMask[i];
6458     if (Idx < 0) {
6459       Locs[i] = std::make_pair(-1, -1);
6460     } else if (Idx < 4) {
6461       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6462       MaskPtr[LoIdx] = Idx;
6463       LoIdx++;
6464     } else {
6465       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6466       MaskPtr[HiIdx] = Idx;
6467       HiIdx++;
6468     }
6469   }
6470
6471   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6472   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6473   int MaskOps[] = { -1, -1, -1, -1 };
6474   for (unsigned i = 0; i != 4; ++i)
6475     if (Locs[i].first != -1)
6476       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6477   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6478 }
6479
6480 static bool MayFoldVectorLoad(SDValue V) {
6481   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6482     V = V.getOperand(0);
6483
6484   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6485     V = V.getOperand(0);
6486   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6487       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6488     // BUILD_VECTOR (load), undef
6489     V = V.getOperand(0);
6490
6491   return MayFoldLoad(V);
6492 }
6493
6494 static
6495 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6496   EVT VT = Op.getValueType();
6497
6498   // Canonizalize to v2f64.
6499   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6500   return DAG.getNode(ISD::BITCAST, dl, VT,
6501                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6502                                           V1, DAG));
6503 }
6504
6505 static
6506 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6507                         bool HasSSE2) {
6508   SDValue V1 = Op.getOperand(0);
6509   SDValue V2 = Op.getOperand(1);
6510   EVT VT = Op.getValueType();
6511
6512   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6513
6514   if (HasSSE2 && VT == MVT::v2f64)
6515     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6516
6517   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6518   return DAG.getNode(ISD::BITCAST, dl, VT,
6519                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6520                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6521                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6522 }
6523
6524 static
6525 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6526   SDValue V1 = Op.getOperand(0);
6527   SDValue V2 = Op.getOperand(1);
6528   EVT VT = Op.getValueType();
6529
6530   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6531          "unsupported shuffle type");
6532
6533   if (V2.getOpcode() == ISD::UNDEF)
6534     V2 = V1;
6535
6536   // v4i32 or v4f32
6537   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6538 }
6539
6540 static
6541 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6542   SDValue V1 = Op.getOperand(0);
6543   SDValue V2 = Op.getOperand(1);
6544   EVT VT = Op.getValueType();
6545   unsigned NumElems = VT.getVectorNumElements();
6546
6547   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6548   // operand of these instructions is only memory, so check if there's a
6549   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6550   // same masks.
6551   bool CanFoldLoad = false;
6552
6553   // Trivial case, when V2 comes from a load.
6554   if (MayFoldVectorLoad(V2))
6555     CanFoldLoad = true;
6556
6557   // When V1 is a load, it can be folded later into a store in isel, example:
6558   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6559   //    turns into:
6560   //  (MOVLPSmr addr:$src1, VR128:$src2)
6561   // So, recognize this potential and also use MOVLPS or MOVLPD
6562   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6563     CanFoldLoad = true;
6564
6565   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6566   if (CanFoldLoad) {
6567     if (HasSSE2 && NumElems == 2)
6568       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6569
6570     if (NumElems == 4)
6571       // If we don't care about the second element, proceed to use movss.
6572       if (SVOp->getMaskElt(1) != -1)
6573         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6574   }
6575
6576   // movl and movlp will both match v2i64, but v2i64 is never matched by
6577   // movl earlier because we make it strict to avoid messing with the movlp load
6578   // folding logic (see the code above getMOVLP call). Match it here then,
6579   // this is horrible, but will stay like this until we move all shuffle
6580   // matching to x86 specific nodes. Note that for the 1st condition all
6581   // types are matched with movsd.
6582   if (HasSSE2) {
6583     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6584     // as to remove this logic from here, as much as possible
6585     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6586       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6587     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6588   }
6589
6590   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6591
6592   // Invert the operand order and use SHUFPS to match it.
6593   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6594                               getShuffleSHUFImmediate(SVOp), DAG);
6595 }
6596
6597 // Reduce a vector shuffle to zext.
6598 SDValue
6599 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6600   // PMOVZX is only available from SSE41.
6601   if (!Subtarget->hasSSE41())
6602     return SDValue();
6603
6604   EVT VT = Op.getValueType();
6605
6606   // Only AVX2 support 256-bit vector integer extending.
6607   if (!Subtarget->hasInt256() && VT.is256BitVector())
6608     return SDValue();
6609
6610   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6611   DebugLoc DL = Op.getDebugLoc();
6612   SDValue V1 = Op.getOperand(0);
6613   SDValue V2 = Op.getOperand(1);
6614   unsigned NumElems = VT.getVectorNumElements();
6615
6616   // Extending is an unary operation and the element type of the source vector
6617   // won't be equal to or larger than i64.
6618   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6619       VT.getVectorElementType() == MVT::i64)
6620     return SDValue();
6621
6622   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6623   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6624   while ((1U << Shift) < NumElems) {
6625     if (SVOp->getMaskElt(1U << Shift) == 1)
6626       break;
6627     Shift += 1;
6628     // The maximal ratio is 8, i.e. from i8 to i64.
6629     if (Shift > 3)
6630       return SDValue();
6631   }
6632
6633   // Check the shuffle mask.
6634   unsigned Mask = (1U << Shift) - 1;
6635   for (unsigned i = 0; i != NumElems; ++i) {
6636     int EltIdx = SVOp->getMaskElt(i);
6637     if ((i & Mask) != 0 && EltIdx != -1)
6638       return SDValue();
6639     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6640       return SDValue();
6641   }
6642
6643   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6644   EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6645   EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6646
6647   if (!isTypeLegal(NVT))
6648     return SDValue();
6649
6650   // Simplify the operand as it's prepared to be fed into shuffle.
6651   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6652   if (V1.getOpcode() == ISD::BITCAST &&
6653       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6654       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6655       V1.getOperand(0)
6656         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6657     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6658     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6659     ConstantSDNode *CIdx =
6660       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6661     // If it's foldable, i.e. normal load with single use, we will let code
6662     // selection to fold it. Otherwise, we will short the conversion sequence.
6663     if (CIdx && CIdx->getZExtValue() == 0 &&
6664         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6665       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6666   }
6667
6668   return DAG.getNode(ISD::BITCAST, DL, VT,
6669                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6670 }
6671
6672 SDValue
6673 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6674   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6675   MVT VT = Op.getValueType().getSimpleVT();
6676   DebugLoc dl = Op.getDebugLoc();
6677   SDValue V1 = Op.getOperand(0);
6678   SDValue V2 = Op.getOperand(1);
6679
6680   if (isZeroShuffle(SVOp))
6681     return getZeroVector(VT, Subtarget, DAG, dl);
6682
6683   // Handle splat operations
6684   if (SVOp->isSplat()) {
6685     // Use vbroadcast whenever the splat comes from a foldable load
6686     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6687     if (Broadcast.getNode())
6688       return Broadcast;
6689   }
6690
6691   // Check integer expanding shuffles.
6692   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6693   if (NewOp.getNode())
6694     return NewOp;
6695
6696   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6697   // do it!
6698   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6699       VT == MVT::v16i16 || VT == MVT::v32i8) {
6700     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6701     if (NewOp.getNode())
6702       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6703   } else if ((VT == MVT::v4i32 ||
6704              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6705     // FIXME: Figure out a cleaner way to do this.
6706     // Try to make use of movq to zero out the top part.
6707     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6708       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6709       if (NewOp.getNode()) {
6710         MVT NewVT = NewOp.getValueType().getSimpleVT();
6711         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6712                                NewVT, true, false))
6713           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6714                               DAG, Subtarget, dl);
6715       }
6716     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6717       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6718       if (NewOp.getNode()) {
6719         MVT NewVT = NewOp.getValueType().getSimpleVT();
6720         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6721           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6722                               DAG, Subtarget, dl);
6723       }
6724     }
6725   }
6726   return SDValue();
6727 }
6728
6729 SDValue
6730 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6731   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6732   SDValue V1 = Op.getOperand(0);
6733   SDValue V2 = Op.getOperand(1);
6734   MVT VT = Op.getValueType().getSimpleVT();
6735   DebugLoc dl = Op.getDebugLoc();
6736   unsigned NumElems = VT.getVectorNumElements();
6737   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6738   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6739   bool V1IsSplat = false;
6740   bool V2IsSplat = false;
6741   bool HasSSE2 = Subtarget->hasSSE2();
6742   bool HasFp256    = Subtarget->hasFp256();
6743   bool HasInt256   = Subtarget->hasInt256();
6744   MachineFunction &MF = DAG.getMachineFunction();
6745   bool OptForSize = MF.getFunction()->getAttributes().
6746     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6747
6748   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6749
6750   if (V1IsUndef && V2IsUndef)
6751     return DAG.getUNDEF(VT);
6752
6753   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6754
6755   // Vector shuffle lowering takes 3 steps:
6756   //
6757   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6758   //    narrowing and commutation of operands should be handled.
6759   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6760   //    shuffle nodes.
6761   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6762   //    so the shuffle can be broken into other shuffles and the legalizer can
6763   //    try the lowering again.
6764   //
6765   // The general idea is that no vector_shuffle operation should be left to
6766   // be matched during isel, all of them must be converted to a target specific
6767   // node here.
6768
6769   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6770   // narrowing and commutation of operands should be handled. The actual code
6771   // doesn't include all of those, work in progress...
6772   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6773   if (NewOp.getNode())
6774     return NewOp;
6775
6776   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6777
6778   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6779   // unpckh_undef). Only use pshufd if speed is more important than size.
6780   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6781     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6782   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6783     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6784
6785   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6786       V2IsUndef && MayFoldVectorLoad(V1))
6787     return getMOVDDup(Op, dl, V1, DAG);
6788
6789   if (isMOVHLPS_v_undef_Mask(M, VT))
6790     return getMOVHighToLow(Op, dl, DAG);
6791
6792   // Use to match splats
6793   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6794       (VT == MVT::v2f64 || VT == MVT::v2i64))
6795     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6796
6797   if (isPSHUFDMask(M, VT)) {
6798     // The actual implementation will match the mask in the if above and then
6799     // during isel it can match several different instructions, not only pshufd
6800     // as its name says, sad but true, emulate the behavior for now...
6801     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6802       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6803
6804     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6805
6806     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6807       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6808
6809     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6810       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6811                                   DAG);
6812
6813     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6814                                 TargetMask, DAG);
6815   }
6816
6817   // Check if this can be converted into a logical shift.
6818   bool isLeft = false;
6819   unsigned ShAmt = 0;
6820   SDValue ShVal;
6821   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6822   if (isShift && ShVal.hasOneUse()) {
6823     // If the shifted value has multiple uses, it may be cheaper to use
6824     // v_set0 + movlhps or movhlps, etc.
6825     MVT EltVT = VT.getVectorElementType();
6826     ShAmt *= EltVT.getSizeInBits();
6827     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6828   }
6829
6830   if (isMOVLMask(M, VT)) {
6831     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6832       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6833     if (!isMOVLPMask(M, VT)) {
6834       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6835         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6836
6837       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6838         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6839     }
6840   }
6841
6842   // FIXME: fold these into legal mask.
6843   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6844     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6845
6846   if (isMOVHLPSMask(M, VT))
6847     return getMOVHighToLow(Op, dl, DAG);
6848
6849   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6850     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6851
6852   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6853     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6854
6855   if (isMOVLPMask(M, VT))
6856     return getMOVLP(Op, dl, DAG, HasSSE2);
6857
6858   if (ShouldXformToMOVHLPS(M, VT) ||
6859       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6860     return CommuteVectorShuffle(SVOp, DAG);
6861
6862   if (isShift) {
6863     // No better options. Use a vshldq / vsrldq.
6864     MVT EltVT = VT.getVectorElementType();
6865     ShAmt *= EltVT.getSizeInBits();
6866     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6867   }
6868
6869   bool Commuted = false;
6870   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6871   // 1,1,1,1 -> v8i16 though.
6872   V1IsSplat = isSplatVector(V1.getNode());
6873   V2IsSplat = isSplatVector(V2.getNode());
6874
6875   // Canonicalize the splat or undef, if present, to be on the RHS.
6876   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6877     CommuteVectorShuffleMask(M, NumElems);
6878     std::swap(V1, V2);
6879     std::swap(V1IsSplat, V2IsSplat);
6880     Commuted = true;
6881   }
6882
6883   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6884     // Shuffling low element of v1 into undef, just return v1.
6885     if (V2IsUndef)
6886       return V1;
6887     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6888     // the instruction selector will not match, so get a canonical MOVL with
6889     // swapped operands to undo the commute.
6890     return getMOVL(DAG, dl, VT, V2, V1);
6891   }
6892
6893   if (isUNPCKLMask(M, VT, HasInt256))
6894     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6895
6896   if (isUNPCKHMask(M, VT, HasInt256))
6897     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6898
6899   if (V2IsSplat) {
6900     // Normalize mask so all entries that point to V2 points to its first
6901     // element then try to match unpck{h|l} again. If match, return a
6902     // new vector_shuffle with the corrected mask.p
6903     SmallVector<int, 8> NewMask(M.begin(), M.end());
6904     NormalizeMask(NewMask, NumElems);
6905     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6906       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6907     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6908       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6909   }
6910
6911   if (Commuted) {
6912     // Commute is back and try unpck* again.
6913     // FIXME: this seems wrong.
6914     CommuteVectorShuffleMask(M, NumElems);
6915     std::swap(V1, V2);
6916     std::swap(V1IsSplat, V2IsSplat);
6917     Commuted = false;
6918
6919     if (isUNPCKLMask(M, VT, HasInt256))
6920       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6921
6922     if (isUNPCKHMask(M, VT, HasInt256))
6923       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6924   }
6925
6926   // Normalize the node to match x86 shuffle ops if needed
6927   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6928     return CommuteVectorShuffle(SVOp, DAG);
6929
6930   // The checks below are all present in isShuffleMaskLegal, but they are
6931   // inlined here right now to enable us to directly emit target specific
6932   // nodes, and remove one by one until they don't return Op anymore.
6933
6934   if (isPALIGNRMask(M, VT, Subtarget))
6935     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6936                                 getShufflePALIGNRImmediate(SVOp),
6937                                 DAG);
6938
6939   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6940       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6941     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6942       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6943   }
6944
6945   if (isPSHUFHWMask(M, VT, HasInt256))
6946     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6947                                 getShufflePSHUFHWImmediate(SVOp),
6948                                 DAG);
6949
6950   if (isPSHUFLWMask(M, VT, HasInt256))
6951     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6952                                 getShufflePSHUFLWImmediate(SVOp),
6953                                 DAG);
6954
6955   if (isSHUFPMask(M, VT, HasFp256))
6956     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6957                                 getShuffleSHUFImmediate(SVOp), DAG);
6958
6959   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6960     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6961   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6962     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6963
6964   //===--------------------------------------------------------------------===//
6965   // Generate target specific nodes for 128 or 256-bit shuffles only
6966   // supported in the AVX instruction set.
6967   //
6968
6969   // Handle VMOVDDUPY permutations
6970   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
6971     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6972
6973   // Handle VPERMILPS/D* permutations
6974   if (isVPERMILPMask(M, VT, HasFp256)) {
6975     if (HasInt256 && VT == MVT::v8i32)
6976       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6977                                   getShuffleSHUFImmediate(SVOp), DAG);
6978     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6979                                 getShuffleSHUFImmediate(SVOp), DAG);
6980   }
6981
6982   // Handle VPERM2F128/VPERM2I128 permutations
6983   if (isVPERM2X128Mask(M, VT, HasFp256))
6984     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6985                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6986
6987   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6988   if (BlendOp.getNode())
6989     return BlendOp;
6990
6991   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6992     SmallVector<SDValue, 8> permclMask;
6993     for (unsigned i = 0; i != 8; ++i) {
6994       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6995     }
6996     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6997                                &permclMask[0], 8);
6998     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6999     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7000                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7001   }
7002
7003   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7004     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7005                                 getShuffleCLImmediate(SVOp), DAG);
7006
7007   //===--------------------------------------------------------------------===//
7008   // Since no target specific shuffle was selected for this generic one,
7009   // lower it into other known shuffles. FIXME: this isn't true yet, but
7010   // this is the plan.
7011   //
7012
7013   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7014   if (VT == MVT::v8i16) {
7015     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7016     if (NewOp.getNode())
7017       return NewOp;
7018   }
7019
7020   if (VT == MVT::v16i8) {
7021     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7022     if (NewOp.getNode())
7023       return NewOp;
7024   }
7025
7026   if (VT == MVT::v32i8) {
7027     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7028     if (NewOp.getNode())
7029       return NewOp;
7030   }
7031
7032   // Handle all 128-bit wide vectors with 4 elements, and match them with
7033   // several different shuffle types.
7034   if (NumElems == 4 && VT.is128BitVector())
7035     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7036
7037   // Handle general 256-bit shuffles
7038   if (VT.is256BitVector())
7039     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7040
7041   return SDValue();
7042 }
7043
7044 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7045   MVT VT = Op.getValueType().getSimpleVT();
7046   DebugLoc dl = Op.getDebugLoc();
7047
7048   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7049     return SDValue();
7050
7051   if (VT.getSizeInBits() == 8) {
7052     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7053                                   Op.getOperand(0), Op.getOperand(1));
7054     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7055                                   DAG.getValueType(VT));
7056     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7057   }
7058
7059   if (VT.getSizeInBits() == 16) {
7060     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7061     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7062     if (Idx == 0)
7063       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7064                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7065                                      DAG.getNode(ISD::BITCAST, dl,
7066                                                  MVT::v4i32,
7067                                                  Op.getOperand(0)),
7068                                      Op.getOperand(1)));
7069     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7070                                   Op.getOperand(0), Op.getOperand(1));
7071     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7072                                   DAG.getValueType(VT));
7073     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7074   }
7075
7076   if (VT == MVT::f32) {
7077     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7078     // the result back to FR32 register. It's only worth matching if the
7079     // result has a single use which is a store or a bitcast to i32.  And in
7080     // the case of a store, it's not worth it if the index is a constant 0,
7081     // because a MOVSSmr can be used instead, which is smaller and faster.
7082     if (!Op.hasOneUse())
7083       return SDValue();
7084     SDNode *User = *Op.getNode()->use_begin();
7085     if ((User->getOpcode() != ISD::STORE ||
7086          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7087           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7088         (User->getOpcode() != ISD::BITCAST ||
7089          User->getValueType(0) != MVT::i32))
7090       return SDValue();
7091     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7092                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7093                                               Op.getOperand(0)),
7094                                               Op.getOperand(1));
7095     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7096   }
7097
7098   if (VT == MVT::i32 || VT == MVT::i64) {
7099     // ExtractPS/pextrq works with constant index.
7100     if (isa<ConstantSDNode>(Op.getOperand(1)))
7101       return Op;
7102   }
7103   return SDValue();
7104 }
7105
7106 SDValue
7107 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7108                                            SelectionDAG &DAG) const {
7109   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7110     return SDValue();
7111
7112   SDValue Vec = Op.getOperand(0);
7113   MVT VecVT = Vec.getValueType().getSimpleVT();
7114
7115   // If this is a 256-bit vector result, first extract the 128-bit vector and
7116   // then extract the element from the 128-bit vector.
7117   if (VecVT.is256BitVector()) {
7118     DebugLoc dl = Op.getNode()->getDebugLoc();
7119     unsigned NumElems = VecVT.getVectorNumElements();
7120     SDValue Idx = Op.getOperand(1);
7121     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7122
7123     // Get the 128-bit vector.
7124     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7125
7126     if (IdxVal >= NumElems/2)
7127       IdxVal -= NumElems/2;
7128     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7129                        DAG.getConstant(IdxVal, MVT::i32));
7130   }
7131
7132   assert(VecVT.is128BitVector() && "Unexpected vector length");
7133
7134   if (Subtarget->hasSSE41()) {
7135     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7136     if (Res.getNode())
7137       return Res;
7138   }
7139
7140   MVT VT = Op.getValueType().getSimpleVT();
7141   DebugLoc dl = Op.getDebugLoc();
7142   // TODO: handle v16i8.
7143   if (VT.getSizeInBits() == 16) {
7144     SDValue Vec = Op.getOperand(0);
7145     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7146     if (Idx == 0)
7147       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7148                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7149                                      DAG.getNode(ISD::BITCAST, dl,
7150                                                  MVT::v4i32, Vec),
7151                                      Op.getOperand(1)));
7152     // Transform it so it match pextrw which produces a 32-bit result.
7153     MVT EltVT = MVT::i32;
7154     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7155                                   Op.getOperand(0), Op.getOperand(1));
7156     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7157                                   DAG.getValueType(VT));
7158     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7159   }
7160
7161   if (VT.getSizeInBits() == 32) {
7162     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7163     if (Idx == 0)
7164       return Op;
7165
7166     // SHUFPS the element to the lowest double word, then movss.
7167     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7168     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7169     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7170                                        DAG.getUNDEF(VVT), Mask);
7171     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7172                        DAG.getIntPtrConstant(0));
7173   }
7174
7175   if (VT.getSizeInBits() == 64) {
7176     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7177     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7178     //        to match extract_elt for f64.
7179     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7180     if (Idx == 0)
7181       return Op;
7182
7183     // UNPCKHPD the element to the lowest double word, then movsd.
7184     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7185     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7186     int Mask[2] = { 1, -1 };
7187     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7188     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7189                                        DAG.getUNDEF(VVT), Mask);
7190     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7191                        DAG.getIntPtrConstant(0));
7192   }
7193
7194   return SDValue();
7195 }
7196
7197 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7198   MVT VT = Op.getValueType().getSimpleVT();
7199   MVT EltVT = VT.getVectorElementType();
7200   DebugLoc dl = Op.getDebugLoc();
7201
7202   SDValue N0 = Op.getOperand(0);
7203   SDValue N1 = Op.getOperand(1);
7204   SDValue N2 = Op.getOperand(2);
7205
7206   if (!VT.is128BitVector())
7207     return SDValue();
7208
7209   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7210       isa<ConstantSDNode>(N2)) {
7211     unsigned Opc;
7212     if (VT == MVT::v8i16)
7213       Opc = X86ISD::PINSRW;
7214     else if (VT == MVT::v16i8)
7215       Opc = X86ISD::PINSRB;
7216     else
7217       Opc = X86ISD::PINSRB;
7218
7219     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7220     // argument.
7221     if (N1.getValueType() != MVT::i32)
7222       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7223     if (N2.getValueType() != MVT::i32)
7224       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7225     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7226   }
7227
7228   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7229     // Bits [7:6] of the constant are the source select.  This will always be
7230     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7231     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7232     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7233     // Bits [5:4] of the constant are the destination select.  This is the
7234     //  value of the incoming immediate.
7235     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7236     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7237     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7238     // Create this as a scalar to vector..
7239     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7240     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7241   }
7242
7243   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7244     // PINSR* works with constant index.
7245     return Op;
7246   }
7247   return SDValue();
7248 }
7249
7250 SDValue
7251 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7252   MVT VT = Op.getValueType().getSimpleVT();
7253   MVT EltVT = VT.getVectorElementType();
7254
7255   DebugLoc dl = Op.getDebugLoc();
7256   SDValue N0 = Op.getOperand(0);
7257   SDValue N1 = Op.getOperand(1);
7258   SDValue N2 = Op.getOperand(2);
7259
7260   // If this is a 256-bit vector result, first extract the 128-bit vector,
7261   // insert the element into the extracted half and then place it back.
7262   if (VT.is256BitVector()) {
7263     if (!isa<ConstantSDNode>(N2))
7264       return SDValue();
7265
7266     // Get the desired 128-bit vector half.
7267     unsigned NumElems = VT.getVectorNumElements();
7268     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7269     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7270
7271     // Insert the element into the desired half.
7272     bool Upper = IdxVal >= NumElems/2;
7273     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7274                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7275
7276     // Insert the changed part back to the 256-bit vector
7277     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7278   }
7279
7280   if (Subtarget->hasSSE41())
7281     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7282
7283   if (EltVT == MVT::i8)
7284     return SDValue();
7285
7286   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7287     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7288     // as its second argument.
7289     if (N1.getValueType() != MVT::i32)
7290       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7291     if (N2.getValueType() != MVT::i32)
7292       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7293     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7294   }
7295   return SDValue();
7296 }
7297
7298 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7299   LLVMContext *Context = DAG.getContext();
7300   DebugLoc dl = Op.getDebugLoc();
7301   MVT OpVT = Op.getValueType().getSimpleVT();
7302
7303   // If this is a 256-bit vector result, first insert into a 128-bit
7304   // vector and then insert into the 256-bit vector.
7305   if (!OpVT.is128BitVector()) {
7306     // Insert into a 128-bit vector.
7307     EVT VT128 = EVT::getVectorVT(*Context,
7308                                  OpVT.getVectorElementType(),
7309                                  OpVT.getVectorNumElements() / 2);
7310
7311     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7312
7313     // Insert the 128-bit vector.
7314     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7315   }
7316
7317   if (OpVT == MVT::v1i64 &&
7318       Op.getOperand(0).getValueType() == MVT::i64)
7319     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7320
7321   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7322   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7323   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7324                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7325 }
7326
7327 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7328 // a simple subregister reference or explicit instructions to grab
7329 // upper bits of a vector.
7330 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7331                                       SelectionDAG &DAG) {
7332   if (Subtarget->hasFp256()) {
7333     DebugLoc dl = Op.getNode()->getDebugLoc();
7334     SDValue Vec = Op.getNode()->getOperand(0);
7335     SDValue Idx = Op.getNode()->getOperand(1);
7336
7337     if (Op.getNode()->getValueType(0).is128BitVector() &&
7338         Vec.getNode()->getValueType(0).is256BitVector() &&
7339         isa<ConstantSDNode>(Idx)) {
7340       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7341       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7342     }
7343   }
7344   return SDValue();
7345 }
7346
7347 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7348 // simple superregister reference or explicit instructions to insert
7349 // the upper bits of a vector.
7350 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7351                                      SelectionDAG &DAG) {
7352   if (Subtarget->hasFp256()) {
7353     DebugLoc dl = Op.getNode()->getDebugLoc();
7354     SDValue Vec = Op.getNode()->getOperand(0);
7355     SDValue SubVec = Op.getNode()->getOperand(1);
7356     SDValue Idx = Op.getNode()->getOperand(2);
7357
7358     if (Op.getNode()->getValueType(0).is256BitVector() &&
7359         SubVec.getNode()->getValueType(0).is128BitVector() &&
7360         isa<ConstantSDNode>(Idx)) {
7361       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7362       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7363     }
7364   }
7365   return SDValue();
7366 }
7367
7368 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7369 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7370 // one of the above mentioned nodes. It has to be wrapped because otherwise
7371 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7372 // be used to form addressing mode. These wrapped nodes will be selected
7373 // into MOV32ri.
7374 SDValue
7375 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7376   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7377
7378   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7379   // global base reg.
7380   unsigned char OpFlag = 0;
7381   unsigned WrapperKind = X86ISD::Wrapper;
7382   CodeModel::Model M = getTargetMachine().getCodeModel();
7383
7384   if (Subtarget->isPICStyleRIPRel() &&
7385       (M == CodeModel::Small || M == CodeModel::Kernel))
7386     WrapperKind = X86ISD::WrapperRIP;
7387   else if (Subtarget->isPICStyleGOT())
7388     OpFlag = X86II::MO_GOTOFF;
7389   else if (Subtarget->isPICStyleStubPIC())
7390     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7391
7392   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7393                                              CP->getAlignment(),
7394                                              CP->getOffset(), OpFlag);
7395   DebugLoc DL = CP->getDebugLoc();
7396   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7397   // With PIC, the address is actually $g + Offset.
7398   if (OpFlag) {
7399     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7400                          DAG.getNode(X86ISD::GlobalBaseReg,
7401                                      DebugLoc(), getPointerTy()),
7402                          Result);
7403   }
7404
7405   return Result;
7406 }
7407
7408 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7409   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7410
7411   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7412   // global base reg.
7413   unsigned char OpFlag = 0;
7414   unsigned WrapperKind = X86ISD::Wrapper;
7415   CodeModel::Model M = getTargetMachine().getCodeModel();
7416
7417   if (Subtarget->isPICStyleRIPRel() &&
7418       (M == CodeModel::Small || M == CodeModel::Kernel))
7419     WrapperKind = X86ISD::WrapperRIP;
7420   else if (Subtarget->isPICStyleGOT())
7421     OpFlag = X86II::MO_GOTOFF;
7422   else if (Subtarget->isPICStyleStubPIC())
7423     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7424
7425   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7426                                           OpFlag);
7427   DebugLoc DL = JT->getDebugLoc();
7428   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7429
7430   // With PIC, the address is actually $g + Offset.
7431   if (OpFlag)
7432     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7433                          DAG.getNode(X86ISD::GlobalBaseReg,
7434                                      DebugLoc(), getPointerTy()),
7435                          Result);
7436
7437   return Result;
7438 }
7439
7440 SDValue
7441 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7442   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7443
7444   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7445   // global base reg.
7446   unsigned char OpFlag = 0;
7447   unsigned WrapperKind = X86ISD::Wrapper;
7448   CodeModel::Model M = getTargetMachine().getCodeModel();
7449
7450   if (Subtarget->isPICStyleRIPRel() &&
7451       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7452     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7453       OpFlag = X86II::MO_GOTPCREL;
7454     WrapperKind = X86ISD::WrapperRIP;
7455   } else if (Subtarget->isPICStyleGOT()) {
7456     OpFlag = X86II::MO_GOT;
7457   } else if (Subtarget->isPICStyleStubPIC()) {
7458     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7459   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7460     OpFlag = X86II::MO_DARWIN_NONLAZY;
7461   }
7462
7463   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7464
7465   DebugLoc DL = Op.getDebugLoc();
7466   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7467
7468   // With PIC, the address is actually $g + Offset.
7469   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7470       !Subtarget->is64Bit()) {
7471     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7472                          DAG.getNode(X86ISD::GlobalBaseReg,
7473                                      DebugLoc(), getPointerTy()),
7474                          Result);
7475   }
7476
7477   // For symbols that require a load from a stub to get the address, emit the
7478   // load.
7479   if (isGlobalStubReference(OpFlag))
7480     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7481                          MachinePointerInfo::getGOT(), false, false, false, 0);
7482
7483   return Result;
7484 }
7485
7486 SDValue
7487 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7488   // Create the TargetBlockAddressAddress node.
7489   unsigned char OpFlags =
7490     Subtarget->ClassifyBlockAddressReference();
7491   CodeModel::Model M = getTargetMachine().getCodeModel();
7492   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7493   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7494   DebugLoc dl = Op.getDebugLoc();
7495   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7496                                              OpFlags);
7497
7498   if (Subtarget->isPICStyleRIPRel() &&
7499       (M == CodeModel::Small || M == CodeModel::Kernel))
7500     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7501   else
7502     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7503
7504   // With PIC, the address is actually $g + Offset.
7505   if (isGlobalRelativeToPICBase(OpFlags)) {
7506     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7507                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7508                          Result);
7509   }
7510
7511   return Result;
7512 }
7513
7514 SDValue
7515 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7516                                       int64_t Offset, SelectionDAG &DAG) const {
7517   // Create the TargetGlobalAddress node, folding in the constant
7518   // offset if it is legal.
7519   unsigned char OpFlags =
7520     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7521   CodeModel::Model M = getTargetMachine().getCodeModel();
7522   SDValue Result;
7523   if (OpFlags == X86II::MO_NO_FLAG &&
7524       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7525     // A direct static reference to a global.
7526     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7527     Offset = 0;
7528   } else {
7529     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7530   }
7531
7532   if (Subtarget->isPICStyleRIPRel() &&
7533       (M == CodeModel::Small || M == CodeModel::Kernel))
7534     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7535   else
7536     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7537
7538   // With PIC, the address is actually $g + Offset.
7539   if (isGlobalRelativeToPICBase(OpFlags)) {
7540     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7541                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7542                          Result);
7543   }
7544
7545   // For globals that require a load from a stub to get the address, emit the
7546   // load.
7547   if (isGlobalStubReference(OpFlags))
7548     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7549                          MachinePointerInfo::getGOT(), false, false, false, 0);
7550
7551   // If there was a non-zero offset that we didn't fold, create an explicit
7552   // addition for it.
7553   if (Offset != 0)
7554     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7555                          DAG.getConstant(Offset, getPointerTy()));
7556
7557   return Result;
7558 }
7559
7560 SDValue
7561 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7562   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7563   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7564   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7565 }
7566
7567 static SDValue
7568 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7569            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7570            unsigned char OperandFlags, bool LocalDynamic = false) {
7571   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7572   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7573   DebugLoc dl = GA->getDebugLoc();
7574   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7575                                            GA->getValueType(0),
7576                                            GA->getOffset(),
7577                                            OperandFlags);
7578
7579   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7580                                            : X86ISD::TLSADDR;
7581
7582   if (InFlag) {
7583     SDValue Ops[] = { Chain,  TGA, *InFlag };
7584     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7585   } else {
7586     SDValue Ops[]  = { Chain, TGA };
7587     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7588   }
7589
7590   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7591   MFI->setAdjustsStack(true);
7592
7593   SDValue Flag = Chain.getValue(1);
7594   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7595 }
7596
7597 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7598 static SDValue
7599 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7600                                 const EVT PtrVT) {
7601   SDValue InFlag;
7602   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7603   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7604                                    DAG.getNode(X86ISD::GlobalBaseReg,
7605                                                DebugLoc(), PtrVT), InFlag);
7606   InFlag = Chain.getValue(1);
7607
7608   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7609 }
7610
7611 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7612 static SDValue
7613 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7614                                 const EVT PtrVT) {
7615   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7616                     X86::RAX, X86II::MO_TLSGD);
7617 }
7618
7619 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7620                                            SelectionDAG &DAG,
7621                                            const EVT PtrVT,
7622                                            bool is64Bit) {
7623   DebugLoc dl = GA->getDebugLoc();
7624
7625   // Get the start address of the TLS block for this module.
7626   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7627       .getInfo<X86MachineFunctionInfo>();
7628   MFI->incNumLocalDynamicTLSAccesses();
7629
7630   SDValue Base;
7631   if (is64Bit) {
7632     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7633                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7634   } else {
7635     SDValue InFlag;
7636     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7637         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7638     InFlag = Chain.getValue(1);
7639     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7640                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7641   }
7642
7643   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7644   // of Base.
7645
7646   // Build x@dtpoff.
7647   unsigned char OperandFlags = X86II::MO_DTPOFF;
7648   unsigned WrapperKind = X86ISD::Wrapper;
7649   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7650                                            GA->getValueType(0),
7651                                            GA->getOffset(), OperandFlags);
7652   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7653
7654   // Add x@dtpoff with the base.
7655   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7656 }
7657
7658 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7659 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7660                                    const EVT PtrVT, TLSModel::Model model,
7661                                    bool is64Bit, bool isPIC) {
7662   DebugLoc dl = GA->getDebugLoc();
7663
7664   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7665   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7666                                                          is64Bit ? 257 : 256));
7667
7668   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7669                                       DAG.getIntPtrConstant(0),
7670                                       MachinePointerInfo(Ptr),
7671                                       false, false, false, 0);
7672
7673   unsigned char OperandFlags = 0;
7674   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7675   // initialexec.
7676   unsigned WrapperKind = X86ISD::Wrapper;
7677   if (model == TLSModel::LocalExec) {
7678     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7679   } else if (model == TLSModel::InitialExec) {
7680     if (is64Bit) {
7681       OperandFlags = X86II::MO_GOTTPOFF;
7682       WrapperKind = X86ISD::WrapperRIP;
7683     } else {
7684       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7685     }
7686   } else {
7687     llvm_unreachable("Unexpected model");
7688   }
7689
7690   // emit "addl x@ntpoff,%eax" (local exec)
7691   // or "addl x@indntpoff,%eax" (initial exec)
7692   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7693   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7694                                            GA->getValueType(0),
7695                                            GA->getOffset(), OperandFlags);
7696   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7697
7698   if (model == TLSModel::InitialExec) {
7699     if (isPIC && !is64Bit) {
7700       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7701                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7702                            Offset);
7703     }
7704
7705     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7706                          MachinePointerInfo::getGOT(), false, false, false,
7707                          0);
7708   }
7709
7710   // The address of the thread local variable is the add of the thread
7711   // pointer with the offset of the variable.
7712   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7713 }
7714
7715 SDValue
7716 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7717
7718   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7719   const GlobalValue *GV = GA->getGlobal();
7720
7721   if (Subtarget->isTargetELF()) {
7722     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7723
7724     switch (model) {
7725       case TLSModel::GeneralDynamic:
7726         if (Subtarget->is64Bit())
7727           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7728         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7729       case TLSModel::LocalDynamic:
7730         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7731                                            Subtarget->is64Bit());
7732       case TLSModel::InitialExec:
7733       case TLSModel::LocalExec:
7734         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7735                                    Subtarget->is64Bit(),
7736                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7737     }
7738     llvm_unreachable("Unknown TLS model.");
7739   }
7740
7741   if (Subtarget->isTargetDarwin()) {
7742     // Darwin only has one model of TLS.  Lower to that.
7743     unsigned char OpFlag = 0;
7744     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7745                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7746
7747     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7748     // global base reg.
7749     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7750                   !Subtarget->is64Bit();
7751     if (PIC32)
7752       OpFlag = X86II::MO_TLVP_PIC_BASE;
7753     else
7754       OpFlag = X86II::MO_TLVP;
7755     DebugLoc DL = Op.getDebugLoc();
7756     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7757                                                 GA->getValueType(0),
7758                                                 GA->getOffset(), OpFlag);
7759     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7760
7761     // With PIC32, the address is actually $g + Offset.
7762     if (PIC32)
7763       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7764                            DAG.getNode(X86ISD::GlobalBaseReg,
7765                                        DebugLoc(), getPointerTy()),
7766                            Offset);
7767
7768     // Lowering the machine isd will make sure everything is in the right
7769     // location.
7770     SDValue Chain = DAG.getEntryNode();
7771     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7772     SDValue Args[] = { Chain, Offset };
7773     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7774
7775     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7776     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7777     MFI->setAdjustsStack(true);
7778
7779     // And our return value (tls address) is in the standard call return value
7780     // location.
7781     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7782     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7783                               Chain.getValue(1));
7784   }
7785
7786   if (Subtarget->isTargetWindows()) {
7787     // Just use the implicit TLS architecture
7788     // Need to generate someting similar to:
7789     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7790     //                                  ; from TEB
7791     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7792     //   mov     rcx, qword [rdx+rcx*8]
7793     //   mov     eax, .tls$:tlsvar
7794     //   [rax+rcx] contains the address
7795     // Windows 64bit: gs:0x58
7796     // Windows 32bit: fs:__tls_array
7797
7798     // If GV is an alias then use the aliasee for determining
7799     // thread-localness.
7800     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7801       GV = GA->resolveAliasedGlobal(false);
7802     DebugLoc dl = GA->getDebugLoc();
7803     SDValue Chain = DAG.getEntryNode();
7804
7805     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7806     // %gs:0x58 (64-bit).
7807     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7808                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7809                                                              256)
7810                                         : Type::getInt32PtrTy(*DAG.getContext(),
7811                                                               257));
7812
7813     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7814                                         Subtarget->is64Bit()
7815                                         ? DAG.getIntPtrConstant(0x58)
7816                                         : DAG.getExternalSymbol("_tls_array",
7817                                                                 getPointerTy()),
7818                                         MachinePointerInfo(Ptr),
7819                                         false, false, false, 0);
7820
7821     // Load the _tls_index variable
7822     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7823     if (Subtarget->is64Bit())
7824       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7825                            IDX, MachinePointerInfo(), MVT::i32,
7826                            false, false, 0);
7827     else
7828       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7829                         false, false, false, 0);
7830
7831     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7832                                     getPointerTy());
7833     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7834
7835     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7836     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7837                       false, false, false, 0);
7838
7839     // Get the offset of start of .tls section
7840     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7841                                              GA->getValueType(0),
7842                                              GA->getOffset(), X86II::MO_SECREL);
7843     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7844
7845     // The address of the thread local variable is the add of the thread
7846     // pointer with the offset of the variable.
7847     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7848   }
7849
7850   llvm_unreachable("TLS not implemented for this target.");
7851 }
7852
7853 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7854 /// and take a 2 x i32 value to shift plus a shift amount.
7855 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7856   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7857   EVT VT = Op.getValueType();
7858   unsigned VTBits = VT.getSizeInBits();
7859   DebugLoc dl = Op.getDebugLoc();
7860   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7861   SDValue ShOpLo = Op.getOperand(0);
7862   SDValue ShOpHi = Op.getOperand(1);
7863   SDValue ShAmt  = Op.getOperand(2);
7864   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7865                                      DAG.getConstant(VTBits - 1, MVT::i8))
7866                        : DAG.getConstant(0, VT);
7867
7868   SDValue Tmp2, Tmp3;
7869   if (Op.getOpcode() == ISD::SHL_PARTS) {
7870     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7871     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7872   } else {
7873     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7874     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7875   }
7876
7877   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7878                                 DAG.getConstant(VTBits, MVT::i8));
7879   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7880                              AndNode, DAG.getConstant(0, MVT::i8));
7881
7882   SDValue Hi, Lo;
7883   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7884   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7885   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7886
7887   if (Op.getOpcode() == ISD::SHL_PARTS) {
7888     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7889     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7890   } else {
7891     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7892     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7893   }
7894
7895   SDValue Ops[2] = { Lo, Hi };
7896   return DAG.getMergeValues(Ops, 2, dl);
7897 }
7898
7899 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7900                                            SelectionDAG &DAG) const {
7901   EVT SrcVT = Op.getOperand(0).getValueType();
7902
7903   if (SrcVT.isVector())
7904     return SDValue();
7905
7906   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7907          "Unknown SINT_TO_FP to lower!");
7908
7909   // These are really Legal; return the operand so the caller accepts it as
7910   // Legal.
7911   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7912     return Op;
7913   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7914       Subtarget->is64Bit()) {
7915     return Op;
7916   }
7917
7918   DebugLoc dl = Op.getDebugLoc();
7919   unsigned Size = SrcVT.getSizeInBits()/8;
7920   MachineFunction &MF = DAG.getMachineFunction();
7921   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7922   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7923   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7924                                StackSlot,
7925                                MachinePointerInfo::getFixedStack(SSFI),
7926                                false, false, 0);
7927   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7928 }
7929
7930 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7931                                      SDValue StackSlot,
7932                                      SelectionDAG &DAG) const {
7933   // Build the FILD
7934   DebugLoc DL = Op.getDebugLoc();
7935   SDVTList Tys;
7936   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7937   if (useSSE)
7938     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7939   else
7940     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7941
7942   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7943
7944   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7945   MachineMemOperand *MMO;
7946   if (FI) {
7947     int SSFI = FI->getIndex();
7948     MMO =
7949       DAG.getMachineFunction()
7950       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7951                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7952   } else {
7953     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7954     StackSlot = StackSlot.getOperand(1);
7955   }
7956   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7957   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7958                                            X86ISD::FILD, DL,
7959                                            Tys, Ops, array_lengthof(Ops),
7960                                            SrcVT, MMO);
7961
7962   if (useSSE) {
7963     Chain = Result.getValue(1);
7964     SDValue InFlag = Result.getValue(2);
7965
7966     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7967     // shouldn't be necessary except that RFP cannot be live across
7968     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7969     MachineFunction &MF = DAG.getMachineFunction();
7970     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7971     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7972     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7973     Tys = DAG.getVTList(MVT::Other);
7974     SDValue Ops[] = {
7975       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7976     };
7977     MachineMemOperand *MMO =
7978       DAG.getMachineFunction()
7979       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7980                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7981
7982     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7983                                     Ops, array_lengthof(Ops),
7984                                     Op.getValueType(), MMO);
7985     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7986                          MachinePointerInfo::getFixedStack(SSFI),
7987                          false, false, false, 0);
7988   }
7989
7990   return Result;
7991 }
7992
7993 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7994 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7995                                                SelectionDAG &DAG) const {
7996   // This algorithm is not obvious. Here it is what we're trying to output:
7997   /*
7998      movq       %rax,  %xmm0
7999      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8000      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8001      #ifdef __SSE3__
8002        haddpd   %xmm0, %xmm0
8003      #else
8004        pshufd   $0x4e, %xmm0, %xmm1
8005        addpd    %xmm1, %xmm0
8006      #endif
8007   */
8008
8009   DebugLoc dl = Op.getDebugLoc();
8010   LLVMContext *Context = DAG.getContext();
8011
8012   // Build some magic constants.
8013   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8014   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8015   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8016
8017   SmallVector<Constant*,2> CV1;
8018   CV1.push_back(
8019     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8020                                       APInt(64, 0x4330000000000000ULL))));
8021   CV1.push_back(
8022     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8023                                       APInt(64, 0x4530000000000000ULL))));
8024   Constant *C1 = ConstantVector::get(CV1);
8025   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8026
8027   // Load the 64-bit value into an XMM register.
8028   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8029                             Op.getOperand(0));
8030   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8031                               MachinePointerInfo::getConstantPool(),
8032                               false, false, false, 16);
8033   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8034                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8035                               CLod0);
8036
8037   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8038                               MachinePointerInfo::getConstantPool(),
8039                               false, false, false, 16);
8040   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8041   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8042   SDValue Result;
8043
8044   if (Subtarget->hasSSE3()) {
8045     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8046     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8047   } else {
8048     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8049     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8050                                            S2F, 0x4E, DAG);
8051     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8052                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8053                          Sub);
8054   }
8055
8056   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8057                      DAG.getIntPtrConstant(0));
8058 }
8059
8060 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8061 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8062                                                SelectionDAG &DAG) const {
8063   DebugLoc dl = Op.getDebugLoc();
8064   // FP constant to bias correct the final result.
8065   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8066                                    MVT::f64);
8067
8068   // Load the 32-bit value into an XMM register.
8069   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8070                              Op.getOperand(0));
8071
8072   // Zero out the upper parts of the register.
8073   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8074
8075   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8076                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8077                      DAG.getIntPtrConstant(0));
8078
8079   // Or the load with the bias.
8080   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8081                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8082                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8083                                                    MVT::v2f64, Load)),
8084                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8085                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8086                                                    MVT::v2f64, Bias)));
8087   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8088                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8089                    DAG.getIntPtrConstant(0));
8090
8091   // Subtract the bias.
8092   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8093
8094   // Handle final rounding.
8095   EVT DestVT = Op.getValueType();
8096
8097   if (DestVT.bitsLT(MVT::f64))
8098     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8099                        DAG.getIntPtrConstant(0));
8100   if (DestVT.bitsGT(MVT::f64))
8101     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8102
8103   // Handle final rounding.
8104   return Sub;
8105 }
8106
8107 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8108                                                SelectionDAG &DAG) const {
8109   SDValue N0 = Op.getOperand(0);
8110   EVT SVT = N0.getValueType();
8111   DebugLoc dl = Op.getDebugLoc();
8112
8113   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8114           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8115          "Custom UINT_TO_FP is not supported!");
8116
8117   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8118                              SVT.getVectorNumElements());
8119   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8120                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8121 }
8122
8123 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8124                                            SelectionDAG &DAG) const {
8125   SDValue N0 = Op.getOperand(0);
8126   DebugLoc dl = Op.getDebugLoc();
8127
8128   if (Op.getValueType().isVector())
8129     return lowerUINT_TO_FP_vec(Op, DAG);
8130
8131   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8132   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8133   // the optimization here.
8134   if (DAG.SignBitIsZero(N0))
8135     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8136
8137   EVT SrcVT = N0.getValueType();
8138   EVT DstVT = Op.getValueType();
8139   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8140     return LowerUINT_TO_FP_i64(Op, DAG);
8141   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8142     return LowerUINT_TO_FP_i32(Op, DAG);
8143   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8144     return SDValue();
8145
8146   // Make a 64-bit buffer, and use it to build an FILD.
8147   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8148   if (SrcVT == MVT::i32) {
8149     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8150     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8151                                      getPointerTy(), StackSlot, WordOff);
8152     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8153                                   StackSlot, MachinePointerInfo(),
8154                                   false, false, 0);
8155     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8156                                   OffsetSlot, MachinePointerInfo(),
8157                                   false, false, 0);
8158     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8159     return Fild;
8160   }
8161
8162   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8163   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8164                                StackSlot, MachinePointerInfo(),
8165                                false, false, 0);
8166   // For i64 source, we need to add the appropriate power of 2 if the input
8167   // was negative.  This is the same as the optimization in
8168   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8169   // we must be careful to do the computation in x87 extended precision, not
8170   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8171   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8172   MachineMemOperand *MMO =
8173     DAG.getMachineFunction()
8174     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8175                           MachineMemOperand::MOLoad, 8, 8);
8176
8177   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8178   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8179   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8180                                          MVT::i64, MMO);
8181
8182   APInt FF(32, 0x5F800000ULL);
8183
8184   // Check whether the sign bit is set.
8185   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8186                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8187                                  ISD::SETLT);
8188
8189   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8190   SDValue FudgePtr = DAG.getConstantPool(
8191                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8192                                          getPointerTy());
8193
8194   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8195   SDValue Zero = DAG.getIntPtrConstant(0);
8196   SDValue Four = DAG.getIntPtrConstant(4);
8197   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8198                                Zero, Four);
8199   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8200
8201   // Load the value out, extending it from f32 to f80.
8202   // FIXME: Avoid the extend by constructing the right constant pool?
8203   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8204                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8205                                  MVT::f32, false, false, 4);
8206   // Extend everything to 80 bits to force it to be done on x87.
8207   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8208   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8209 }
8210
8211 std::pair<SDValue,SDValue>
8212 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8213                                     bool IsSigned, bool IsReplace) const {
8214   DebugLoc DL = Op.getDebugLoc();
8215
8216   EVT DstTy = Op.getValueType();
8217
8218   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8219     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8220     DstTy = MVT::i64;
8221   }
8222
8223   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8224          DstTy.getSimpleVT() >= MVT::i16 &&
8225          "Unknown FP_TO_INT to lower!");
8226
8227   // These are really Legal.
8228   if (DstTy == MVT::i32 &&
8229       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8230     return std::make_pair(SDValue(), SDValue());
8231   if (Subtarget->is64Bit() &&
8232       DstTy == MVT::i64 &&
8233       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8234     return std::make_pair(SDValue(), SDValue());
8235
8236   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8237   // stack slot, or into the FTOL runtime function.
8238   MachineFunction &MF = DAG.getMachineFunction();
8239   unsigned MemSize = DstTy.getSizeInBits()/8;
8240   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8241   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8242
8243   unsigned Opc;
8244   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8245     Opc = X86ISD::WIN_FTOL;
8246   else
8247     switch (DstTy.getSimpleVT().SimpleTy) {
8248     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8249     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8250     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8251     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8252     }
8253
8254   SDValue Chain = DAG.getEntryNode();
8255   SDValue Value = Op.getOperand(0);
8256   EVT TheVT = Op.getOperand(0).getValueType();
8257   // FIXME This causes a redundant load/store if the SSE-class value is already
8258   // in memory, such as if it is on the callstack.
8259   if (isScalarFPTypeInSSEReg(TheVT)) {
8260     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8261     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8262                          MachinePointerInfo::getFixedStack(SSFI),
8263                          false, false, 0);
8264     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8265     SDValue Ops[] = {
8266       Chain, StackSlot, DAG.getValueType(TheVT)
8267     };
8268
8269     MachineMemOperand *MMO =
8270       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8271                               MachineMemOperand::MOLoad, MemSize, MemSize);
8272     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8273                                     DstTy, MMO);
8274     Chain = Value.getValue(1);
8275     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8276     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8277   }
8278
8279   MachineMemOperand *MMO =
8280     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8281                             MachineMemOperand::MOStore, MemSize, MemSize);
8282
8283   if (Opc != X86ISD::WIN_FTOL) {
8284     // Build the FP_TO_INT*_IN_MEM
8285     SDValue Ops[] = { Chain, Value, StackSlot };
8286     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8287                                            Ops, 3, DstTy, MMO);
8288     return std::make_pair(FIST, StackSlot);
8289   } else {
8290     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8291       DAG.getVTList(MVT::Other, MVT::Glue),
8292       Chain, Value);
8293     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8294       MVT::i32, ftol.getValue(1));
8295     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8296       MVT::i32, eax.getValue(2));
8297     SDValue Ops[] = { eax, edx };
8298     SDValue pair = IsReplace
8299       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8300       : DAG.getMergeValues(Ops, 2, DL);
8301     return std::make_pair(pair, SDValue());
8302   }
8303 }
8304
8305 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8306                               const X86Subtarget *Subtarget) {
8307   MVT VT = Op->getValueType(0).getSimpleVT();
8308   SDValue In = Op->getOperand(0);
8309   MVT InVT = In.getValueType().getSimpleVT();
8310   DebugLoc dl = Op->getDebugLoc();
8311
8312   // Optimize vectors in AVX mode:
8313   //
8314   //   v8i16 -> v8i32
8315   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8316   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8317   //   Concat upper and lower parts.
8318   //
8319   //   v4i32 -> v4i64
8320   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8321   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8322   //   Concat upper and lower parts.
8323   //
8324
8325   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8326       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8327     return SDValue();
8328
8329   if (Subtarget->hasInt256())
8330     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8331
8332   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8333   SDValue Undef = DAG.getUNDEF(InVT);
8334   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8335   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8336   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8337
8338   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8339                              VT.getVectorNumElements()/2);
8340
8341   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8342   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8343
8344   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8345 }
8346
8347 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8348                                            SelectionDAG &DAG) const {
8349   if (Subtarget->hasFp256()) {
8350     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8351     if (Res.getNode())
8352       return Res;
8353   }
8354
8355   return SDValue();
8356 }
8357 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8358                                             SelectionDAG &DAG) const {
8359   DebugLoc DL = Op.getDebugLoc();
8360   MVT VT = Op.getValueType().getSimpleVT();
8361   SDValue In = Op.getOperand(0);
8362   MVT SVT = In.getValueType().getSimpleVT();
8363
8364   if (Subtarget->hasFp256()) {
8365     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8366     if (Res.getNode())
8367       return Res;
8368   }
8369
8370   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8371       VT.getVectorNumElements() != SVT.getVectorNumElements())
8372     return SDValue();
8373
8374   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8375
8376   // AVX2 has better support of integer extending.
8377   if (Subtarget->hasInt256())
8378     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8379
8380   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8381   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8382   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8383                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8384                                                 DAG.getUNDEF(MVT::v8i16),
8385                                                 &Mask[0]));
8386
8387   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8388 }
8389
8390 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8391   DebugLoc DL = Op.getDebugLoc();
8392   MVT VT = Op.getValueType().getSimpleVT();
8393   SDValue In = Op.getOperand(0);
8394   MVT SVT = In.getValueType().getSimpleVT();
8395
8396   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8397     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8398     if (Subtarget->hasInt256()) {
8399       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8400       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8401       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8402                                 ShufMask);
8403       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8404                          DAG.getIntPtrConstant(0));
8405     }
8406
8407     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8408     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8409                                DAG.getIntPtrConstant(0));
8410     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8411                                DAG.getIntPtrConstant(2));
8412
8413     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8414     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8415
8416     // The PSHUFD mask:
8417     static const int ShufMask1[] = {0, 2, 0, 0};
8418     SDValue Undef = DAG.getUNDEF(VT);
8419     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8420     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8421
8422     // The MOVLHPS mask:
8423     static const int ShufMask2[] = {0, 1, 4, 5};
8424     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8425   }
8426
8427   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8428     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8429     if (Subtarget->hasInt256()) {
8430       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8431
8432       SmallVector<SDValue,32> pshufbMask;
8433       for (unsigned i = 0; i < 2; ++i) {
8434         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8435         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8436         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8437         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8438         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8439         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8440         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8441         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8442         for (unsigned j = 0; j < 8; ++j)
8443           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8444       }
8445       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8446                                &pshufbMask[0], 32);
8447       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8448       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8449
8450       static const int ShufMask[] = {0,  2,  -1,  -1};
8451       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8452                                 &ShufMask[0]);
8453       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8454                        DAG.getIntPtrConstant(0));
8455       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8456     }
8457
8458     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8459                                DAG.getIntPtrConstant(0));
8460
8461     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8462                                DAG.getIntPtrConstant(4));
8463
8464     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8465     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8466
8467     // The PSHUFB mask:
8468     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8469                                    -1, -1, -1, -1, -1, -1, -1, -1};
8470
8471     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8472     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8473     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8474
8475     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8476     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8477
8478     // The MOVLHPS Mask:
8479     static const int ShufMask2[] = {0, 1, 4, 5};
8480     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8481     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8482   }
8483
8484   // Handle truncation of V256 to V128 using shuffles.
8485   if (!VT.is128BitVector() || !SVT.is256BitVector())
8486     return SDValue();
8487
8488   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8489          "Invalid op");
8490   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8491
8492   unsigned NumElems = VT.getVectorNumElements();
8493   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8494                              NumElems * 2);
8495
8496   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8497   // Prepare truncation shuffle mask
8498   for (unsigned i = 0; i != NumElems; ++i)
8499     MaskVec[i] = i * 2;
8500   SDValue V = DAG.getVectorShuffle(NVT, DL,
8501                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8502                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8503   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8504                      DAG.getIntPtrConstant(0));
8505 }
8506
8507 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8508                                            SelectionDAG &DAG) const {
8509   MVT VT = Op.getValueType().getSimpleVT();
8510   if (VT.isVector()) {
8511     if (VT == MVT::v8i16)
8512       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8513                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8514                                      MVT::v8i32, Op.getOperand(0)));
8515     return SDValue();
8516   }
8517
8518   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8519     /*IsSigned=*/ true, /*IsReplace=*/ false);
8520   SDValue FIST = Vals.first, StackSlot = Vals.second;
8521   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8522   if (FIST.getNode() == 0) return Op;
8523
8524   if (StackSlot.getNode())
8525     // Load the result.
8526     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8527                        FIST, StackSlot, MachinePointerInfo(),
8528                        false, false, false, 0);
8529
8530   // The node is the result.
8531   return FIST;
8532 }
8533
8534 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8535                                            SelectionDAG &DAG) const {
8536   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8537     /*IsSigned=*/ false, /*IsReplace=*/ false);
8538   SDValue FIST = Vals.first, StackSlot = Vals.second;
8539   assert(FIST.getNode() && "Unexpected failure");
8540
8541   if (StackSlot.getNode())
8542     // Load the result.
8543     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8544                        FIST, StackSlot, MachinePointerInfo(),
8545                        false, false, false, 0);
8546
8547   // The node is the result.
8548   return FIST;
8549 }
8550
8551 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8552   DebugLoc DL = Op.getDebugLoc();
8553   MVT VT = Op.getValueType().getSimpleVT();
8554   SDValue In = Op.getOperand(0);
8555   MVT SVT = In.getValueType().getSimpleVT();
8556
8557   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8558
8559   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8560                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8561                                  In, DAG.getUNDEF(SVT)));
8562 }
8563
8564 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8565   LLVMContext *Context = DAG.getContext();
8566   DebugLoc dl = Op.getDebugLoc();
8567   MVT VT = Op.getValueType().getSimpleVT();
8568   MVT EltVT = VT;
8569   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8570   if (VT.isVector()) {
8571     EltVT = VT.getVectorElementType();
8572     NumElts = VT.getVectorNumElements();
8573   }
8574   Constant *C;
8575   if (EltVT == MVT::f64)
8576     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8577                                           APInt(64, ~(1ULL << 63))));
8578   else
8579     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8580                                           APInt(32, ~(1U << 31))));
8581   C = ConstantVector::getSplat(NumElts, C);
8582   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8583   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8584   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8585                              MachinePointerInfo::getConstantPool(),
8586                              false, false, false, Alignment);
8587   if (VT.isVector()) {
8588     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8589     return DAG.getNode(ISD::BITCAST, dl, VT,
8590                        DAG.getNode(ISD::AND, dl, ANDVT,
8591                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8592                                                Op.getOperand(0)),
8593                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8594   }
8595   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8596 }
8597
8598 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8599   LLVMContext *Context = DAG.getContext();
8600   DebugLoc dl = Op.getDebugLoc();
8601   MVT VT = Op.getValueType().getSimpleVT();
8602   MVT EltVT = VT;
8603   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8604   if (VT.isVector()) {
8605     EltVT = VT.getVectorElementType();
8606     NumElts = VT.getVectorNumElements();
8607   }
8608   Constant *C;
8609   if (EltVT == MVT::f64)
8610     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8611                                           APInt(64, 1ULL << 63)));
8612   else
8613     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8614                                           APInt(32, 1U << 31)));
8615   C = ConstantVector::getSplat(NumElts, C);
8616   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8617   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8618   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8619                              MachinePointerInfo::getConstantPool(),
8620                              false, false, false, Alignment);
8621   if (VT.isVector()) {
8622     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8623     return DAG.getNode(ISD::BITCAST, dl, VT,
8624                        DAG.getNode(ISD::XOR, dl, XORVT,
8625                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8626                                                Op.getOperand(0)),
8627                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8628   }
8629
8630   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8631 }
8632
8633 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8634   LLVMContext *Context = DAG.getContext();
8635   SDValue Op0 = Op.getOperand(0);
8636   SDValue Op1 = Op.getOperand(1);
8637   DebugLoc dl = Op.getDebugLoc();
8638   MVT VT = Op.getValueType().getSimpleVT();
8639   MVT SrcVT = Op1.getValueType().getSimpleVT();
8640
8641   // If second operand is smaller, extend it first.
8642   if (SrcVT.bitsLT(VT)) {
8643     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8644     SrcVT = VT;
8645   }
8646   // And if it is bigger, shrink it first.
8647   if (SrcVT.bitsGT(VT)) {
8648     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8649     SrcVT = VT;
8650   }
8651
8652   // At this point the operands and the result should have the same
8653   // type, and that won't be f80 since that is not custom lowered.
8654
8655   // First get the sign bit of second operand.
8656   SmallVector<Constant*,4> CV;
8657   if (SrcVT == MVT::f64) {
8658     const fltSemantics &Sem = APFloat::IEEEdouble;
8659     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8660     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8661   } else {
8662     const fltSemantics &Sem = APFloat::IEEEsingle;
8663     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8664     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8665     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8666     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8667   }
8668   Constant *C = ConstantVector::get(CV);
8669   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8670   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8671                               MachinePointerInfo::getConstantPool(),
8672                               false, false, false, 16);
8673   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8674
8675   // Shift sign bit right or left if the two operands have different types.
8676   if (SrcVT.bitsGT(VT)) {
8677     // Op0 is MVT::f32, Op1 is MVT::f64.
8678     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8679     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8680                           DAG.getConstant(32, MVT::i32));
8681     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8682     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8683                           DAG.getIntPtrConstant(0));
8684   }
8685
8686   // Clear first operand sign bit.
8687   CV.clear();
8688   if (VT == MVT::f64) {
8689     const fltSemantics &Sem = APFloat::IEEEdouble;
8690     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8691                                                    APInt(64, ~(1ULL << 63)))));
8692     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8693   } else {
8694     const fltSemantics &Sem = APFloat::IEEEsingle;
8695     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8696                                                    APInt(32, ~(1U << 31)))));
8697     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8698     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8699     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8700   }
8701   C = ConstantVector::get(CV);
8702   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8703   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8704                               MachinePointerInfo::getConstantPool(),
8705                               false, false, false, 16);
8706   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8707
8708   // Or the value with the sign bit.
8709   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8710 }
8711
8712 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8713   SDValue N0 = Op.getOperand(0);
8714   DebugLoc dl = Op.getDebugLoc();
8715   MVT VT = Op.getValueType().getSimpleVT();
8716
8717   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8718   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8719                                   DAG.getConstant(1, VT));
8720   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8721 }
8722
8723 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8724 //
8725 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8726                                                   SelectionDAG &DAG) const {
8727   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8728
8729   if (!Subtarget->hasSSE41())
8730     return SDValue();
8731
8732   if (!Op->hasOneUse())
8733     return SDValue();
8734
8735   SDNode *N = Op.getNode();
8736   DebugLoc DL = N->getDebugLoc();
8737
8738   SmallVector<SDValue, 8> Opnds;
8739   DenseMap<SDValue, unsigned> VecInMap;
8740   EVT VT = MVT::Other;
8741
8742   // Recognize a special case where a vector is casted into wide integer to
8743   // test all 0s.
8744   Opnds.push_back(N->getOperand(0));
8745   Opnds.push_back(N->getOperand(1));
8746
8747   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8748     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8749     // BFS traverse all OR'd operands.
8750     if (I->getOpcode() == ISD::OR) {
8751       Opnds.push_back(I->getOperand(0));
8752       Opnds.push_back(I->getOperand(1));
8753       // Re-evaluate the number of nodes to be traversed.
8754       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8755       continue;
8756     }
8757
8758     // Quit if a non-EXTRACT_VECTOR_ELT
8759     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8760       return SDValue();
8761
8762     // Quit if without a constant index.
8763     SDValue Idx = I->getOperand(1);
8764     if (!isa<ConstantSDNode>(Idx))
8765       return SDValue();
8766
8767     SDValue ExtractedFromVec = I->getOperand(0);
8768     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8769     if (M == VecInMap.end()) {
8770       VT = ExtractedFromVec.getValueType();
8771       // Quit if not 128/256-bit vector.
8772       if (!VT.is128BitVector() && !VT.is256BitVector())
8773         return SDValue();
8774       // Quit if not the same type.
8775       if (VecInMap.begin() != VecInMap.end() &&
8776           VT != VecInMap.begin()->first.getValueType())
8777         return SDValue();
8778       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8779     }
8780     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8781   }
8782
8783   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8784          "Not extracted from 128-/256-bit vector.");
8785
8786   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8787   SmallVector<SDValue, 8> VecIns;
8788
8789   for (DenseMap<SDValue, unsigned>::const_iterator
8790         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8791     // Quit if not all elements are used.
8792     if (I->second != FullMask)
8793       return SDValue();
8794     VecIns.push_back(I->first);
8795   }
8796
8797   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8798
8799   // Cast all vectors into TestVT for PTEST.
8800   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8801     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8802
8803   // If more than one full vectors are evaluated, OR them first before PTEST.
8804   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8805     // Each iteration will OR 2 nodes and append the result until there is only
8806     // 1 node left, i.e. the final OR'd value of all vectors.
8807     SDValue LHS = VecIns[Slot];
8808     SDValue RHS = VecIns[Slot + 1];
8809     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8810   }
8811
8812   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8813                      VecIns.back(), VecIns.back());
8814 }
8815
8816 /// Emit nodes that will be selected as "test Op0,Op0", or something
8817 /// equivalent.
8818 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8819                                     SelectionDAG &DAG) const {
8820   DebugLoc dl = Op.getDebugLoc();
8821
8822   // CF and OF aren't always set the way we want. Determine which
8823   // of these we need.
8824   bool NeedCF = false;
8825   bool NeedOF = false;
8826   switch (X86CC) {
8827   default: break;
8828   case X86::COND_A: case X86::COND_AE:
8829   case X86::COND_B: case X86::COND_BE:
8830     NeedCF = true;
8831     break;
8832   case X86::COND_G: case X86::COND_GE:
8833   case X86::COND_L: case X86::COND_LE:
8834   case X86::COND_O: case X86::COND_NO:
8835     NeedOF = true;
8836     break;
8837   }
8838
8839   // See if we can use the EFLAGS value from the operand instead of
8840   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8841   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8842   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8843     // Emit a CMP with 0, which is the TEST pattern.
8844     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8845                        DAG.getConstant(0, Op.getValueType()));
8846
8847   unsigned Opcode = 0;
8848   unsigned NumOperands = 0;
8849
8850   // Truncate operations may prevent the merge of the SETCC instruction
8851   // and the arithmetic intruction before it. Attempt to truncate the operands
8852   // of the arithmetic instruction and use a reduced bit-width instruction.
8853   bool NeedTruncation = false;
8854   SDValue ArithOp = Op;
8855   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8856     SDValue Arith = Op->getOperand(0);
8857     // Both the trunc and the arithmetic op need to have one user each.
8858     if (Arith->hasOneUse())
8859       switch (Arith.getOpcode()) {
8860         default: break;
8861         case ISD::ADD:
8862         case ISD::SUB:
8863         case ISD::AND:
8864         case ISD::OR:
8865         case ISD::XOR: {
8866           NeedTruncation = true;
8867           ArithOp = Arith;
8868         }
8869       }
8870   }
8871
8872   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8873   // which may be the result of a CAST.  We use the variable 'Op', which is the
8874   // non-casted variable when we check for possible users.
8875   switch (ArithOp.getOpcode()) {
8876   case ISD::ADD:
8877     // Due to an isel shortcoming, be conservative if this add is likely to be
8878     // selected as part of a load-modify-store instruction. When the root node
8879     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8880     // uses of other nodes in the match, such as the ADD in this case. This
8881     // leads to the ADD being left around and reselected, with the result being
8882     // two adds in the output.  Alas, even if none our users are stores, that
8883     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8884     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8885     // climbing the DAG back to the root, and it doesn't seem to be worth the
8886     // effort.
8887     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8888          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8889       if (UI->getOpcode() != ISD::CopyToReg &&
8890           UI->getOpcode() != ISD::SETCC &&
8891           UI->getOpcode() != ISD::STORE)
8892         goto default_case;
8893
8894     if (ConstantSDNode *C =
8895         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8896       // An add of one will be selected as an INC.
8897       if (C->getAPIntValue() == 1) {
8898         Opcode = X86ISD::INC;
8899         NumOperands = 1;
8900         break;
8901       }
8902
8903       // An add of negative one (subtract of one) will be selected as a DEC.
8904       if (C->getAPIntValue().isAllOnesValue()) {
8905         Opcode = X86ISD::DEC;
8906         NumOperands = 1;
8907         break;
8908       }
8909     }
8910
8911     // Otherwise use a regular EFLAGS-setting add.
8912     Opcode = X86ISD::ADD;
8913     NumOperands = 2;
8914     break;
8915   case ISD::AND: {
8916     // If the primary and result isn't used, don't bother using X86ISD::AND,
8917     // because a TEST instruction will be better.
8918     bool NonFlagUse = false;
8919     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8920            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8921       SDNode *User = *UI;
8922       unsigned UOpNo = UI.getOperandNo();
8923       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8924         // Look pass truncate.
8925         UOpNo = User->use_begin().getOperandNo();
8926         User = *User->use_begin();
8927       }
8928
8929       if (User->getOpcode() != ISD::BRCOND &&
8930           User->getOpcode() != ISD::SETCC &&
8931           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8932         NonFlagUse = true;
8933         break;
8934       }
8935     }
8936
8937     if (!NonFlagUse)
8938       break;
8939   }
8940     // FALL THROUGH
8941   case ISD::SUB:
8942   case ISD::OR:
8943   case ISD::XOR:
8944     // Due to the ISEL shortcoming noted above, be conservative if this op is
8945     // likely to be selected as part of a load-modify-store instruction.
8946     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8947            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8948       if (UI->getOpcode() == ISD::STORE)
8949         goto default_case;
8950
8951     // Otherwise use a regular EFLAGS-setting instruction.
8952     switch (ArithOp.getOpcode()) {
8953     default: llvm_unreachable("unexpected operator!");
8954     case ISD::SUB: Opcode = X86ISD::SUB; break;
8955     case ISD::XOR: Opcode = X86ISD::XOR; break;
8956     case ISD::AND: Opcode = X86ISD::AND; break;
8957     case ISD::OR: {
8958       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8959         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8960         if (EFLAGS.getNode())
8961           return EFLAGS;
8962       }
8963       Opcode = X86ISD::OR;
8964       break;
8965     }
8966     }
8967
8968     NumOperands = 2;
8969     break;
8970   case X86ISD::ADD:
8971   case X86ISD::SUB:
8972   case X86ISD::INC:
8973   case X86ISD::DEC:
8974   case X86ISD::OR:
8975   case X86ISD::XOR:
8976   case X86ISD::AND:
8977     return SDValue(Op.getNode(), 1);
8978   default:
8979   default_case:
8980     break;
8981   }
8982
8983   // If we found that truncation is beneficial, perform the truncation and
8984   // update 'Op'.
8985   if (NeedTruncation) {
8986     EVT VT = Op.getValueType();
8987     SDValue WideVal = Op->getOperand(0);
8988     EVT WideVT = WideVal.getValueType();
8989     unsigned ConvertedOp = 0;
8990     // Use a target machine opcode to prevent further DAGCombine
8991     // optimizations that may separate the arithmetic operations
8992     // from the setcc node.
8993     switch (WideVal.getOpcode()) {
8994       default: break;
8995       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8996       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8997       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8998       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8999       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9000     }
9001
9002     if (ConvertedOp) {
9003       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9004       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9005         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9006         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9007         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9008       }
9009     }
9010   }
9011
9012   if (Opcode == 0)
9013     // Emit a CMP with 0, which is the TEST pattern.
9014     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9015                        DAG.getConstant(0, Op.getValueType()));
9016
9017   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9018   SmallVector<SDValue, 4> Ops;
9019   for (unsigned i = 0; i != NumOperands; ++i)
9020     Ops.push_back(Op.getOperand(i));
9021
9022   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9023   DAG.ReplaceAllUsesWith(Op, New);
9024   return SDValue(New.getNode(), 1);
9025 }
9026
9027 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9028 /// equivalent.
9029 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9030                                    SelectionDAG &DAG) const {
9031   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9032     if (C->getAPIntValue() == 0)
9033       return EmitTest(Op0, X86CC, DAG);
9034
9035   DebugLoc dl = Op0.getDebugLoc();
9036   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9037        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9038     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9039     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9040     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9041                               Op0, Op1);
9042     return SDValue(Sub.getNode(), 1);
9043   }
9044   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9045 }
9046
9047 /// Convert a comparison if required by the subtarget.
9048 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9049                                                  SelectionDAG &DAG) const {
9050   // If the subtarget does not support the FUCOMI instruction, floating-point
9051   // comparisons have to be converted.
9052   if (Subtarget->hasCMov() ||
9053       Cmp.getOpcode() != X86ISD::CMP ||
9054       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9055       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9056     return Cmp;
9057
9058   // The instruction selector will select an FUCOM instruction instead of
9059   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9060   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9061   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9062   DebugLoc dl = Cmp.getDebugLoc();
9063   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9064   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9065   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9066                             DAG.getConstant(8, MVT::i8));
9067   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9068   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9069 }
9070
9071 static bool isAllOnes(SDValue V) {
9072   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9073   return C && C->isAllOnesValue();
9074 }
9075
9076 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9077 /// if it's possible.
9078 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9079                                      DebugLoc dl, SelectionDAG &DAG) const {
9080   SDValue Op0 = And.getOperand(0);
9081   SDValue Op1 = And.getOperand(1);
9082   if (Op0.getOpcode() == ISD::TRUNCATE)
9083     Op0 = Op0.getOperand(0);
9084   if (Op1.getOpcode() == ISD::TRUNCATE)
9085     Op1 = Op1.getOperand(0);
9086
9087   SDValue LHS, RHS;
9088   if (Op1.getOpcode() == ISD::SHL)
9089     std::swap(Op0, Op1);
9090   if (Op0.getOpcode() == ISD::SHL) {
9091     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9092       if (And00C->getZExtValue() == 1) {
9093         // If we looked past a truncate, check that it's only truncating away
9094         // known zeros.
9095         unsigned BitWidth = Op0.getValueSizeInBits();
9096         unsigned AndBitWidth = And.getValueSizeInBits();
9097         if (BitWidth > AndBitWidth) {
9098           APInt Zeros, Ones;
9099           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9100           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9101             return SDValue();
9102         }
9103         LHS = Op1;
9104         RHS = Op0.getOperand(1);
9105       }
9106   } else if (Op1.getOpcode() == ISD::Constant) {
9107     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9108     uint64_t AndRHSVal = AndRHS->getZExtValue();
9109     SDValue AndLHS = Op0;
9110
9111     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9112       LHS = AndLHS.getOperand(0);
9113       RHS = AndLHS.getOperand(1);
9114     }
9115
9116     // Use BT if the immediate can't be encoded in a TEST instruction.
9117     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9118       LHS = AndLHS;
9119       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9120     }
9121   }
9122
9123   if (LHS.getNode()) {
9124     // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9125     // the condition code later.
9126     bool Invert = false;
9127     if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9128       Invert = true;
9129       LHS = LHS.getOperand(0);
9130     }
9131
9132     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9133     // instruction.  Since the shift amount is in-range-or-undefined, we know
9134     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9135     // the encoding for the i16 version is larger than the i32 version.
9136     // Also promote i16 to i32 for performance / code size reason.
9137     if (LHS.getValueType() == MVT::i8 ||
9138         LHS.getValueType() == MVT::i16)
9139       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9140
9141     // If the operand types disagree, extend the shift amount to match.  Since
9142     // BT ignores high bits (like shifts) we can use anyextend.
9143     if (LHS.getValueType() != RHS.getValueType())
9144       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9145
9146     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9147     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9148     // Flip the condition if the LHS was a not instruction
9149     if (Invert)
9150       Cond = X86::GetOppositeBranchCondition(Cond);
9151     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9152                        DAG.getConstant(Cond, MVT::i8), BT);
9153   }
9154
9155   return SDValue();
9156 }
9157
9158 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9159 // ones, and then concatenate the result back.
9160 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9161   MVT VT = Op.getValueType().getSimpleVT();
9162
9163   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9164          "Unsupported value type for operation");
9165
9166   unsigned NumElems = VT.getVectorNumElements();
9167   DebugLoc dl = Op.getDebugLoc();
9168   SDValue CC = Op.getOperand(2);
9169
9170   // Extract the LHS vectors
9171   SDValue LHS = Op.getOperand(0);
9172   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9173   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9174
9175   // Extract the RHS vectors
9176   SDValue RHS = Op.getOperand(1);
9177   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9178   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9179
9180   // Issue the operation on the smaller types and concatenate the result back
9181   MVT EltVT = VT.getVectorElementType();
9182   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9183   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9184                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9185                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9186 }
9187
9188 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9189                            SelectionDAG &DAG) {
9190   SDValue Cond;
9191   SDValue Op0 = Op.getOperand(0);
9192   SDValue Op1 = Op.getOperand(1);
9193   SDValue CC = Op.getOperand(2);
9194   MVT VT = Op.getValueType().getSimpleVT();
9195   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9196   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9197   DebugLoc dl = Op.getDebugLoc();
9198
9199   if (isFP) {
9200 #ifndef NDEBUG
9201     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9202     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9203 #endif
9204
9205     unsigned SSECC;
9206     bool Swap = false;
9207
9208     // SSE Condition code mapping:
9209     //  0 - EQ
9210     //  1 - LT
9211     //  2 - LE
9212     //  3 - UNORD
9213     //  4 - NEQ
9214     //  5 - NLT
9215     //  6 - NLE
9216     //  7 - ORD
9217     switch (SetCCOpcode) {
9218     default: llvm_unreachable("Unexpected SETCC condition");
9219     case ISD::SETOEQ:
9220     case ISD::SETEQ:  SSECC = 0; break;
9221     case ISD::SETOGT:
9222     case ISD::SETGT: Swap = true; // Fallthrough
9223     case ISD::SETLT:
9224     case ISD::SETOLT: SSECC = 1; break;
9225     case ISD::SETOGE:
9226     case ISD::SETGE: Swap = true; // Fallthrough
9227     case ISD::SETLE:
9228     case ISD::SETOLE: SSECC = 2; break;
9229     case ISD::SETUO:  SSECC = 3; break;
9230     case ISD::SETUNE:
9231     case ISD::SETNE:  SSECC = 4; break;
9232     case ISD::SETULE: Swap = true; // Fallthrough
9233     case ISD::SETUGE: SSECC = 5; break;
9234     case ISD::SETULT: Swap = true; // Fallthrough
9235     case ISD::SETUGT: SSECC = 6; break;
9236     case ISD::SETO:   SSECC = 7; break;
9237     case ISD::SETUEQ:
9238     case ISD::SETONE: SSECC = 8; break;
9239     }
9240     if (Swap)
9241       std::swap(Op0, Op1);
9242
9243     // In the two special cases we can't handle, emit two comparisons.
9244     if (SSECC == 8) {
9245       unsigned CC0, CC1;
9246       unsigned CombineOpc;
9247       if (SetCCOpcode == ISD::SETUEQ) {
9248         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9249       } else {
9250         assert(SetCCOpcode == ISD::SETONE);
9251         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9252       }
9253
9254       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9255                                  DAG.getConstant(CC0, MVT::i8));
9256       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9257                                  DAG.getConstant(CC1, MVT::i8));
9258       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9259     }
9260     // Handle all other FP comparisons here.
9261     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9262                        DAG.getConstant(SSECC, MVT::i8));
9263   }
9264
9265   // Break 256-bit integer vector compare into smaller ones.
9266   if (VT.is256BitVector() && !Subtarget->hasInt256())
9267     return Lower256IntVSETCC(Op, DAG);
9268
9269   // We are handling one of the integer comparisons here.  Since SSE only has
9270   // GT and EQ comparisons for integer, swapping operands and multiple
9271   // operations may be required for some comparisons.
9272   unsigned Opc;
9273   bool Swap = false, Invert = false, FlipSigns = false;
9274
9275   switch (SetCCOpcode) {
9276   default: llvm_unreachable("Unexpected SETCC condition");
9277   case ISD::SETNE:  Invert = true;
9278   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9279   case ISD::SETLT:  Swap = true;
9280   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9281   case ISD::SETGE:  Swap = true;
9282   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9283   case ISD::SETULT: Swap = true;
9284   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9285   case ISD::SETUGE: Swap = true;
9286   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9287   }
9288   if (Swap)
9289     std::swap(Op0, Op1);
9290
9291   // Check that the operation in question is available (most are plain SSE2,
9292   // but PCMPGTQ and PCMPEQQ have different requirements).
9293   if (VT == MVT::v2i64) {
9294     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9295       return SDValue();
9296     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9297       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9298       // pcmpeqd + pshufd + pand.
9299       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9300
9301       // First cast everything to the right type,
9302       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9303       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9304
9305       // Do the compare.
9306       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9307
9308       // Make sure the lower and upper halves are both all-ones.
9309       const int Mask[] = { 1, 0, 3, 2 };
9310       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9311       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9312
9313       if (Invert)
9314         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9315
9316       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9317     }
9318   }
9319
9320   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9321   // bits of the inputs before performing those operations.
9322   if (FlipSigns) {
9323     EVT EltVT = VT.getVectorElementType();
9324     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9325                                       EltVT);
9326     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9327     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9328                                     SignBits.size());
9329     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9330     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9331   }
9332
9333   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9334
9335   // If the logical-not of the result is required, perform that now.
9336   if (Invert)
9337     Result = DAG.getNOT(dl, Result, VT);
9338
9339   return Result;
9340 }
9341
9342 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9343
9344   MVT VT = Op.getValueType().getSimpleVT();
9345
9346   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9347
9348   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9349   SDValue Op0 = Op.getOperand(0);
9350   SDValue Op1 = Op.getOperand(1);
9351   DebugLoc dl = Op.getDebugLoc();
9352   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9353
9354   // Optimize to BT if possible.
9355   // Lower (X & (1 << N)) == 0 to BT(X, N).
9356   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9357   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9358   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9359       Op1.getOpcode() == ISD::Constant &&
9360       cast<ConstantSDNode>(Op1)->isNullValue() &&
9361       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9362     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9363     if (NewSetCC.getNode())
9364       return NewSetCC;
9365   }
9366
9367   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9368   // these.
9369   if (Op1.getOpcode() == ISD::Constant &&
9370       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9371        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9372       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9373
9374     // If the input is a setcc, then reuse the input setcc or use a new one with
9375     // the inverted condition.
9376     if (Op0.getOpcode() == X86ISD::SETCC) {
9377       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9378       bool Invert = (CC == ISD::SETNE) ^
9379         cast<ConstantSDNode>(Op1)->isNullValue();
9380       if (!Invert) return Op0;
9381
9382       CCode = X86::GetOppositeBranchCondition(CCode);
9383       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9384                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9385     }
9386   }
9387
9388   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9389   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9390   if (X86CC == X86::COND_INVALID)
9391     return SDValue();
9392
9393   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9394   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9395   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9396                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9397 }
9398
9399 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9400 static bool isX86LogicalCmp(SDValue Op) {
9401   unsigned Opc = Op.getNode()->getOpcode();
9402   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9403       Opc == X86ISD::SAHF)
9404     return true;
9405   if (Op.getResNo() == 1 &&
9406       (Opc == X86ISD::ADD ||
9407        Opc == X86ISD::SUB ||
9408        Opc == X86ISD::ADC ||
9409        Opc == X86ISD::SBB ||
9410        Opc == X86ISD::SMUL ||
9411        Opc == X86ISD::UMUL ||
9412        Opc == X86ISD::INC ||
9413        Opc == X86ISD::DEC ||
9414        Opc == X86ISD::OR ||
9415        Opc == X86ISD::XOR ||
9416        Opc == X86ISD::AND))
9417     return true;
9418
9419   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9420     return true;
9421
9422   return false;
9423 }
9424
9425 static bool isZero(SDValue V) {
9426   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9427   return C && C->isNullValue();
9428 }
9429
9430 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9431   if (V.getOpcode() != ISD::TRUNCATE)
9432     return false;
9433
9434   SDValue VOp0 = V.getOperand(0);
9435   unsigned InBits = VOp0.getValueSizeInBits();
9436   unsigned Bits = V.getValueSizeInBits();
9437   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9438 }
9439
9440 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9441   bool addTest = true;
9442   SDValue Cond  = Op.getOperand(0);
9443   SDValue Op1 = Op.getOperand(1);
9444   SDValue Op2 = Op.getOperand(2);
9445   DebugLoc DL = Op.getDebugLoc();
9446   SDValue CC;
9447
9448   if (Cond.getOpcode() == ISD::SETCC) {
9449     SDValue NewCond = LowerSETCC(Cond, DAG);
9450     if (NewCond.getNode())
9451       Cond = NewCond;
9452   }
9453
9454   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9455   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9456   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9457   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9458   if (Cond.getOpcode() == X86ISD::SETCC &&
9459       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9460       isZero(Cond.getOperand(1).getOperand(1))) {
9461     SDValue Cmp = Cond.getOperand(1);
9462
9463     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9464
9465     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9466         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9467       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9468
9469       SDValue CmpOp0 = Cmp.getOperand(0);
9470       // Apply further optimizations for special cases
9471       // (select (x != 0), -1, 0) -> neg & sbb
9472       // (select (x == 0), 0, -1) -> neg & sbb
9473       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9474         if (YC->isNullValue() &&
9475             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9476           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9477           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9478                                     DAG.getConstant(0, CmpOp0.getValueType()),
9479                                     CmpOp0);
9480           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9481                                     DAG.getConstant(X86::COND_B, MVT::i8),
9482                                     SDValue(Neg.getNode(), 1));
9483           return Res;
9484         }
9485
9486       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9487                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9488       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9489
9490       SDValue Res =   // Res = 0 or -1.
9491         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9492                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9493
9494       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9495         Res = DAG.getNOT(DL, Res, Res.getValueType());
9496
9497       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9498       if (N2C == 0 || !N2C->isNullValue())
9499         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9500       return Res;
9501     }
9502   }
9503
9504   // Look past (and (setcc_carry (cmp ...)), 1).
9505   if (Cond.getOpcode() == ISD::AND &&
9506       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9507     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9508     if (C && C->getAPIntValue() == 1)
9509       Cond = Cond.getOperand(0);
9510   }
9511
9512   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9513   // setting operand in place of the X86ISD::SETCC.
9514   unsigned CondOpcode = Cond.getOpcode();
9515   if (CondOpcode == X86ISD::SETCC ||
9516       CondOpcode == X86ISD::SETCC_CARRY) {
9517     CC = Cond.getOperand(0);
9518
9519     SDValue Cmp = Cond.getOperand(1);
9520     unsigned Opc = Cmp.getOpcode();
9521     MVT VT = Op.getValueType().getSimpleVT();
9522
9523     bool IllegalFPCMov = false;
9524     if (VT.isFloatingPoint() && !VT.isVector() &&
9525         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9526       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9527
9528     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9529         Opc == X86ISD::BT) { // FIXME
9530       Cond = Cmp;
9531       addTest = false;
9532     }
9533   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9534              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9535              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9536               Cond.getOperand(0).getValueType() != MVT::i8)) {
9537     SDValue LHS = Cond.getOperand(0);
9538     SDValue RHS = Cond.getOperand(1);
9539     unsigned X86Opcode;
9540     unsigned X86Cond;
9541     SDVTList VTs;
9542     switch (CondOpcode) {
9543     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9544     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9545     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9546     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9547     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9548     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9549     default: llvm_unreachable("unexpected overflowing operator");
9550     }
9551     if (CondOpcode == ISD::UMULO)
9552       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9553                           MVT::i32);
9554     else
9555       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9556
9557     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9558
9559     if (CondOpcode == ISD::UMULO)
9560       Cond = X86Op.getValue(2);
9561     else
9562       Cond = X86Op.getValue(1);
9563
9564     CC = DAG.getConstant(X86Cond, MVT::i8);
9565     addTest = false;
9566   }
9567
9568   if (addTest) {
9569     // Look pass the truncate if the high bits are known zero.
9570     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9571         Cond = Cond.getOperand(0);
9572
9573     // We know the result of AND is compared against zero. Try to match
9574     // it to BT.
9575     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9576       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9577       if (NewSetCC.getNode()) {
9578         CC = NewSetCC.getOperand(0);
9579         Cond = NewSetCC.getOperand(1);
9580         addTest = false;
9581       }
9582     }
9583   }
9584
9585   if (addTest) {
9586     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9587     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9588   }
9589
9590   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9591   // a <  b ?  0 : -1 -> RES = setcc_carry
9592   // a >= b ? -1 :  0 -> RES = setcc_carry
9593   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9594   if (Cond.getOpcode() == X86ISD::SUB) {
9595     Cond = ConvertCmpIfNecessary(Cond, DAG);
9596     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9597
9598     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9599         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9600       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9601                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9602       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9603         return DAG.getNOT(DL, Res, Res.getValueType());
9604       return Res;
9605     }
9606   }
9607
9608   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9609   // widen the cmov and push the truncate through. This avoids introducing a new
9610   // branch during isel and doesn't add any extensions.
9611   if (Op.getValueType() == MVT::i8 &&
9612       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9613     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9614     if (T1.getValueType() == T2.getValueType() &&
9615         // Blacklist CopyFromReg to avoid partial register stalls.
9616         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9617       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9618       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9619       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9620     }
9621   }
9622
9623   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9624   // condition is true.
9625   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9626   SDValue Ops[] = { Op2, Op1, CC, Cond };
9627   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9628 }
9629
9630 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9631                                             SelectionDAG &DAG) const {
9632   MVT VT = Op->getValueType(0).getSimpleVT();
9633   SDValue In = Op->getOperand(0);
9634   MVT InVT = In.getValueType().getSimpleVT();
9635   DebugLoc dl = Op->getDebugLoc();
9636
9637   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9638       (VT != MVT::v8i32 || InVT != MVT::v8i16))
9639     return SDValue();
9640
9641   if (Subtarget->hasInt256())
9642     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9643
9644   // Optimize vectors in AVX mode
9645   // Sign extend  v8i16 to v8i32 and
9646   //              v4i32 to v4i64
9647   //
9648   // Divide input vector into two parts
9649   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9650   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9651   // concat the vectors to original VT
9652
9653   unsigned NumElems = InVT.getVectorNumElements();
9654   SDValue Undef = DAG.getUNDEF(InVT);
9655
9656   SmallVector<int,8> ShufMask1(NumElems, -1);
9657   for (unsigned i = 0; i != NumElems/2; ++i)
9658     ShufMask1[i] = i;
9659
9660   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9661
9662   SmallVector<int,8> ShufMask2(NumElems, -1);
9663   for (unsigned i = 0; i != NumElems/2; ++i)
9664     ShufMask2[i] = i + NumElems/2;
9665
9666   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9667
9668   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9669                                 VT.getVectorNumElements()/2);
9670
9671   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9672   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9673
9674   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9675 }
9676
9677 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9678 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9679 // from the AND / OR.
9680 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9681   Opc = Op.getOpcode();
9682   if (Opc != ISD::OR && Opc != ISD::AND)
9683     return false;
9684   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9685           Op.getOperand(0).hasOneUse() &&
9686           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9687           Op.getOperand(1).hasOneUse());
9688 }
9689
9690 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9691 // 1 and that the SETCC node has a single use.
9692 static bool isXor1OfSetCC(SDValue Op) {
9693   if (Op.getOpcode() != ISD::XOR)
9694     return false;
9695   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9696   if (N1C && N1C->getAPIntValue() == 1) {
9697     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9698       Op.getOperand(0).hasOneUse();
9699   }
9700   return false;
9701 }
9702
9703 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9704   bool addTest = true;
9705   SDValue Chain = Op.getOperand(0);
9706   SDValue Cond  = Op.getOperand(1);
9707   SDValue Dest  = Op.getOperand(2);
9708   DebugLoc dl = Op.getDebugLoc();
9709   SDValue CC;
9710   bool Inverted = false;
9711
9712   if (Cond.getOpcode() == ISD::SETCC) {
9713     // Check for setcc([su]{add,sub,mul}o == 0).
9714     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9715         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9716         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9717         Cond.getOperand(0).getResNo() == 1 &&
9718         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9719          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9720          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9721          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9722          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9723          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9724       Inverted = true;
9725       Cond = Cond.getOperand(0);
9726     } else {
9727       SDValue NewCond = LowerSETCC(Cond, DAG);
9728       if (NewCond.getNode())
9729         Cond = NewCond;
9730     }
9731   }
9732 #if 0
9733   // FIXME: LowerXALUO doesn't handle these!!
9734   else if (Cond.getOpcode() == X86ISD::ADD  ||
9735            Cond.getOpcode() == X86ISD::SUB  ||
9736            Cond.getOpcode() == X86ISD::SMUL ||
9737            Cond.getOpcode() == X86ISD::UMUL)
9738     Cond = LowerXALUO(Cond, DAG);
9739 #endif
9740
9741   // Look pass (and (setcc_carry (cmp ...)), 1).
9742   if (Cond.getOpcode() == ISD::AND &&
9743       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9744     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9745     if (C && C->getAPIntValue() == 1)
9746       Cond = Cond.getOperand(0);
9747   }
9748
9749   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9750   // setting operand in place of the X86ISD::SETCC.
9751   unsigned CondOpcode = Cond.getOpcode();
9752   if (CondOpcode == X86ISD::SETCC ||
9753       CondOpcode == X86ISD::SETCC_CARRY) {
9754     CC = Cond.getOperand(0);
9755
9756     SDValue Cmp = Cond.getOperand(1);
9757     unsigned Opc = Cmp.getOpcode();
9758     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9759     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9760       Cond = Cmp;
9761       addTest = false;
9762     } else {
9763       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9764       default: break;
9765       case X86::COND_O:
9766       case X86::COND_B:
9767         // These can only come from an arithmetic instruction with overflow,
9768         // e.g. SADDO, UADDO.
9769         Cond = Cond.getNode()->getOperand(1);
9770         addTest = false;
9771         break;
9772       }
9773     }
9774   }
9775   CondOpcode = Cond.getOpcode();
9776   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9777       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9778       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9779        Cond.getOperand(0).getValueType() != MVT::i8)) {
9780     SDValue LHS = Cond.getOperand(0);
9781     SDValue RHS = Cond.getOperand(1);
9782     unsigned X86Opcode;
9783     unsigned X86Cond;
9784     SDVTList VTs;
9785     switch (CondOpcode) {
9786     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9787     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9788     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9789     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9790     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9791     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9792     default: llvm_unreachable("unexpected overflowing operator");
9793     }
9794     if (Inverted)
9795       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9796     if (CondOpcode == ISD::UMULO)
9797       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9798                           MVT::i32);
9799     else
9800       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9801
9802     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9803
9804     if (CondOpcode == ISD::UMULO)
9805       Cond = X86Op.getValue(2);
9806     else
9807       Cond = X86Op.getValue(1);
9808
9809     CC = DAG.getConstant(X86Cond, MVT::i8);
9810     addTest = false;
9811   } else {
9812     unsigned CondOpc;
9813     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9814       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9815       if (CondOpc == ISD::OR) {
9816         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9817         // two branches instead of an explicit OR instruction with a
9818         // separate test.
9819         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9820             isX86LogicalCmp(Cmp)) {
9821           CC = Cond.getOperand(0).getOperand(0);
9822           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9823                               Chain, Dest, CC, Cmp);
9824           CC = Cond.getOperand(1).getOperand(0);
9825           Cond = Cmp;
9826           addTest = false;
9827         }
9828       } else { // ISD::AND
9829         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9830         // two branches instead of an explicit AND instruction with a
9831         // separate test. However, we only do this if this block doesn't
9832         // have a fall-through edge, because this requires an explicit
9833         // jmp when the condition is false.
9834         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9835             isX86LogicalCmp(Cmp) &&
9836             Op.getNode()->hasOneUse()) {
9837           X86::CondCode CCode =
9838             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9839           CCode = X86::GetOppositeBranchCondition(CCode);
9840           CC = DAG.getConstant(CCode, MVT::i8);
9841           SDNode *User = *Op.getNode()->use_begin();
9842           // Look for an unconditional branch following this conditional branch.
9843           // We need this because we need to reverse the successors in order
9844           // to implement FCMP_OEQ.
9845           if (User->getOpcode() == ISD::BR) {
9846             SDValue FalseBB = User->getOperand(1);
9847             SDNode *NewBR =
9848               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9849             assert(NewBR == User);
9850             (void)NewBR;
9851             Dest = FalseBB;
9852
9853             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9854                                 Chain, Dest, CC, Cmp);
9855             X86::CondCode CCode =
9856               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9857             CCode = X86::GetOppositeBranchCondition(CCode);
9858             CC = DAG.getConstant(CCode, MVT::i8);
9859             Cond = Cmp;
9860             addTest = false;
9861           }
9862         }
9863       }
9864     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9865       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9866       // It should be transformed during dag combiner except when the condition
9867       // is set by a arithmetics with overflow node.
9868       X86::CondCode CCode =
9869         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9870       CCode = X86::GetOppositeBranchCondition(CCode);
9871       CC = DAG.getConstant(CCode, MVT::i8);
9872       Cond = Cond.getOperand(0).getOperand(1);
9873       addTest = false;
9874     } else if (Cond.getOpcode() == ISD::SETCC &&
9875                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9876       // For FCMP_OEQ, we can emit
9877       // two branches instead of an explicit AND instruction with a
9878       // separate test. However, we only do this if this block doesn't
9879       // have a fall-through edge, because this requires an explicit
9880       // jmp when the condition is false.
9881       if (Op.getNode()->hasOneUse()) {
9882         SDNode *User = *Op.getNode()->use_begin();
9883         // Look for an unconditional branch following this conditional branch.
9884         // We need this because we need to reverse the successors in order
9885         // to implement FCMP_OEQ.
9886         if (User->getOpcode() == ISD::BR) {
9887           SDValue FalseBB = User->getOperand(1);
9888           SDNode *NewBR =
9889             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9890           assert(NewBR == User);
9891           (void)NewBR;
9892           Dest = FalseBB;
9893
9894           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9895                                     Cond.getOperand(0), Cond.getOperand(1));
9896           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9897           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9898           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9899                               Chain, Dest, CC, Cmp);
9900           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9901           Cond = Cmp;
9902           addTest = false;
9903         }
9904       }
9905     } else if (Cond.getOpcode() == ISD::SETCC &&
9906                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9907       // For FCMP_UNE, we can emit
9908       // two branches instead of an explicit AND instruction with a
9909       // separate test. However, we only do this if this block doesn't
9910       // have a fall-through edge, because this requires an explicit
9911       // jmp when the condition is false.
9912       if (Op.getNode()->hasOneUse()) {
9913         SDNode *User = *Op.getNode()->use_begin();
9914         // Look for an unconditional branch following this conditional branch.
9915         // We need this because we need to reverse the successors in order
9916         // to implement FCMP_UNE.
9917         if (User->getOpcode() == ISD::BR) {
9918           SDValue FalseBB = User->getOperand(1);
9919           SDNode *NewBR =
9920             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9921           assert(NewBR == User);
9922           (void)NewBR;
9923
9924           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9925                                     Cond.getOperand(0), Cond.getOperand(1));
9926           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9927           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9928           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9929                               Chain, Dest, CC, Cmp);
9930           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9931           Cond = Cmp;
9932           addTest = false;
9933           Dest = FalseBB;
9934         }
9935       }
9936     }
9937   }
9938
9939   if (addTest) {
9940     // Look pass the truncate if the high bits are known zero.
9941     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9942         Cond = Cond.getOperand(0);
9943
9944     // We know the result of AND is compared against zero. Try to match
9945     // it to BT.
9946     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9947       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9948       if (NewSetCC.getNode()) {
9949         CC = NewSetCC.getOperand(0);
9950         Cond = NewSetCC.getOperand(1);
9951         addTest = false;
9952       }
9953     }
9954   }
9955
9956   if (addTest) {
9957     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9958     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9959   }
9960   Cond = ConvertCmpIfNecessary(Cond, DAG);
9961   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9962                      Chain, Dest, CC, Cond);
9963 }
9964
9965 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9966 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9967 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9968 // that the guard pages used by the OS virtual memory manager are allocated in
9969 // correct sequence.
9970 SDValue
9971 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9972                                            SelectionDAG &DAG) const {
9973   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9974           getTargetMachine().Options.EnableSegmentedStacks) &&
9975          "This should be used only on Windows targets or when segmented stacks "
9976          "are being used");
9977   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9978   DebugLoc dl = Op.getDebugLoc();
9979
9980   // Get the inputs.
9981   SDValue Chain = Op.getOperand(0);
9982   SDValue Size  = Op.getOperand(1);
9983   // FIXME: Ensure alignment here
9984
9985   bool Is64Bit = Subtarget->is64Bit();
9986   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9987
9988   if (getTargetMachine().Options.EnableSegmentedStacks) {
9989     MachineFunction &MF = DAG.getMachineFunction();
9990     MachineRegisterInfo &MRI = MF.getRegInfo();
9991
9992     if (Is64Bit) {
9993       // The 64 bit implementation of segmented stacks needs to clobber both r10
9994       // r11. This makes it impossible to use it along with nested parameters.
9995       const Function *F = MF.getFunction();
9996
9997       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9998            I != E; ++I)
9999         if (I->hasNestAttr())
10000           report_fatal_error("Cannot use segmented stacks with functions that "
10001                              "have nested arguments.");
10002     }
10003
10004     const TargetRegisterClass *AddrRegClass =
10005       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10006     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10007     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10008     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10009                                 DAG.getRegister(Vreg, SPTy));
10010     SDValue Ops1[2] = { Value, Chain };
10011     return DAG.getMergeValues(Ops1, 2, dl);
10012   } else {
10013     SDValue Flag;
10014     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10015
10016     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10017     Flag = Chain.getValue(1);
10018     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10019
10020     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10021     Flag = Chain.getValue(1);
10022
10023     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10024                                SPTy).getValue(1);
10025
10026     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10027     return DAG.getMergeValues(Ops1, 2, dl);
10028   }
10029 }
10030
10031 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10032   MachineFunction &MF = DAG.getMachineFunction();
10033   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10034
10035   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10036   DebugLoc DL = Op.getDebugLoc();
10037
10038   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10039     // vastart just stores the address of the VarArgsFrameIndex slot into the
10040     // memory location argument.
10041     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10042                                    getPointerTy());
10043     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10044                         MachinePointerInfo(SV), false, false, 0);
10045   }
10046
10047   // __va_list_tag:
10048   //   gp_offset         (0 - 6 * 8)
10049   //   fp_offset         (48 - 48 + 8 * 16)
10050   //   overflow_arg_area (point to parameters coming in memory).
10051   //   reg_save_area
10052   SmallVector<SDValue, 8> MemOps;
10053   SDValue FIN = Op.getOperand(1);
10054   // Store gp_offset
10055   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10056                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10057                                                MVT::i32),
10058                                FIN, MachinePointerInfo(SV), false, false, 0);
10059   MemOps.push_back(Store);
10060
10061   // Store fp_offset
10062   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10063                     FIN, DAG.getIntPtrConstant(4));
10064   Store = DAG.getStore(Op.getOperand(0), DL,
10065                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10066                                        MVT::i32),
10067                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10068   MemOps.push_back(Store);
10069
10070   // Store ptr to overflow_arg_area
10071   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10072                     FIN, DAG.getIntPtrConstant(4));
10073   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10074                                     getPointerTy());
10075   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10076                        MachinePointerInfo(SV, 8),
10077                        false, false, 0);
10078   MemOps.push_back(Store);
10079
10080   // Store ptr to reg_save_area.
10081   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10082                     FIN, DAG.getIntPtrConstant(8));
10083   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10084                                     getPointerTy());
10085   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10086                        MachinePointerInfo(SV, 16), false, false, 0);
10087   MemOps.push_back(Store);
10088   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10089                      &MemOps[0], MemOps.size());
10090 }
10091
10092 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10093   assert(Subtarget->is64Bit() &&
10094          "LowerVAARG only handles 64-bit va_arg!");
10095   assert((Subtarget->isTargetLinux() ||
10096           Subtarget->isTargetDarwin()) &&
10097           "Unhandled target in LowerVAARG");
10098   assert(Op.getNode()->getNumOperands() == 4);
10099   SDValue Chain = Op.getOperand(0);
10100   SDValue SrcPtr = Op.getOperand(1);
10101   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10102   unsigned Align = Op.getConstantOperandVal(3);
10103   DebugLoc dl = Op.getDebugLoc();
10104
10105   EVT ArgVT = Op.getNode()->getValueType(0);
10106   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10107   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10108   uint8_t ArgMode;
10109
10110   // Decide which area this value should be read from.
10111   // TODO: Implement the AMD64 ABI in its entirety. This simple
10112   // selection mechanism works only for the basic types.
10113   if (ArgVT == MVT::f80) {
10114     llvm_unreachable("va_arg for f80 not yet implemented");
10115   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10116     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10117   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10118     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10119   } else {
10120     llvm_unreachable("Unhandled argument type in LowerVAARG");
10121   }
10122
10123   if (ArgMode == 2) {
10124     // Sanity Check: Make sure using fp_offset makes sense.
10125     assert(!getTargetMachine().Options.UseSoftFloat &&
10126            !(DAG.getMachineFunction()
10127                 .getFunction()->getAttributes()
10128                 .hasAttribute(AttributeSet::FunctionIndex,
10129                               Attribute::NoImplicitFloat)) &&
10130            Subtarget->hasSSE1());
10131   }
10132
10133   // Insert VAARG_64 node into the DAG
10134   // VAARG_64 returns two values: Variable Argument Address, Chain
10135   SmallVector<SDValue, 11> InstOps;
10136   InstOps.push_back(Chain);
10137   InstOps.push_back(SrcPtr);
10138   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10139   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10140   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10141   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10142   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10143                                           VTs, &InstOps[0], InstOps.size(),
10144                                           MVT::i64,
10145                                           MachinePointerInfo(SV),
10146                                           /*Align=*/0,
10147                                           /*Volatile=*/false,
10148                                           /*ReadMem=*/true,
10149                                           /*WriteMem=*/true);
10150   Chain = VAARG.getValue(1);
10151
10152   // Load the next argument and return it
10153   return DAG.getLoad(ArgVT, dl,
10154                      Chain,
10155                      VAARG,
10156                      MachinePointerInfo(),
10157                      false, false, false, 0);
10158 }
10159
10160 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10161                            SelectionDAG &DAG) {
10162   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10163   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10164   SDValue Chain = Op.getOperand(0);
10165   SDValue DstPtr = Op.getOperand(1);
10166   SDValue SrcPtr = Op.getOperand(2);
10167   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10168   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10169   DebugLoc DL = Op.getDebugLoc();
10170
10171   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10172                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10173                        false,
10174                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10175 }
10176
10177 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
10178 // may or may not be a constant. Takes immediate version of shift as input.
10179 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10180                                    SDValue SrcOp, SDValue ShAmt,
10181                                    SelectionDAG &DAG) {
10182   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10183
10184   if (isa<ConstantSDNode>(ShAmt)) {
10185     // Constant may be a TargetConstant. Use a regular constant.
10186     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10187     switch (Opc) {
10188       default: llvm_unreachable("Unknown target vector shift node");
10189       case X86ISD::VSHLI:
10190       case X86ISD::VSRLI:
10191       case X86ISD::VSRAI:
10192         return DAG.getNode(Opc, dl, VT, SrcOp,
10193                            DAG.getConstant(ShiftAmt, MVT::i32));
10194     }
10195   }
10196
10197   // Change opcode to non-immediate version
10198   switch (Opc) {
10199     default: llvm_unreachable("Unknown target vector shift node");
10200     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10201     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10202     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10203   }
10204
10205   // Need to build a vector containing shift amount
10206   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10207   SDValue ShOps[4];
10208   ShOps[0] = ShAmt;
10209   ShOps[1] = DAG.getConstant(0, MVT::i32);
10210   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10211   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10212
10213   // The return type has to be a 128-bit type with the same element
10214   // type as the input type.
10215   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10216   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10217
10218   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10219   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10220 }
10221
10222 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10223   DebugLoc dl = Op.getDebugLoc();
10224   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10225   switch (IntNo) {
10226   default: return SDValue();    // Don't custom lower most intrinsics.
10227   // Comparison intrinsics.
10228   case Intrinsic::x86_sse_comieq_ss:
10229   case Intrinsic::x86_sse_comilt_ss:
10230   case Intrinsic::x86_sse_comile_ss:
10231   case Intrinsic::x86_sse_comigt_ss:
10232   case Intrinsic::x86_sse_comige_ss:
10233   case Intrinsic::x86_sse_comineq_ss:
10234   case Intrinsic::x86_sse_ucomieq_ss:
10235   case Intrinsic::x86_sse_ucomilt_ss:
10236   case Intrinsic::x86_sse_ucomile_ss:
10237   case Intrinsic::x86_sse_ucomigt_ss:
10238   case Intrinsic::x86_sse_ucomige_ss:
10239   case Intrinsic::x86_sse_ucomineq_ss:
10240   case Intrinsic::x86_sse2_comieq_sd:
10241   case Intrinsic::x86_sse2_comilt_sd:
10242   case Intrinsic::x86_sse2_comile_sd:
10243   case Intrinsic::x86_sse2_comigt_sd:
10244   case Intrinsic::x86_sse2_comige_sd:
10245   case Intrinsic::x86_sse2_comineq_sd:
10246   case Intrinsic::x86_sse2_ucomieq_sd:
10247   case Intrinsic::x86_sse2_ucomilt_sd:
10248   case Intrinsic::x86_sse2_ucomile_sd:
10249   case Intrinsic::x86_sse2_ucomigt_sd:
10250   case Intrinsic::x86_sse2_ucomige_sd:
10251   case Intrinsic::x86_sse2_ucomineq_sd: {
10252     unsigned Opc;
10253     ISD::CondCode CC;
10254     switch (IntNo) {
10255     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10256     case Intrinsic::x86_sse_comieq_ss:
10257     case Intrinsic::x86_sse2_comieq_sd:
10258       Opc = X86ISD::COMI;
10259       CC = ISD::SETEQ;
10260       break;
10261     case Intrinsic::x86_sse_comilt_ss:
10262     case Intrinsic::x86_sse2_comilt_sd:
10263       Opc = X86ISD::COMI;
10264       CC = ISD::SETLT;
10265       break;
10266     case Intrinsic::x86_sse_comile_ss:
10267     case Intrinsic::x86_sse2_comile_sd:
10268       Opc = X86ISD::COMI;
10269       CC = ISD::SETLE;
10270       break;
10271     case Intrinsic::x86_sse_comigt_ss:
10272     case Intrinsic::x86_sse2_comigt_sd:
10273       Opc = X86ISD::COMI;
10274       CC = ISD::SETGT;
10275       break;
10276     case Intrinsic::x86_sse_comige_ss:
10277     case Intrinsic::x86_sse2_comige_sd:
10278       Opc = X86ISD::COMI;
10279       CC = ISD::SETGE;
10280       break;
10281     case Intrinsic::x86_sse_comineq_ss:
10282     case Intrinsic::x86_sse2_comineq_sd:
10283       Opc = X86ISD::COMI;
10284       CC = ISD::SETNE;
10285       break;
10286     case Intrinsic::x86_sse_ucomieq_ss:
10287     case Intrinsic::x86_sse2_ucomieq_sd:
10288       Opc = X86ISD::UCOMI;
10289       CC = ISD::SETEQ;
10290       break;
10291     case Intrinsic::x86_sse_ucomilt_ss:
10292     case Intrinsic::x86_sse2_ucomilt_sd:
10293       Opc = X86ISD::UCOMI;
10294       CC = ISD::SETLT;
10295       break;
10296     case Intrinsic::x86_sse_ucomile_ss:
10297     case Intrinsic::x86_sse2_ucomile_sd:
10298       Opc = X86ISD::UCOMI;
10299       CC = ISD::SETLE;
10300       break;
10301     case Intrinsic::x86_sse_ucomigt_ss:
10302     case Intrinsic::x86_sse2_ucomigt_sd:
10303       Opc = X86ISD::UCOMI;
10304       CC = ISD::SETGT;
10305       break;
10306     case Intrinsic::x86_sse_ucomige_ss:
10307     case Intrinsic::x86_sse2_ucomige_sd:
10308       Opc = X86ISD::UCOMI;
10309       CC = ISD::SETGE;
10310       break;
10311     case Intrinsic::x86_sse_ucomineq_ss:
10312     case Intrinsic::x86_sse2_ucomineq_sd:
10313       Opc = X86ISD::UCOMI;
10314       CC = ISD::SETNE;
10315       break;
10316     }
10317
10318     SDValue LHS = Op.getOperand(1);
10319     SDValue RHS = Op.getOperand(2);
10320     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10321     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10322     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10323     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10324                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10325     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10326   }
10327
10328   // Arithmetic intrinsics.
10329   case Intrinsic::x86_sse2_pmulu_dq:
10330   case Intrinsic::x86_avx2_pmulu_dq:
10331     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10332                        Op.getOperand(1), Op.getOperand(2));
10333
10334   // SSE2/AVX2 sub with unsigned saturation intrinsics
10335   case Intrinsic::x86_sse2_psubus_b:
10336   case Intrinsic::x86_sse2_psubus_w:
10337   case Intrinsic::x86_avx2_psubus_b:
10338   case Intrinsic::x86_avx2_psubus_w:
10339     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10340                        Op.getOperand(1), Op.getOperand(2));
10341
10342   // SSE3/AVX horizontal add/sub intrinsics
10343   case Intrinsic::x86_sse3_hadd_ps:
10344   case Intrinsic::x86_sse3_hadd_pd:
10345   case Intrinsic::x86_avx_hadd_ps_256:
10346   case Intrinsic::x86_avx_hadd_pd_256:
10347   case Intrinsic::x86_sse3_hsub_ps:
10348   case Intrinsic::x86_sse3_hsub_pd:
10349   case Intrinsic::x86_avx_hsub_ps_256:
10350   case Intrinsic::x86_avx_hsub_pd_256:
10351   case Intrinsic::x86_ssse3_phadd_w_128:
10352   case Intrinsic::x86_ssse3_phadd_d_128:
10353   case Intrinsic::x86_avx2_phadd_w:
10354   case Intrinsic::x86_avx2_phadd_d:
10355   case Intrinsic::x86_ssse3_phsub_w_128:
10356   case Intrinsic::x86_ssse3_phsub_d_128:
10357   case Intrinsic::x86_avx2_phsub_w:
10358   case Intrinsic::x86_avx2_phsub_d: {
10359     unsigned Opcode;
10360     switch (IntNo) {
10361     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10362     case Intrinsic::x86_sse3_hadd_ps:
10363     case Intrinsic::x86_sse3_hadd_pd:
10364     case Intrinsic::x86_avx_hadd_ps_256:
10365     case Intrinsic::x86_avx_hadd_pd_256:
10366       Opcode = X86ISD::FHADD;
10367       break;
10368     case Intrinsic::x86_sse3_hsub_ps:
10369     case Intrinsic::x86_sse3_hsub_pd:
10370     case Intrinsic::x86_avx_hsub_ps_256:
10371     case Intrinsic::x86_avx_hsub_pd_256:
10372       Opcode = X86ISD::FHSUB;
10373       break;
10374     case Intrinsic::x86_ssse3_phadd_w_128:
10375     case Intrinsic::x86_ssse3_phadd_d_128:
10376     case Intrinsic::x86_avx2_phadd_w:
10377     case Intrinsic::x86_avx2_phadd_d:
10378       Opcode = X86ISD::HADD;
10379       break;
10380     case Intrinsic::x86_ssse3_phsub_w_128:
10381     case Intrinsic::x86_ssse3_phsub_d_128:
10382     case Intrinsic::x86_avx2_phsub_w:
10383     case Intrinsic::x86_avx2_phsub_d:
10384       Opcode = X86ISD::HSUB;
10385       break;
10386     }
10387     return DAG.getNode(Opcode, dl, Op.getValueType(),
10388                        Op.getOperand(1), Op.getOperand(2));
10389   }
10390
10391   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10392   case Intrinsic::x86_sse2_pmaxu_b:
10393   case Intrinsic::x86_sse41_pmaxuw:
10394   case Intrinsic::x86_sse41_pmaxud:
10395   case Intrinsic::x86_avx2_pmaxu_b:
10396   case Intrinsic::x86_avx2_pmaxu_w:
10397   case Intrinsic::x86_avx2_pmaxu_d:
10398   case Intrinsic::x86_sse2_pminu_b:
10399   case Intrinsic::x86_sse41_pminuw:
10400   case Intrinsic::x86_sse41_pminud:
10401   case Intrinsic::x86_avx2_pminu_b:
10402   case Intrinsic::x86_avx2_pminu_w:
10403   case Intrinsic::x86_avx2_pminu_d:
10404   case Intrinsic::x86_sse41_pmaxsb:
10405   case Intrinsic::x86_sse2_pmaxs_w:
10406   case Intrinsic::x86_sse41_pmaxsd:
10407   case Intrinsic::x86_avx2_pmaxs_b:
10408   case Intrinsic::x86_avx2_pmaxs_w:
10409   case Intrinsic::x86_avx2_pmaxs_d:
10410   case Intrinsic::x86_sse41_pminsb:
10411   case Intrinsic::x86_sse2_pmins_w:
10412   case Intrinsic::x86_sse41_pminsd:
10413   case Intrinsic::x86_avx2_pmins_b:
10414   case Intrinsic::x86_avx2_pmins_w:
10415   case Intrinsic::x86_avx2_pmins_d: {
10416     unsigned Opcode;
10417     switch (IntNo) {
10418     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10419     case Intrinsic::x86_sse2_pmaxu_b:
10420     case Intrinsic::x86_sse41_pmaxuw:
10421     case Intrinsic::x86_sse41_pmaxud:
10422     case Intrinsic::x86_avx2_pmaxu_b:
10423     case Intrinsic::x86_avx2_pmaxu_w:
10424     case Intrinsic::x86_avx2_pmaxu_d:
10425       Opcode = X86ISD::UMAX;
10426       break;
10427     case Intrinsic::x86_sse2_pminu_b:
10428     case Intrinsic::x86_sse41_pminuw:
10429     case Intrinsic::x86_sse41_pminud:
10430     case Intrinsic::x86_avx2_pminu_b:
10431     case Intrinsic::x86_avx2_pminu_w:
10432     case Intrinsic::x86_avx2_pminu_d:
10433       Opcode = X86ISD::UMIN;
10434       break;
10435     case Intrinsic::x86_sse41_pmaxsb:
10436     case Intrinsic::x86_sse2_pmaxs_w:
10437     case Intrinsic::x86_sse41_pmaxsd:
10438     case Intrinsic::x86_avx2_pmaxs_b:
10439     case Intrinsic::x86_avx2_pmaxs_w:
10440     case Intrinsic::x86_avx2_pmaxs_d:
10441       Opcode = X86ISD::SMAX;
10442       break;
10443     case Intrinsic::x86_sse41_pminsb:
10444     case Intrinsic::x86_sse2_pmins_w:
10445     case Intrinsic::x86_sse41_pminsd:
10446     case Intrinsic::x86_avx2_pmins_b:
10447     case Intrinsic::x86_avx2_pmins_w:
10448     case Intrinsic::x86_avx2_pmins_d:
10449       Opcode = X86ISD::SMIN;
10450       break;
10451     }
10452     return DAG.getNode(Opcode, dl, Op.getValueType(),
10453                        Op.getOperand(1), Op.getOperand(2));
10454   }
10455
10456   // SSE/SSE2/AVX floating point max/min intrinsics.
10457   case Intrinsic::x86_sse_max_ps:
10458   case Intrinsic::x86_sse2_max_pd:
10459   case Intrinsic::x86_avx_max_ps_256:
10460   case Intrinsic::x86_avx_max_pd_256:
10461   case Intrinsic::x86_sse_min_ps:
10462   case Intrinsic::x86_sse2_min_pd:
10463   case Intrinsic::x86_avx_min_ps_256:
10464   case Intrinsic::x86_avx_min_pd_256: {
10465     unsigned Opcode;
10466     switch (IntNo) {
10467     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10468     case Intrinsic::x86_sse_max_ps:
10469     case Intrinsic::x86_sse2_max_pd:
10470     case Intrinsic::x86_avx_max_ps_256:
10471     case Intrinsic::x86_avx_max_pd_256:
10472       Opcode = X86ISD::FMAX;
10473       break;
10474     case Intrinsic::x86_sse_min_ps:
10475     case Intrinsic::x86_sse2_min_pd:
10476     case Intrinsic::x86_avx_min_ps_256:
10477     case Intrinsic::x86_avx_min_pd_256:
10478       Opcode = X86ISD::FMIN;
10479       break;
10480     }
10481     return DAG.getNode(Opcode, dl, Op.getValueType(),
10482                        Op.getOperand(1), Op.getOperand(2));
10483   }
10484
10485   // AVX2 variable shift intrinsics
10486   case Intrinsic::x86_avx2_psllv_d:
10487   case Intrinsic::x86_avx2_psllv_q:
10488   case Intrinsic::x86_avx2_psllv_d_256:
10489   case Intrinsic::x86_avx2_psllv_q_256:
10490   case Intrinsic::x86_avx2_psrlv_d:
10491   case Intrinsic::x86_avx2_psrlv_q:
10492   case Intrinsic::x86_avx2_psrlv_d_256:
10493   case Intrinsic::x86_avx2_psrlv_q_256:
10494   case Intrinsic::x86_avx2_psrav_d:
10495   case Intrinsic::x86_avx2_psrav_d_256: {
10496     unsigned Opcode;
10497     switch (IntNo) {
10498     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10499     case Intrinsic::x86_avx2_psllv_d:
10500     case Intrinsic::x86_avx2_psllv_q:
10501     case Intrinsic::x86_avx2_psllv_d_256:
10502     case Intrinsic::x86_avx2_psllv_q_256:
10503       Opcode = ISD::SHL;
10504       break;
10505     case Intrinsic::x86_avx2_psrlv_d:
10506     case Intrinsic::x86_avx2_psrlv_q:
10507     case Intrinsic::x86_avx2_psrlv_d_256:
10508     case Intrinsic::x86_avx2_psrlv_q_256:
10509       Opcode = ISD::SRL;
10510       break;
10511     case Intrinsic::x86_avx2_psrav_d:
10512     case Intrinsic::x86_avx2_psrav_d_256:
10513       Opcode = ISD::SRA;
10514       break;
10515     }
10516     return DAG.getNode(Opcode, dl, Op.getValueType(),
10517                        Op.getOperand(1), Op.getOperand(2));
10518   }
10519
10520   case Intrinsic::x86_ssse3_pshuf_b_128:
10521   case Intrinsic::x86_avx2_pshuf_b:
10522     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10523                        Op.getOperand(1), Op.getOperand(2));
10524
10525   case Intrinsic::x86_ssse3_psign_b_128:
10526   case Intrinsic::x86_ssse3_psign_w_128:
10527   case Intrinsic::x86_ssse3_psign_d_128:
10528   case Intrinsic::x86_avx2_psign_b:
10529   case Intrinsic::x86_avx2_psign_w:
10530   case Intrinsic::x86_avx2_psign_d:
10531     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10532                        Op.getOperand(1), Op.getOperand(2));
10533
10534   case Intrinsic::x86_sse41_insertps:
10535     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10536                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10537
10538   case Intrinsic::x86_avx_vperm2f128_ps_256:
10539   case Intrinsic::x86_avx_vperm2f128_pd_256:
10540   case Intrinsic::x86_avx_vperm2f128_si_256:
10541   case Intrinsic::x86_avx2_vperm2i128:
10542     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10543                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10544
10545   case Intrinsic::x86_avx2_permd:
10546   case Intrinsic::x86_avx2_permps:
10547     // Operands intentionally swapped. Mask is last operand to intrinsic,
10548     // but second operand for node/intruction.
10549     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10550                        Op.getOperand(2), Op.getOperand(1));
10551
10552   case Intrinsic::x86_sse_sqrt_ps:
10553   case Intrinsic::x86_sse2_sqrt_pd:
10554   case Intrinsic::x86_avx_sqrt_ps_256:
10555   case Intrinsic::x86_avx_sqrt_pd_256:
10556     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10557
10558   // ptest and testp intrinsics. The intrinsic these come from are designed to
10559   // return an integer value, not just an instruction so lower it to the ptest
10560   // or testp pattern and a setcc for the result.
10561   case Intrinsic::x86_sse41_ptestz:
10562   case Intrinsic::x86_sse41_ptestc:
10563   case Intrinsic::x86_sse41_ptestnzc:
10564   case Intrinsic::x86_avx_ptestz_256:
10565   case Intrinsic::x86_avx_ptestc_256:
10566   case Intrinsic::x86_avx_ptestnzc_256:
10567   case Intrinsic::x86_avx_vtestz_ps:
10568   case Intrinsic::x86_avx_vtestc_ps:
10569   case Intrinsic::x86_avx_vtestnzc_ps:
10570   case Intrinsic::x86_avx_vtestz_pd:
10571   case Intrinsic::x86_avx_vtestc_pd:
10572   case Intrinsic::x86_avx_vtestnzc_pd:
10573   case Intrinsic::x86_avx_vtestz_ps_256:
10574   case Intrinsic::x86_avx_vtestc_ps_256:
10575   case Intrinsic::x86_avx_vtestnzc_ps_256:
10576   case Intrinsic::x86_avx_vtestz_pd_256:
10577   case Intrinsic::x86_avx_vtestc_pd_256:
10578   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10579     bool IsTestPacked = false;
10580     unsigned X86CC;
10581     switch (IntNo) {
10582     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10583     case Intrinsic::x86_avx_vtestz_ps:
10584     case Intrinsic::x86_avx_vtestz_pd:
10585     case Intrinsic::x86_avx_vtestz_ps_256:
10586     case Intrinsic::x86_avx_vtestz_pd_256:
10587       IsTestPacked = true; // Fallthrough
10588     case Intrinsic::x86_sse41_ptestz:
10589     case Intrinsic::x86_avx_ptestz_256:
10590       // ZF = 1
10591       X86CC = X86::COND_E;
10592       break;
10593     case Intrinsic::x86_avx_vtestc_ps:
10594     case Intrinsic::x86_avx_vtestc_pd:
10595     case Intrinsic::x86_avx_vtestc_ps_256:
10596     case Intrinsic::x86_avx_vtestc_pd_256:
10597       IsTestPacked = true; // Fallthrough
10598     case Intrinsic::x86_sse41_ptestc:
10599     case Intrinsic::x86_avx_ptestc_256:
10600       // CF = 1
10601       X86CC = X86::COND_B;
10602       break;
10603     case Intrinsic::x86_avx_vtestnzc_ps:
10604     case Intrinsic::x86_avx_vtestnzc_pd:
10605     case Intrinsic::x86_avx_vtestnzc_ps_256:
10606     case Intrinsic::x86_avx_vtestnzc_pd_256:
10607       IsTestPacked = true; // Fallthrough
10608     case Intrinsic::x86_sse41_ptestnzc:
10609     case Intrinsic::x86_avx_ptestnzc_256:
10610       // ZF and CF = 0
10611       X86CC = X86::COND_A;
10612       break;
10613     }
10614
10615     SDValue LHS = Op.getOperand(1);
10616     SDValue RHS = Op.getOperand(2);
10617     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10618     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10619     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10620     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10621     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10622   }
10623
10624   // SSE/AVX shift intrinsics
10625   case Intrinsic::x86_sse2_psll_w:
10626   case Intrinsic::x86_sse2_psll_d:
10627   case Intrinsic::x86_sse2_psll_q:
10628   case Intrinsic::x86_avx2_psll_w:
10629   case Intrinsic::x86_avx2_psll_d:
10630   case Intrinsic::x86_avx2_psll_q:
10631   case Intrinsic::x86_sse2_psrl_w:
10632   case Intrinsic::x86_sse2_psrl_d:
10633   case Intrinsic::x86_sse2_psrl_q:
10634   case Intrinsic::x86_avx2_psrl_w:
10635   case Intrinsic::x86_avx2_psrl_d:
10636   case Intrinsic::x86_avx2_psrl_q:
10637   case Intrinsic::x86_sse2_psra_w:
10638   case Intrinsic::x86_sse2_psra_d:
10639   case Intrinsic::x86_avx2_psra_w:
10640   case Intrinsic::x86_avx2_psra_d: {
10641     unsigned Opcode;
10642     switch (IntNo) {
10643     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10644     case Intrinsic::x86_sse2_psll_w:
10645     case Intrinsic::x86_sse2_psll_d:
10646     case Intrinsic::x86_sse2_psll_q:
10647     case Intrinsic::x86_avx2_psll_w:
10648     case Intrinsic::x86_avx2_psll_d:
10649     case Intrinsic::x86_avx2_psll_q:
10650       Opcode = X86ISD::VSHL;
10651       break;
10652     case Intrinsic::x86_sse2_psrl_w:
10653     case Intrinsic::x86_sse2_psrl_d:
10654     case Intrinsic::x86_sse2_psrl_q:
10655     case Intrinsic::x86_avx2_psrl_w:
10656     case Intrinsic::x86_avx2_psrl_d:
10657     case Intrinsic::x86_avx2_psrl_q:
10658       Opcode = X86ISD::VSRL;
10659       break;
10660     case Intrinsic::x86_sse2_psra_w:
10661     case Intrinsic::x86_sse2_psra_d:
10662     case Intrinsic::x86_avx2_psra_w:
10663     case Intrinsic::x86_avx2_psra_d:
10664       Opcode = X86ISD::VSRA;
10665       break;
10666     }
10667     return DAG.getNode(Opcode, dl, Op.getValueType(),
10668                        Op.getOperand(1), Op.getOperand(2));
10669   }
10670
10671   // SSE/AVX immediate shift intrinsics
10672   case Intrinsic::x86_sse2_pslli_w:
10673   case Intrinsic::x86_sse2_pslli_d:
10674   case Intrinsic::x86_sse2_pslli_q:
10675   case Intrinsic::x86_avx2_pslli_w:
10676   case Intrinsic::x86_avx2_pslli_d:
10677   case Intrinsic::x86_avx2_pslli_q:
10678   case Intrinsic::x86_sse2_psrli_w:
10679   case Intrinsic::x86_sse2_psrli_d:
10680   case Intrinsic::x86_sse2_psrli_q:
10681   case Intrinsic::x86_avx2_psrli_w:
10682   case Intrinsic::x86_avx2_psrli_d:
10683   case Intrinsic::x86_avx2_psrli_q:
10684   case Intrinsic::x86_sse2_psrai_w:
10685   case Intrinsic::x86_sse2_psrai_d:
10686   case Intrinsic::x86_avx2_psrai_w:
10687   case Intrinsic::x86_avx2_psrai_d: {
10688     unsigned Opcode;
10689     switch (IntNo) {
10690     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10691     case Intrinsic::x86_sse2_pslli_w:
10692     case Intrinsic::x86_sse2_pslli_d:
10693     case Intrinsic::x86_sse2_pslli_q:
10694     case Intrinsic::x86_avx2_pslli_w:
10695     case Intrinsic::x86_avx2_pslli_d:
10696     case Intrinsic::x86_avx2_pslli_q:
10697       Opcode = X86ISD::VSHLI;
10698       break;
10699     case Intrinsic::x86_sse2_psrli_w:
10700     case Intrinsic::x86_sse2_psrli_d:
10701     case Intrinsic::x86_sse2_psrli_q:
10702     case Intrinsic::x86_avx2_psrli_w:
10703     case Intrinsic::x86_avx2_psrli_d:
10704     case Intrinsic::x86_avx2_psrli_q:
10705       Opcode = X86ISD::VSRLI;
10706       break;
10707     case Intrinsic::x86_sse2_psrai_w:
10708     case Intrinsic::x86_sse2_psrai_d:
10709     case Intrinsic::x86_avx2_psrai_w:
10710     case Intrinsic::x86_avx2_psrai_d:
10711       Opcode = X86ISD::VSRAI;
10712       break;
10713     }
10714     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10715                                Op.getOperand(1), Op.getOperand(2), DAG);
10716   }
10717
10718   case Intrinsic::x86_sse42_pcmpistria128:
10719   case Intrinsic::x86_sse42_pcmpestria128:
10720   case Intrinsic::x86_sse42_pcmpistric128:
10721   case Intrinsic::x86_sse42_pcmpestric128:
10722   case Intrinsic::x86_sse42_pcmpistrio128:
10723   case Intrinsic::x86_sse42_pcmpestrio128:
10724   case Intrinsic::x86_sse42_pcmpistris128:
10725   case Intrinsic::x86_sse42_pcmpestris128:
10726   case Intrinsic::x86_sse42_pcmpistriz128:
10727   case Intrinsic::x86_sse42_pcmpestriz128: {
10728     unsigned Opcode;
10729     unsigned X86CC;
10730     switch (IntNo) {
10731     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10732     case Intrinsic::x86_sse42_pcmpistria128:
10733       Opcode = X86ISD::PCMPISTRI;
10734       X86CC = X86::COND_A;
10735       break;
10736     case Intrinsic::x86_sse42_pcmpestria128:
10737       Opcode = X86ISD::PCMPESTRI;
10738       X86CC = X86::COND_A;
10739       break;
10740     case Intrinsic::x86_sse42_pcmpistric128:
10741       Opcode = X86ISD::PCMPISTRI;
10742       X86CC = X86::COND_B;
10743       break;
10744     case Intrinsic::x86_sse42_pcmpestric128:
10745       Opcode = X86ISD::PCMPESTRI;
10746       X86CC = X86::COND_B;
10747       break;
10748     case Intrinsic::x86_sse42_pcmpistrio128:
10749       Opcode = X86ISD::PCMPISTRI;
10750       X86CC = X86::COND_O;
10751       break;
10752     case Intrinsic::x86_sse42_pcmpestrio128:
10753       Opcode = X86ISD::PCMPESTRI;
10754       X86CC = X86::COND_O;
10755       break;
10756     case Intrinsic::x86_sse42_pcmpistris128:
10757       Opcode = X86ISD::PCMPISTRI;
10758       X86CC = X86::COND_S;
10759       break;
10760     case Intrinsic::x86_sse42_pcmpestris128:
10761       Opcode = X86ISD::PCMPESTRI;
10762       X86CC = X86::COND_S;
10763       break;
10764     case Intrinsic::x86_sse42_pcmpistriz128:
10765       Opcode = X86ISD::PCMPISTRI;
10766       X86CC = X86::COND_E;
10767       break;
10768     case Intrinsic::x86_sse42_pcmpestriz128:
10769       Opcode = X86ISD::PCMPESTRI;
10770       X86CC = X86::COND_E;
10771       break;
10772     }
10773     SmallVector<SDValue, 5> NewOps;
10774     NewOps.append(Op->op_begin()+1, Op->op_end());
10775     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10776     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10777     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10778                                 DAG.getConstant(X86CC, MVT::i8),
10779                                 SDValue(PCMP.getNode(), 1));
10780     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10781   }
10782
10783   case Intrinsic::x86_sse42_pcmpistri128:
10784   case Intrinsic::x86_sse42_pcmpestri128: {
10785     unsigned Opcode;
10786     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10787       Opcode = X86ISD::PCMPISTRI;
10788     else
10789       Opcode = X86ISD::PCMPESTRI;
10790
10791     SmallVector<SDValue, 5> NewOps;
10792     NewOps.append(Op->op_begin()+1, Op->op_end());
10793     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10794     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10795   }
10796   case Intrinsic::x86_fma_vfmadd_ps:
10797   case Intrinsic::x86_fma_vfmadd_pd:
10798   case Intrinsic::x86_fma_vfmsub_ps:
10799   case Intrinsic::x86_fma_vfmsub_pd:
10800   case Intrinsic::x86_fma_vfnmadd_ps:
10801   case Intrinsic::x86_fma_vfnmadd_pd:
10802   case Intrinsic::x86_fma_vfnmsub_ps:
10803   case Intrinsic::x86_fma_vfnmsub_pd:
10804   case Intrinsic::x86_fma_vfmaddsub_ps:
10805   case Intrinsic::x86_fma_vfmaddsub_pd:
10806   case Intrinsic::x86_fma_vfmsubadd_ps:
10807   case Intrinsic::x86_fma_vfmsubadd_pd:
10808   case Intrinsic::x86_fma_vfmadd_ps_256:
10809   case Intrinsic::x86_fma_vfmadd_pd_256:
10810   case Intrinsic::x86_fma_vfmsub_ps_256:
10811   case Intrinsic::x86_fma_vfmsub_pd_256:
10812   case Intrinsic::x86_fma_vfnmadd_ps_256:
10813   case Intrinsic::x86_fma_vfnmadd_pd_256:
10814   case Intrinsic::x86_fma_vfnmsub_ps_256:
10815   case Intrinsic::x86_fma_vfnmsub_pd_256:
10816   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10817   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10818   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10819   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10820     unsigned Opc;
10821     switch (IntNo) {
10822     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10823     case Intrinsic::x86_fma_vfmadd_ps:
10824     case Intrinsic::x86_fma_vfmadd_pd:
10825     case Intrinsic::x86_fma_vfmadd_ps_256:
10826     case Intrinsic::x86_fma_vfmadd_pd_256:
10827       Opc = X86ISD::FMADD;
10828       break;
10829     case Intrinsic::x86_fma_vfmsub_ps:
10830     case Intrinsic::x86_fma_vfmsub_pd:
10831     case Intrinsic::x86_fma_vfmsub_ps_256:
10832     case Intrinsic::x86_fma_vfmsub_pd_256:
10833       Opc = X86ISD::FMSUB;
10834       break;
10835     case Intrinsic::x86_fma_vfnmadd_ps:
10836     case Intrinsic::x86_fma_vfnmadd_pd:
10837     case Intrinsic::x86_fma_vfnmadd_ps_256:
10838     case Intrinsic::x86_fma_vfnmadd_pd_256:
10839       Opc = X86ISD::FNMADD;
10840       break;
10841     case Intrinsic::x86_fma_vfnmsub_ps:
10842     case Intrinsic::x86_fma_vfnmsub_pd:
10843     case Intrinsic::x86_fma_vfnmsub_ps_256:
10844     case Intrinsic::x86_fma_vfnmsub_pd_256:
10845       Opc = X86ISD::FNMSUB;
10846       break;
10847     case Intrinsic::x86_fma_vfmaddsub_ps:
10848     case Intrinsic::x86_fma_vfmaddsub_pd:
10849     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10850     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10851       Opc = X86ISD::FMADDSUB;
10852       break;
10853     case Intrinsic::x86_fma_vfmsubadd_ps:
10854     case Intrinsic::x86_fma_vfmsubadd_pd:
10855     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10856     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10857       Opc = X86ISD::FMSUBADD;
10858       break;
10859     }
10860
10861     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10862                        Op.getOperand(2), Op.getOperand(3));
10863   }
10864   }
10865 }
10866
10867 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10868   DebugLoc dl = Op.getDebugLoc();
10869   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10870   switch (IntNo) {
10871   default: return SDValue();    // Don't custom lower most intrinsics.
10872
10873   // RDRAND intrinsics.
10874   case Intrinsic::x86_rdrand_16:
10875   case Intrinsic::x86_rdrand_32:
10876   case Intrinsic::x86_rdrand_64: {
10877     // Emit the node with the right value type.
10878     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10879     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10880
10881     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10882     // return the value from Rand, which is always 0, casted to i32.
10883     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10884                       DAG.getConstant(1, Op->getValueType(1)),
10885                       DAG.getConstant(X86::COND_B, MVT::i32),
10886                       SDValue(Result.getNode(), 1) };
10887     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10888                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10889                                   Ops, 4);
10890
10891     // Return { result, isValid, chain }.
10892     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10893                        SDValue(Result.getNode(), 2));
10894   }
10895   }
10896 }
10897
10898 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10899                                            SelectionDAG &DAG) const {
10900   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10901   MFI->setReturnAddressIsTaken(true);
10902
10903   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10904   DebugLoc dl = Op.getDebugLoc();
10905   EVT PtrVT = getPointerTy();
10906
10907   if (Depth > 0) {
10908     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10909     SDValue Offset =
10910       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10911     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10912                        DAG.getNode(ISD::ADD, dl, PtrVT,
10913                                    FrameAddr, Offset),
10914                        MachinePointerInfo(), false, false, false, 0);
10915   }
10916
10917   // Just load the return address.
10918   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10919   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10920                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10921 }
10922
10923 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10924   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10925   MFI->setFrameAddressIsTaken(true);
10926
10927   EVT VT = Op.getValueType();
10928   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10929   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10930   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10931   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10932   while (Depth--)
10933     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10934                             MachinePointerInfo(),
10935                             false, false, false, 0);
10936   return FrameAddr;
10937 }
10938
10939 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10940                                                      SelectionDAG &DAG) const {
10941   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10942 }
10943
10944 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10945   SDValue Chain     = Op.getOperand(0);
10946   SDValue Offset    = Op.getOperand(1);
10947   SDValue Handler   = Op.getOperand(2);
10948   DebugLoc dl       = Op.getDebugLoc();
10949
10950   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10951                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10952                                      getPointerTy());
10953   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10954
10955   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10956                                   DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10957   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10958   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10959                        false, false, 0);
10960   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10961
10962   return DAG.getNode(X86ISD::EH_RETURN, dl,
10963                      MVT::Other,
10964                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10965 }
10966
10967 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10968                                                SelectionDAG &DAG) const {
10969   DebugLoc DL = Op.getDebugLoc();
10970   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10971                      DAG.getVTList(MVT::i32, MVT::Other),
10972                      Op.getOperand(0), Op.getOperand(1));
10973 }
10974
10975 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10976                                                 SelectionDAG &DAG) const {
10977   DebugLoc DL = Op.getDebugLoc();
10978   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10979                      Op.getOperand(0), Op.getOperand(1));
10980 }
10981
10982 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10983   return Op.getOperand(0);
10984 }
10985
10986 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10987                                                 SelectionDAG &DAG) const {
10988   SDValue Root = Op.getOperand(0);
10989   SDValue Trmp = Op.getOperand(1); // trampoline
10990   SDValue FPtr = Op.getOperand(2); // nested function
10991   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10992   DebugLoc dl  = Op.getDebugLoc();
10993
10994   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10995   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10996
10997   if (Subtarget->is64Bit()) {
10998     SDValue OutChains[6];
10999
11000     // Large code-model.
11001     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11002     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11003
11004     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11005     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11006
11007     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11008
11009     // Load the pointer to the nested function into R11.
11010     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11011     SDValue Addr = Trmp;
11012     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11013                                 Addr, MachinePointerInfo(TrmpAddr),
11014                                 false, false, 0);
11015
11016     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11017                        DAG.getConstant(2, MVT::i64));
11018     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11019                                 MachinePointerInfo(TrmpAddr, 2),
11020                                 false, false, 2);
11021
11022     // Load the 'nest' parameter value into R10.
11023     // R10 is specified in X86CallingConv.td
11024     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11025     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11026                        DAG.getConstant(10, MVT::i64));
11027     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11028                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11029                                 false, false, 0);
11030
11031     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11032                        DAG.getConstant(12, MVT::i64));
11033     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11034                                 MachinePointerInfo(TrmpAddr, 12),
11035                                 false, false, 2);
11036
11037     // Jump to the nested function.
11038     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11039     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11040                        DAG.getConstant(20, MVT::i64));
11041     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11042                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11043                                 false, false, 0);
11044
11045     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11046     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11047                        DAG.getConstant(22, MVT::i64));
11048     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11049                                 MachinePointerInfo(TrmpAddr, 22),
11050                                 false, false, 0);
11051
11052     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11053   } else {
11054     const Function *Func =
11055       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11056     CallingConv::ID CC = Func->getCallingConv();
11057     unsigned NestReg;
11058
11059     switch (CC) {
11060     default:
11061       llvm_unreachable("Unsupported calling convention");
11062     case CallingConv::C:
11063     case CallingConv::X86_StdCall: {
11064       // Pass 'nest' parameter in ECX.
11065       // Must be kept in sync with X86CallingConv.td
11066       NestReg = X86::ECX;
11067
11068       // Check that ECX wasn't needed by an 'inreg' parameter.
11069       FunctionType *FTy = Func->getFunctionType();
11070       const AttributeSet &Attrs = Func->getAttributes();
11071
11072       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11073         unsigned InRegCount = 0;
11074         unsigned Idx = 1;
11075
11076         for (FunctionType::param_iterator I = FTy->param_begin(),
11077              E = FTy->param_end(); I != E; ++I, ++Idx)
11078           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11079             // FIXME: should only count parameters that are lowered to integers.
11080             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11081
11082         if (InRegCount > 2) {
11083           report_fatal_error("Nest register in use - reduce number of inreg"
11084                              " parameters!");
11085         }
11086       }
11087       break;
11088     }
11089     case CallingConv::X86_FastCall:
11090     case CallingConv::X86_ThisCall:
11091     case CallingConv::Fast:
11092       // Pass 'nest' parameter in EAX.
11093       // Must be kept in sync with X86CallingConv.td
11094       NestReg = X86::EAX;
11095       break;
11096     }
11097
11098     SDValue OutChains[4];
11099     SDValue Addr, Disp;
11100
11101     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11102                        DAG.getConstant(10, MVT::i32));
11103     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11104
11105     // This is storing the opcode for MOV32ri.
11106     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11107     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11108     OutChains[0] = DAG.getStore(Root, dl,
11109                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11110                                 Trmp, MachinePointerInfo(TrmpAddr),
11111                                 false, false, 0);
11112
11113     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11114                        DAG.getConstant(1, MVT::i32));
11115     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11116                                 MachinePointerInfo(TrmpAddr, 1),
11117                                 false, false, 1);
11118
11119     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11120     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11121                        DAG.getConstant(5, MVT::i32));
11122     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11123                                 MachinePointerInfo(TrmpAddr, 5),
11124                                 false, false, 1);
11125
11126     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11127                        DAG.getConstant(6, MVT::i32));
11128     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11129                                 MachinePointerInfo(TrmpAddr, 6),
11130                                 false, false, 1);
11131
11132     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11133   }
11134 }
11135
11136 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11137                                             SelectionDAG &DAG) const {
11138   /*
11139    The rounding mode is in bits 11:10 of FPSR, and has the following
11140    settings:
11141      00 Round to nearest
11142      01 Round to -inf
11143      10 Round to +inf
11144      11 Round to 0
11145
11146   FLT_ROUNDS, on the other hand, expects the following:
11147     -1 Undefined
11148      0 Round to 0
11149      1 Round to nearest
11150      2 Round to +inf
11151      3 Round to -inf
11152
11153   To perform the conversion, we do:
11154     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11155   */
11156
11157   MachineFunction &MF = DAG.getMachineFunction();
11158   const TargetMachine &TM = MF.getTarget();
11159   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11160   unsigned StackAlignment = TFI.getStackAlignment();
11161   EVT VT = Op.getValueType();
11162   DebugLoc DL = Op.getDebugLoc();
11163
11164   // Save FP Control Word to stack slot
11165   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11166   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11167
11168   MachineMemOperand *MMO =
11169    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11170                            MachineMemOperand::MOStore, 2, 2);
11171
11172   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11173   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11174                                           DAG.getVTList(MVT::Other),
11175                                           Ops, 2, MVT::i16, MMO);
11176
11177   // Load FP Control Word from stack slot
11178   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11179                             MachinePointerInfo(), false, false, false, 0);
11180
11181   // Transform as necessary
11182   SDValue CWD1 =
11183     DAG.getNode(ISD::SRL, DL, MVT::i16,
11184                 DAG.getNode(ISD::AND, DL, MVT::i16,
11185                             CWD, DAG.getConstant(0x800, MVT::i16)),
11186                 DAG.getConstant(11, MVT::i8));
11187   SDValue CWD2 =
11188     DAG.getNode(ISD::SRL, DL, MVT::i16,
11189                 DAG.getNode(ISD::AND, DL, MVT::i16,
11190                             CWD, DAG.getConstant(0x400, MVT::i16)),
11191                 DAG.getConstant(9, MVT::i8));
11192
11193   SDValue RetVal =
11194     DAG.getNode(ISD::AND, DL, MVT::i16,
11195                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11196                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11197                             DAG.getConstant(1, MVT::i16)),
11198                 DAG.getConstant(3, MVT::i16));
11199
11200   return DAG.getNode((VT.getSizeInBits() < 16 ?
11201                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11202 }
11203
11204 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11205   EVT VT = Op.getValueType();
11206   EVT OpVT = VT;
11207   unsigned NumBits = VT.getSizeInBits();
11208   DebugLoc dl = Op.getDebugLoc();
11209
11210   Op = Op.getOperand(0);
11211   if (VT == MVT::i8) {
11212     // Zero extend to i32 since there is not an i8 bsr.
11213     OpVT = MVT::i32;
11214     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11215   }
11216
11217   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11218   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11219   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11220
11221   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11222   SDValue Ops[] = {
11223     Op,
11224     DAG.getConstant(NumBits+NumBits-1, OpVT),
11225     DAG.getConstant(X86::COND_E, MVT::i8),
11226     Op.getValue(1)
11227   };
11228   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11229
11230   // Finally xor with NumBits-1.
11231   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11232
11233   if (VT == MVT::i8)
11234     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11235   return Op;
11236 }
11237
11238 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11239   EVT VT = Op.getValueType();
11240   EVT OpVT = VT;
11241   unsigned NumBits = VT.getSizeInBits();
11242   DebugLoc dl = Op.getDebugLoc();
11243
11244   Op = Op.getOperand(0);
11245   if (VT == MVT::i8) {
11246     // Zero extend to i32 since there is not an i8 bsr.
11247     OpVT = MVT::i32;
11248     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11249   }
11250
11251   // Issue a bsr (scan bits in reverse).
11252   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11253   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11254
11255   // And xor with NumBits-1.
11256   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11257
11258   if (VT == MVT::i8)
11259     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11260   return Op;
11261 }
11262
11263 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11264   EVT VT = Op.getValueType();
11265   unsigned NumBits = VT.getSizeInBits();
11266   DebugLoc dl = Op.getDebugLoc();
11267   Op = Op.getOperand(0);
11268
11269   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11270   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11271   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11272
11273   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11274   SDValue Ops[] = {
11275     Op,
11276     DAG.getConstant(NumBits, VT),
11277     DAG.getConstant(X86::COND_E, MVT::i8),
11278     Op.getValue(1)
11279   };
11280   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11281 }
11282
11283 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11284 // ones, and then concatenate the result back.
11285 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11286   EVT VT = Op.getValueType();
11287
11288   assert(VT.is256BitVector() && VT.isInteger() &&
11289          "Unsupported value type for operation");
11290
11291   unsigned NumElems = VT.getVectorNumElements();
11292   DebugLoc dl = Op.getDebugLoc();
11293
11294   // Extract the LHS vectors
11295   SDValue LHS = Op.getOperand(0);
11296   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11297   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11298
11299   // Extract the RHS vectors
11300   SDValue RHS = Op.getOperand(1);
11301   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11302   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11303
11304   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11305   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11306
11307   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11308                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11309                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11310 }
11311
11312 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11313   assert(Op.getValueType().is256BitVector() &&
11314          Op.getValueType().isInteger() &&
11315          "Only handle AVX 256-bit vector integer operation");
11316   return Lower256IntArith(Op, DAG);
11317 }
11318
11319 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11320   assert(Op.getValueType().is256BitVector() &&
11321          Op.getValueType().isInteger() &&
11322          "Only handle AVX 256-bit vector integer operation");
11323   return Lower256IntArith(Op, DAG);
11324 }
11325
11326 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11327                         SelectionDAG &DAG) {
11328   DebugLoc dl = Op.getDebugLoc();
11329   EVT VT = Op.getValueType();
11330
11331   // Decompose 256-bit ops into smaller 128-bit ops.
11332   if (VT.is256BitVector() && !Subtarget->hasInt256())
11333     return Lower256IntArith(Op, DAG);
11334
11335   SDValue A = Op.getOperand(0);
11336   SDValue B = Op.getOperand(1);
11337
11338   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11339   if (VT == MVT::v4i32) {
11340     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11341            "Should not custom lower when pmuldq is available!");
11342
11343     // Extract the odd parts.
11344     const int UnpackMask[] = { 1, -1, 3, -1 };
11345     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11346     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11347
11348     // Multiply the even parts.
11349     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11350     // Now multiply odd parts.
11351     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11352
11353     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11354     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11355
11356     // Merge the two vectors back together with a shuffle. This expands into 2
11357     // shuffles.
11358     const int ShufMask[] = { 0, 4, 2, 6 };
11359     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11360   }
11361
11362   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11363          "Only know how to lower V2I64/V4I64 multiply");
11364
11365   //  Ahi = psrlqi(a, 32);
11366   //  Bhi = psrlqi(b, 32);
11367   //
11368   //  AloBlo = pmuludq(a, b);
11369   //  AloBhi = pmuludq(a, Bhi);
11370   //  AhiBlo = pmuludq(Ahi, b);
11371
11372   //  AloBhi = psllqi(AloBhi, 32);
11373   //  AhiBlo = psllqi(AhiBlo, 32);
11374   //  return AloBlo + AloBhi + AhiBlo;
11375
11376   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11377
11378   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11379   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11380
11381   // Bit cast to 32-bit vectors for MULUDQ
11382   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11383   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11384   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11385   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11386   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11387
11388   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11389   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11390   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11391
11392   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11393   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11394
11395   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11396   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11397 }
11398
11399 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11400   EVT VT = Op.getValueType();
11401   EVT EltTy = VT.getVectorElementType();
11402   unsigned NumElts = VT.getVectorNumElements();
11403   SDValue N0 = Op.getOperand(0);
11404   DebugLoc dl = Op.getDebugLoc();
11405
11406   // Lower sdiv X, pow2-const.
11407   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11408   if (!C)
11409     return SDValue();
11410
11411   APInt SplatValue, SplatUndef;
11412   unsigned MinSplatBits;
11413   bool HasAnyUndefs;
11414   if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11415     return SDValue();
11416
11417   if ((SplatValue != 0) &&
11418       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11419     unsigned lg2 = SplatValue.countTrailingZeros();
11420     // Splat the sign bit.
11421     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11422     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11423     // Add (N0 < 0) ? abs2 - 1 : 0;
11424     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11425     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11426     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11427     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11428     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11429
11430     // If we're dividing by a positive value, we're done.  Otherwise, we must
11431     // negate the result.
11432     if (SplatValue.isNonNegative())
11433       return SRA;
11434
11435     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11436     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11437     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11438   }
11439   return SDValue();
11440 }
11441
11442 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11443
11444   EVT VT = Op.getValueType();
11445   DebugLoc dl = Op.getDebugLoc();
11446   SDValue R = Op.getOperand(0);
11447   SDValue Amt = Op.getOperand(1);
11448   LLVMContext *Context = DAG.getContext();
11449
11450   if (!Subtarget->hasSSE2())
11451     return SDValue();
11452
11453   // Optimize shl/srl/sra with constant shift amount.
11454   if (isSplatVector(Amt.getNode())) {
11455     SDValue SclrAmt = Amt->getOperand(0);
11456     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11457       uint64_t ShiftAmt = C->getZExtValue();
11458
11459       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11460           (Subtarget->hasInt256() &&
11461            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11462         if (Op.getOpcode() == ISD::SHL)
11463           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11464                              DAG.getConstant(ShiftAmt, MVT::i32));
11465         if (Op.getOpcode() == ISD::SRL)
11466           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11467                              DAG.getConstant(ShiftAmt, MVT::i32));
11468         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11469           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11470                              DAG.getConstant(ShiftAmt, MVT::i32));
11471       }
11472
11473       if (VT == MVT::v16i8) {
11474         if (Op.getOpcode() == ISD::SHL) {
11475           // Make a large shift.
11476           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11477                                     DAG.getConstant(ShiftAmt, MVT::i32));
11478           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11479           // Zero out the rightmost bits.
11480           SmallVector<SDValue, 16> V(16,
11481                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11482                                                      MVT::i8));
11483           return DAG.getNode(ISD::AND, dl, VT, SHL,
11484                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11485         }
11486         if (Op.getOpcode() == ISD::SRL) {
11487           // Make a large shift.
11488           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11489                                     DAG.getConstant(ShiftAmt, MVT::i32));
11490           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11491           // Zero out the leftmost bits.
11492           SmallVector<SDValue, 16> V(16,
11493                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11494                                                      MVT::i8));
11495           return DAG.getNode(ISD::AND, dl, VT, SRL,
11496                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11497         }
11498         if (Op.getOpcode() == ISD::SRA) {
11499           if (ShiftAmt == 7) {
11500             // R s>> 7  ===  R s< 0
11501             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11502             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11503           }
11504
11505           // R s>> a === ((R u>> a) ^ m) - m
11506           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11507           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11508                                                          MVT::i8));
11509           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11510           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11511           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11512           return Res;
11513         }
11514         llvm_unreachable("Unknown shift opcode.");
11515       }
11516
11517       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11518         if (Op.getOpcode() == ISD::SHL) {
11519           // Make a large shift.
11520           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11521                                     DAG.getConstant(ShiftAmt, MVT::i32));
11522           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11523           // Zero out the rightmost bits.
11524           SmallVector<SDValue, 32> V(32,
11525                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11526                                                      MVT::i8));
11527           return DAG.getNode(ISD::AND, dl, VT, SHL,
11528                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11529         }
11530         if (Op.getOpcode() == ISD::SRL) {
11531           // Make a large shift.
11532           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11533                                     DAG.getConstant(ShiftAmt, MVT::i32));
11534           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11535           // Zero out the leftmost bits.
11536           SmallVector<SDValue, 32> V(32,
11537                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11538                                                      MVT::i8));
11539           return DAG.getNode(ISD::AND, dl, VT, SRL,
11540                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11541         }
11542         if (Op.getOpcode() == ISD::SRA) {
11543           if (ShiftAmt == 7) {
11544             // R s>> 7  ===  R s< 0
11545             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11546             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11547           }
11548
11549           // R s>> a === ((R u>> a) ^ m) - m
11550           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11551           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11552                                                          MVT::i8));
11553           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11554           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11555           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11556           return Res;
11557         }
11558         llvm_unreachable("Unknown shift opcode.");
11559       }
11560     }
11561   }
11562
11563   // Lower SHL with variable shift amount.
11564   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11565     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11566                      DAG.getConstant(23, MVT::i32));
11567
11568     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11569     Constant *C = ConstantDataVector::get(*Context, CV);
11570     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11571     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11572                                  MachinePointerInfo::getConstantPool(),
11573                                  false, false, false, 16);
11574
11575     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11576     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11577     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11578     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11579   }
11580   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11581     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11582
11583     // a = a << 5;
11584     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11585                      DAG.getConstant(5, MVT::i32));
11586     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11587
11588     // Turn 'a' into a mask suitable for VSELECT
11589     SDValue VSelM = DAG.getConstant(0x80, VT);
11590     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11591     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11592
11593     SDValue CM1 = DAG.getConstant(0x0f, VT);
11594     SDValue CM2 = DAG.getConstant(0x3f, VT);
11595
11596     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11597     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11598     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11599                             DAG.getConstant(4, MVT::i32), DAG);
11600     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11601     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11602
11603     // a += a
11604     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11605     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11606     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11607
11608     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11609     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11610     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11611                             DAG.getConstant(2, MVT::i32), DAG);
11612     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11613     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11614
11615     // a += a
11616     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11617     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11618     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11619
11620     // return VSELECT(r, r+r, a);
11621     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11622                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11623     return R;
11624   }
11625
11626   // Decompose 256-bit shifts into smaller 128-bit shifts.
11627   if (VT.is256BitVector()) {
11628     unsigned NumElems = VT.getVectorNumElements();
11629     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11630     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11631
11632     // Extract the two vectors
11633     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11634     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11635
11636     // Recreate the shift amount vectors
11637     SDValue Amt1, Amt2;
11638     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11639       // Constant shift amount
11640       SmallVector<SDValue, 4> Amt1Csts;
11641       SmallVector<SDValue, 4> Amt2Csts;
11642       for (unsigned i = 0; i != NumElems/2; ++i)
11643         Amt1Csts.push_back(Amt->getOperand(i));
11644       for (unsigned i = NumElems/2; i != NumElems; ++i)
11645         Amt2Csts.push_back(Amt->getOperand(i));
11646
11647       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11648                                  &Amt1Csts[0], NumElems/2);
11649       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11650                                  &Amt2Csts[0], NumElems/2);
11651     } else {
11652       // Variable shift amount
11653       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11654       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11655     }
11656
11657     // Issue new vector shifts for the smaller types
11658     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11659     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11660
11661     // Concatenate the result back
11662     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11663   }
11664
11665   return SDValue();
11666 }
11667
11668 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11669   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11670   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11671   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11672   // has only one use.
11673   SDNode *N = Op.getNode();
11674   SDValue LHS = N->getOperand(0);
11675   SDValue RHS = N->getOperand(1);
11676   unsigned BaseOp = 0;
11677   unsigned Cond = 0;
11678   DebugLoc DL = Op.getDebugLoc();
11679   switch (Op.getOpcode()) {
11680   default: llvm_unreachable("Unknown ovf instruction!");
11681   case ISD::SADDO:
11682     // A subtract of one will be selected as a INC. Note that INC doesn't
11683     // set CF, so we can't do this for UADDO.
11684     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11685       if (C->isOne()) {
11686         BaseOp = X86ISD::INC;
11687         Cond = X86::COND_O;
11688         break;
11689       }
11690     BaseOp = X86ISD::ADD;
11691     Cond = X86::COND_O;
11692     break;
11693   case ISD::UADDO:
11694     BaseOp = X86ISD::ADD;
11695     Cond = X86::COND_B;
11696     break;
11697   case ISD::SSUBO:
11698     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11699     // set CF, so we can't do this for USUBO.
11700     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11701       if (C->isOne()) {
11702         BaseOp = X86ISD::DEC;
11703         Cond = X86::COND_O;
11704         break;
11705       }
11706     BaseOp = X86ISD::SUB;
11707     Cond = X86::COND_O;
11708     break;
11709   case ISD::USUBO:
11710     BaseOp = X86ISD::SUB;
11711     Cond = X86::COND_B;
11712     break;
11713   case ISD::SMULO:
11714     BaseOp = X86ISD::SMUL;
11715     Cond = X86::COND_O;
11716     break;
11717   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11718     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11719                                  MVT::i32);
11720     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11721
11722     SDValue SetCC =
11723       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11724                   DAG.getConstant(X86::COND_O, MVT::i32),
11725                   SDValue(Sum.getNode(), 2));
11726
11727     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11728   }
11729   }
11730
11731   // Also sets EFLAGS.
11732   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11733   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11734
11735   SDValue SetCC =
11736     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11737                 DAG.getConstant(Cond, MVT::i32),
11738                 SDValue(Sum.getNode(), 1));
11739
11740   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11741 }
11742
11743 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11744                                                   SelectionDAG &DAG) const {
11745   DebugLoc dl = Op.getDebugLoc();
11746   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11747   EVT VT = Op.getValueType();
11748
11749   if (!Subtarget->hasSSE2() || !VT.isVector())
11750     return SDValue();
11751
11752   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11753                       ExtraVT.getScalarType().getSizeInBits();
11754   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11755
11756   switch (VT.getSimpleVT().SimpleTy) {
11757     default: return SDValue();
11758     case MVT::v8i32:
11759     case MVT::v16i16:
11760       if (!Subtarget->hasFp256())
11761         return SDValue();
11762       if (!Subtarget->hasInt256()) {
11763         // needs to be split
11764         unsigned NumElems = VT.getVectorNumElements();
11765
11766         // Extract the LHS vectors
11767         SDValue LHS = Op.getOperand(0);
11768         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11769         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11770
11771         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11772         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11773
11774         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11775         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11776         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11777                                    ExtraNumElems/2);
11778         SDValue Extra = DAG.getValueType(ExtraVT);
11779
11780         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11781         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11782
11783         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11784       }
11785       // fall through
11786     case MVT::v4i32:
11787     case MVT::v8i16: {
11788       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11789                                          Op.getOperand(0), ShAmt, DAG);
11790       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11791     }
11792   }
11793 }
11794
11795 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11796                               SelectionDAG &DAG) {
11797   DebugLoc dl = Op.getDebugLoc();
11798
11799   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11800   // There isn't any reason to disable it if the target processor supports it.
11801   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11802     SDValue Chain = Op.getOperand(0);
11803     SDValue Zero = DAG.getConstant(0, MVT::i32);
11804     SDValue Ops[] = {
11805       DAG.getRegister(X86::ESP, MVT::i32), // Base
11806       DAG.getTargetConstant(1, MVT::i8),   // Scale
11807       DAG.getRegister(0, MVT::i32),        // Index
11808       DAG.getTargetConstant(0, MVT::i32),  // Disp
11809       DAG.getRegister(0, MVT::i32),        // Segment.
11810       Zero,
11811       Chain
11812     };
11813     SDNode *Res =
11814       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11815                           array_lengthof(Ops));
11816     return SDValue(Res, 0);
11817   }
11818
11819   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11820   if (!isDev)
11821     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11822
11823   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11824   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11825   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11826   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11827
11828   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11829   if (!Op1 && !Op2 && !Op3 && Op4)
11830     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11831
11832   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11833   if (Op1 && !Op2 && !Op3 && !Op4)
11834     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11835
11836   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11837   //           (MFENCE)>;
11838   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11839 }
11840
11841 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11842                                  SelectionDAG &DAG) {
11843   DebugLoc dl = Op.getDebugLoc();
11844   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11845     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11846   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11847     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11848
11849   // The only fence that needs an instruction is a sequentially-consistent
11850   // cross-thread fence.
11851   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11852     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11853     // no-sse2). There isn't any reason to disable it if the target processor
11854     // supports it.
11855     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11856       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11857
11858     SDValue Chain = Op.getOperand(0);
11859     SDValue Zero = DAG.getConstant(0, MVT::i32);
11860     SDValue Ops[] = {
11861       DAG.getRegister(X86::ESP, MVT::i32), // Base
11862       DAG.getTargetConstant(1, MVT::i8),   // Scale
11863       DAG.getRegister(0, MVT::i32),        // Index
11864       DAG.getTargetConstant(0, MVT::i32),  // Disp
11865       DAG.getRegister(0, MVT::i32),        // Segment.
11866       Zero,
11867       Chain
11868     };
11869     SDNode *Res =
11870       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11871                          array_lengthof(Ops));
11872     return SDValue(Res, 0);
11873   }
11874
11875   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11876   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11877 }
11878
11879 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11880                              SelectionDAG &DAG) {
11881   EVT T = Op.getValueType();
11882   DebugLoc DL = Op.getDebugLoc();
11883   unsigned Reg = 0;
11884   unsigned size = 0;
11885   switch(T.getSimpleVT().SimpleTy) {
11886   default: llvm_unreachable("Invalid value type!");
11887   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11888   case MVT::i16: Reg = X86::AX;  size = 2; break;
11889   case MVT::i32: Reg = X86::EAX; size = 4; break;
11890   case MVT::i64:
11891     assert(Subtarget->is64Bit() && "Node not type legal!");
11892     Reg = X86::RAX; size = 8;
11893     break;
11894   }
11895   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11896                                     Op.getOperand(2), SDValue());
11897   SDValue Ops[] = { cpIn.getValue(0),
11898                     Op.getOperand(1),
11899                     Op.getOperand(3),
11900                     DAG.getTargetConstant(size, MVT::i8),
11901                     cpIn.getValue(1) };
11902   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11903   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11904   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11905                                            Ops, 5, T, MMO);
11906   SDValue cpOut =
11907     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11908   return cpOut;
11909 }
11910
11911 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11912                                      SelectionDAG &DAG) {
11913   assert(Subtarget->is64Bit() && "Result not type legalized?");
11914   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11915   SDValue TheChain = Op.getOperand(0);
11916   DebugLoc dl = Op.getDebugLoc();
11917   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11918   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11919   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11920                                    rax.getValue(2));
11921   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11922                             DAG.getConstant(32, MVT::i8));
11923   SDValue Ops[] = {
11924     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11925     rdx.getValue(1)
11926   };
11927   return DAG.getMergeValues(Ops, 2, dl);
11928 }
11929
11930 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11931   EVT SrcVT = Op.getOperand(0).getValueType();
11932   EVT DstVT = Op.getValueType();
11933   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11934          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11935   assert((DstVT == MVT::i64 ||
11936           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11937          "Unexpected custom BITCAST");
11938   // i64 <=> MMX conversions are Legal.
11939   if (SrcVT==MVT::i64 && DstVT.isVector())
11940     return Op;
11941   if (DstVT==MVT::i64 && SrcVT.isVector())
11942     return Op;
11943   // MMX <=> MMX conversions are Legal.
11944   if (SrcVT.isVector() && DstVT.isVector())
11945     return Op;
11946   // All other conversions need to be expanded.
11947   return SDValue();
11948 }
11949
11950 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11951   SDNode *Node = Op.getNode();
11952   DebugLoc dl = Node->getDebugLoc();
11953   EVT T = Node->getValueType(0);
11954   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11955                               DAG.getConstant(0, T), Node->getOperand(2));
11956   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11957                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11958                        Node->getOperand(0),
11959                        Node->getOperand(1), negOp,
11960                        cast<AtomicSDNode>(Node)->getSrcValue(),
11961                        cast<AtomicSDNode>(Node)->getAlignment(),
11962                        cast<AtomicSDNode>(Node)->getOrdering(),
11963                        cast<AtomicSDNode>(Node)->getSynchScope());
11964 }
11965
11966 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11967   SDNode *Node = Op.getNode();
11968   DebugLoc dl = Node->getDebugLoc();
11969   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11970
11971   // Convert seq_cst store -> xchg
11972   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11973   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11974   //        (The only way to get a 16-byte store is cmpxchg16b)
11975   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11976   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11977       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11978     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11979                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11980                                  Node->getOperand(0),
11981                                  Node->getOperand(1), Node->getOperand(2),
11982                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11983                                  cast<AtomicSDNode>(Node)->getOrdering(),
11984                                  cast<AtomicSDNode>(Node)->getSynchScope());
11985     return Swap.getValue(1);
11986   }
11987   // Other atomic stores have a simple pattern.
11988   return Op;
11989 }
11990
11991 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11992   EVT VT = Op.getNode()->getValueType(0);
11993
11994   // Let legalize expand this if it isn't a legal type yet.
11995   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11996     return SDValue();
11997
11998   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11999
12000   unsigned Opc;
12001   bool ExtraOp = false;
12002   switch (Op.getOpcode()) {
12003   default: llvm_unreachable("Invalid code");
12004   case ISD::ADDC: Opc = X86ISD::ADD; break;
12005   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12006   case ISD::SUBC: Opc = X86ISD::SUB; break;
12007   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12008   }
12009
12010   if (!ExtraOp)
12011     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12012                        Op.getOperand(1));
12013   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12014                      Op.getOperand(1), Op.getOperand(2));
12015 }
12016
12017 /// LowerOperation - Provide custom lowering hooks for some operations.
12018 ///
12019 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12020   switch (Op.getOpcode()) {
12021   default: llvm_unreachable("Should not custom lower this!");
12022   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12023   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
12024   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12025   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12026   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12027   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12028   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12029   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12030   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12031   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12032   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12033   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12034   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12035   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12036   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12037   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12038   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12039   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12040   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12041   case ISD::SHL_PARTS:
12042   case ISD::SRA_PARTS:
12043   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12044   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12045   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12046   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12047   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12048   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12049   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12050   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12051   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12052   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12053   case ISD::FABS:               return LowerFABS(Op, DAG);
12054   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12055   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12056   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12057   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12058   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12059   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12060   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12061   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12062   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12063   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12064   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12065   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12066   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12067   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12068   case ISD::FRAME_TO_ARGS_OFFSET:
12069                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12070   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12071   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12072   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12073   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12074   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12075   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12076   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12077   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12078   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12079   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12080   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12081   case ISD::SRA:
12082   case ISD::SRL:
12083   case ISD::SHL:                return LowerShift(Op, DAG);
12084   case ISD::SADDO:
12085   case ISD::UADDO:
12086   case ISD::SSUBO:
12087   case ISD::USUBO:
12088   case ISD::SMULO:
12089   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12090   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12091   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12092   case ISD::ADDC:
12093   case ISD::ADDE:
12094   case ISD::SUBC:
12095   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12096   case ISD::ADD:                return LowerADD(Op, DAG);
12097   case ISD::SUB:                return LowerSUB(Op, DAG);
12098   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12099   }
12100 }
12101
12102 static void ReplaceATOMIC_LOAD(SDNode *Node,
12103                                   SmallVectorImpl<SDValue> &Results,
12104                                   SelectionDAG &DAG) {
12105   DebugLoc dl = Node->getDebugLoc();
12106   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12107
12108   // Convert wide load -> cmpxchg8b/cmpxchg16b
12109   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12110   //        (The only way to get a 16-byte load is cmpxchg16b)
12111   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12112   SDValue Zero = DAG.getConstant(0, VT);
12113   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12114                                Node->getOperand(0),
12115                                Node->getOperand(1), Zero, Zero,
12116                                cast<AtomicSDNode>(Node)->getMemOperand(),
12117                                cast<AtomicSDNode>(Node)->getOrdering(),
12118                                cast<AtomicSDNode>(Node)->getSynchScope());
12119   Results.push_back(Swap.getValue(0));
12120   Results.push_back(Swap.getValue(1));
12121 }
12122
12123 static void
12124 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12125                         SelectionDAG &DAG, unsigned NewOp) {
12126   DebugLoc dl = Node->getDebugLoc();
12127   assert (Node->getValueType(0) == MVT::i64 &&
12128           "Only know how to expand i64 atomics");
12129
12130   SDValue Chain = Node->getOperand(0);
12131   SDValue In1 = Node->getOperand(1);
12132   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12133                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12134   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12135                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12136   SDValue Ops[] = { Chain, In1, In2L, In2H };
12137   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12138   SDValue Result =
12139     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12140                             cast<MemSDNode>(Node)->getMemOperand());
12141   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12142   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12143   Results.push_back(Result.getValue(2));
12144 }
12145
12146 /// ReplaceNodeResults - Replace a node with an illegal result type
12147 /// with a new node built out of custom code.
12148 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12149                                            SmallVectorImpl<SDValue>&Results,
12150                                            SelectionDAG &DAG) const {
12151   DebugLoc dl = N->getDebugLoc();
12152   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12153   switch (N->getOpcode()) {
12154   default:
12155     llvm_unreachable("Do not know how to custom type legalize this operation!");
12156   case ISD::SIGN_EXTEND_INREG:
12157   case ISD::ADDC:
12158   case ISD::ADDE:
12159   case ISD::SUBC:
12160   case ISD::SUBE:
12161     // We don't want to expand or promote these.
12162     return;
12163   case ISD::FP_TO_SINT:
12164   case ISD::FP_TO_UINT: {
12165     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12166
12167     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12168       return;
12169
12170     std::pair<SDValue,SDValue> Vals =
12171         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12172     SDValue FIST = Vals.first, StackSlot = Vals.second;
12173     if (FIST.getNode() != 0) {
12174       EVT VT = N->getValueType(0);
12175       // Return a load from the stack slot.
12176       if (StackSlot.getNode() != 0)
12177         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12178                                       MachinePointerInfo(),
12179                                       false, false, false, 0));
12180       else
12181         Results.push_back(FIST);
12182     }
12183     return;
12184   }
12185   case ISD::UINT_TO_FP: {
12186     if (N->getOperand(0).getValueType() != MVT::v2i32 &&
12187         N->getValueType(0) != MVT::v2f32)
12188       return;
12189     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12190                                  N->getOperand(0));
12191     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12192                                      MVT::f64);
12193     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12194     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12195                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12196     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12197     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12198     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12199     return;
12200   }
12201   case ISD::FP_ROUND: {
12202     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12203         return;
12204     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12205     Results.push_back(V);
12206     return;
12207   }
12208   case ISD::READCYCLECOUNTER: {
12209     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12210     SDValue TheChain = N->getOperand(0);
12211     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12212     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12213                                      rd.getValue(1));
12214     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12215                                      eax.getValue(2));
12216     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12217     SDValue Ops[] = { eax, edx };
12218     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12219     Results.push_back(edx.getValue(1));
12220     return;
12221   }
12222   case ISD::ATOMIC_CMP_SWAP: {
12223     EVT T = N->getValueType(0);
12224     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12225     bool Regs64bit = T == MVT::i128;
12226     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12227     SDValue cpInL, cpInH;
12228     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12229                         DAG.getConstant(0, HalfT));
12230     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12231                         DAG.getConstant(1, HalfT));
12232     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12233                              Regs64bit ? X86::RAX : X86::EAX,
12234                              cpInL, SDValue());
12235     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12236                              Regs64bit ? X86::RDX : X86::EDX,
12237                              cpInH, cpInL.getValue(1));
12238     SDValue swapInL, swapInH;
12239     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12240                           DAG.getConstant(0, HalfT));
12241     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12242                           DAG.getConstant(1, HalfT));
12243     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12244                                Regs64bit ? X86::RBX : X86::EBX,
12245                                swapInL, cpInH.getValue(1));
12246     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12247                                Regs64bit ? X86::RCX : X86::ECX,
12248                                swapInH, swapInL.getValue(1));
12249     SDValue Ops[] = { swapInH.getValue(0),
12250                       N->getOperand(1),
12251                       swapInH.getValue(1) };
12252     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12253     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12254     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12255                                   X86ISD::LCMPXCHG8_DAG;
12256     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12257                                              Ops, 3, T, MMO);
12258     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12259                                         Regs64bit ? X86::RAX : X86::EAX,
12260                                         HalfT, Result.getValue(1));
12261     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12262                                         Regs64bit ? X86::RDX : X86::EDX,
12263                                         HalfT, cpOutL.getValue(2));
12264     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12265     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12266     Results.push_back(cpOutH.getValue(1));
12267     return;
12268   }
12269   case ISD::ATOMIC_LOAD_ADD:
12270   case ISD::ATOMIC_LOAD_AND:
12271   case ISD::ATOMIC_LOAD_NAND:
12272   case ISD::ATOMIC_LOAD_OR:
12273   case ISD::ATOMIC_LOAD_SUB:
12274   case ISD::ATOMIC_LOAD_XOR:
12275   case ISD::ATOMIC_LOAD_MAX:
12276   case ISD::ATOMIC_LOAD_MIN:
12277   case ISD::ATOMIC_LOAD_UMAX:
12278   case ISD::ATOMIC_LOAD_UMIN:
12279   case ISD::ATOMIC_SWAP: {
12280     unsigned Opc;
12281     switch (N->getOpcode()) {
12282     default: llvm_unreachable("Unexpected opcode");
12283     case ISD::ATOMIC_LOAD_ADD:
12284       Opc = X86ISD::ATOMADD64_DAG;
12285       break;
12286     case ISD::ATOMIC_LOAD_AND:
12287       Opc = X86ISD::ATOMAND64_DAG;
12288       break;
12289     case ISD::ATOMIC_LOAD_NAND:
12290       Opc = X86ISD::ATOMNAND64_DAG;
12291       break;
12292     case ISD::ATOMIC_LOAD_OR:
12293       Opc = X86ISD::ATOMOR64_DAG;
12294       break;
12295     case ISD::ATOMIC_LOAD_SUB:
12296       Opc = X86ISD::ATOMSUB64_DAG;
12297       break;
12298     case ISD::ATOMIC_LOAD_XOR:
12299       Opc = X86ISD::ATOMXOR64_DAG;
12300       break;
12301     case ISD::ATOMIC_LOAD_MAX:
12302       Opc = X86ISD::ATOMMAX64_DAG;
12303       break;
12304     case ISD::ATOMIC_LOAD_MIN:
12305       Opc = X86ISD::ATOMMIN64_DAG;
12306       break;
12307     case ISD::ATOMIC_LOAD_UMAX:
12308       Opc = X86ISD::ATOMUMAX64_DAG;
12309       break;
12310     case ISD::ATOMIC_LOAD_UMIN:
12311       Opc = X86ISD::ATOMUMIN64_DAG;
12312       break;
12313     case ISD::ATOMIC_SWAP:
12314       Opc = X86ISD::ATOMSWAP64_DAG;
12315       break;
12316     }
12317     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12318     return;
12319   }
12320   case ISD::ATOMIC_LOAD:
12321     ReplaceATOMIC_LOAD(N, Results, DAG);
12322   }
12323 }
12324
12325 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12326   switch (Opcode) {
12327   default: return NULL;
12328   case X86ISD::BSF:                return "X86ISD::BSF";
12329   case X86ISD::BSR:                return "X86ISD::BSR";
12330   case X86ISD::SHLD:               return "X86ISD::SHLD";
12331   case X86ISD::SHRD:               return "X86ISD::SHRD";
12332   case X86ISD::FAND:               return "X86ISD::FAND";
12333   case X86ISD::FOR:                return "X86ISD::FOR";
12334   case X86ISD::FXOR:               return "X86ISD::FXOR";
12335   case X86ISD::FSRL:               return "X86ISD::FSRL";
12336   case X86ISD::FILD:               return "X86ISD::FILD";
12337   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12338   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12339   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12340   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12341   case X86ISD::FLD:                return "X86ISD::FLD";
12342   case X86ISD::FST:                return "X86ISD::FST";
12343   case X86ISD::CALL:               return "X86ISD::CALL";
12344   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12345   case X86ISD::BT:                 return "X86ISD::BT";
12346   case X86ISD::CMP:                return "X86ISD::CMP";
12347   case X86ISD::COMI:               return "X86ISD::COMI";
12348   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12349   case X86ISD::SETCC:              return "X86ISD::SETCC";
12350   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12351   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12352   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12353   case X86ISD::CMOV:               return "X86ISD::CMOV";
12354   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12355   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12356   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12357   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12358   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12359   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12360   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12361   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12362   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12363   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12364   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12365   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12366   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12367   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12368   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12369   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12370   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12371   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12372   case X86ISD::HADD:               return "X86ISD::HADD";
12373   case X86ISD::HSUB:               return "X86ISD::HSUB";
12374   case X86ISD::FHADD:              return "X86ISD::FHADD";
12375   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12376   case X86ISD::UMAX:               return "X86ISD::UMAX";
12377   case X86ISD::UMIN:               return "X86ISD::UMIN";
12378   case X86ISD::SMAX:               return "X86ISD::SMAX";
12379   case X86ISD::SMIN:               return "X86ISD::SMIN";
12380   case X86ISD::FMAX:               return "X86ISD::FMAX";
12381   case X86ISD::FMIN:               return "X86ISD::FMIN";
12382   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12383   case X86ISD::FMINC:              return "X86ISD::FMINC";
12384   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12385   case X86ISD::FRCP:               return "X86ISD::FRCP";
12386   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12387   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12388   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12389   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12390   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12391   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12392   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12393   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12394   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12395   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12396   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12397   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12398   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12399   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12400   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12401   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12402   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12403   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12404   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12405   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12406   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12407   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12408   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12409   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12410   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12411   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12412   case X86ISD::VSHL:               return "X86ISD::VSHL";
12413   case X86ISD::VSRL:               return "X86ISD::VSRL";
12414   case X86ISD::VSRA:               return "X86ISD::VSRA";
12415   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12416   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12417   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12418   case X86ISD::CMPP:               return "X86ISD::CMPP";
12419   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12420   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12421   case X86ISD::ADD:                return "X86ISD::ADD";
12422   case X86ISD::SUB:                return "X86ISD::SUB";
12423   case X86ISD::ADC:                return "X86ISD::ADC";
12424   case X86ISD::SBB:                return "X86ISD::SBB";
12425   case X86ISD::SMUL:               return "X86ISD::SMUL";
12426   case X86ISD::UMUL:               return "X86ISD::UMUL";
12427   case X86ISD::INC:                return "X86ISD::INC";
12428   case X86ISD::DEC:                return "X86ISD::DEC";
12429   case X86ISD::OR:                 return "X86ISD::OR";
12430   case X86ISD::XOR:                return "X86ISD::XOR";
12431   case X86ISD::AND:                return "X86ISD::AND";
12432   case X86ISD::BLSI:               return "X86ISD::BLSI";
12433   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12434   case X86ISD::BLSR:               return "X86ISD::BLSR";
12435   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12436   case X86ISD::PTEST:              return "X86ISD::PTEST";
12437   case X86ISD::TESTP:              return "X86ISD::TESTP";
12438   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
12439   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12440   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12441   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12442   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12443   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12444   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12445   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12446   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12447   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12448   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12449   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12450   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12451   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12452   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12453   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12454   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12455   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12456   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12457   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12458   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12459   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12460   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12461   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12462   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12463   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12464   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12465   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12466   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12467   case X86ISD::SAHF:               return "X86ISD::SAHF";
12468   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12469   case X86ISD::FMADD:              return "X86ISD::FMADD";
12470   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12471   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12472   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12473   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12474   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12475   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12476   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12477   }
12478 }
12479
12480 // isLegalAddressingMode - Return true if the addressing mode represented
12481 // by AM is legal for this target, for a load/store of the specified type.
12482 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12483                                               Type *Ty) const {
12484   // X86 supports extremely general addressing modes.
12485   CodeModel::Model M = getTargetMachine().getCodeModel();
12486   Reloc::Model R = getTargetMachine().getRelocationModel();
12487
12488   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12489   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12490     return false;
12491
12492   if (AM.BaseGV) {
12493     unsigned GVFlags =
12494       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12495
12496     // If a reference to this global requires an extra load, we can't fold it.
12497     if (isGlobalStubReference(GVFlags))
12498       return false;
12499
12500     // If BaseGV requires a register for the PIC base, we cannot also have a
12501     // BaseReg specified.
12502     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12503       return false;
12504
12505     // If lower 4G is not available, then we must use rip-relative addressing.
12506     if ((M != CodeModel::Small || R != Reloc::Static) &&
12507         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12508       return false;
12509   }
12510
12511   switch (AM.Scale) {
12512   case 0:
12513   case 1:
12514   case 2:
12515   case 4:
12516   case 8:
12517     // These scales always work.
12518     break;
12519   case 3:
12520   case 5:
12521   case 9:
12522     // These scales are formed with basereg+scalereg.  Only accept if there is
12523     // no basereg yet.
12524     if (AM.HasBaseReg)
12525       return false;
12526     break;
12527   default:  // Other stuff never works.
12528     return false;
12529   }
12530
12531   return true;
12532 }
12533
12534 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12535   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12536     return false;
12537   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12538   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12539   return NumBits1 > NumBits2;
12540 }
12541
12542 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12543   return isInt<32>(Imm);
12544 }
12545
12546 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12547   // Can also use sub to handle negated immediates.
12548   return isInt<32>(Imm);
12549 }
12550
12551 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12552   if (!VT1.isInteger() || !VT2.isInteger())
12553     return false;
12554   unsigned NumBits1 = VT1.getSizeInBits();
12555   unsigned NumBits2 = VT2.getSizeInBits();
12556   return NumBits1 > NumBits2;
12557 }
12558
12559 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12560   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12561   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12562 }
12563
12564 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12565   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12566   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12567 }
12568
12569 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12570   EVT VT1 = Val.getValueType();
12571   if (isZExtFree(VT1, VT2))
12572     return true;
12573
12574   if (Val.getOpcode() != ISD::LOAD)
12575     return false;
12576
12577   if (!VT1.isSimple() || !VT1.isInteger() ||
12578       !VT2.isSimple() || !VT2.isInteger())
12579     return false;
12580
12581   switch (VT1.getSimpleVT().SimpleTy) {
12582   default: break;
12583   case MVT::i8:
12584   case MVT::i16:
12585   case MVT::i32:
12586     // X86 has 8, 16, and 32-bit zero-extending loads.
12587     return true;
12588   }
12589
12590   return false;
12591 }
12592
12593 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12594   // i16 instructions are longer (0x66 prefix) and potentially slower.
12595   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12596 }
12597
12598 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12599 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12600 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12601 /// are assumed to be legal.
12602 bool
12603 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12604                                       EVT VT) const {
12605   // Very little shuffling can be done for 64-bit vectors right now.
12606   if (VT.getSizeInBits() == 64)
12607     return false;
12608
12609   // FIXME: pshufb, blends, shifts.
12610   return (VT.getVectorNumElements() == 2 ||
12611           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12612           isMOVLMask(M, VT) ||
12613           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12614           isPSHUFDMask(M, VT) ||
12615           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12616           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12617           isPALIGNRMask(M, VT, Subtarget) ||
12618           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12619           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12620           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12621           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12622 }
12623
12624 bool
12625 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12626                                           EVT VT) const {
12627   unsigned NumElts = VT.getVectorNumElements();
12628   // FIXME: This collection of masks seems suspect.
12629   if (NumElts == 2)
12630     return true;
12631   if (NumElts == 4 && VT.is128BitVector()) {
12632     return (isMOVLMask(Mask, VT)  ||
12633             isCommutedMOVLMask(Mask, VT, true) ||
12634             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12635             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12636   }
12637   return false;
12638 }
12639
12640 //===----------------------------------------------------------------------===//
12641 //                           X86 Scheduler Hooks
12642 //===----------------------------------------------------------------------===//
12643
12644 /// Utility function to emit xbegin specifying the start of an RTM region.
12645 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12646                                      const TargetInstrInfo *TII) {
12647   DebugLoc DL = MI->getDebugLoc();
12648
12649   const BasicBlock *BB = MBB->getBasicBlock();
12650   MachineFunction::iterator I = MBB;
12651   ++I;
12652
12653   // For the v = xbegin(), we generate
12654   //
12655   // thisMBB:
12656   //  xbegin sinkMBB
12657   //
12658   // mainMBB:
12659   //  eax = -1
12660   //
12661   // sinkMBB:
12662   //  v = eax
12663
12664   MachineBasicBlock *thisMBB = MBB;
12665   MachineFunction *MF = MBB->getParent();
12666   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12667   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12668   MF->insert(I, mainMBB);
12669   MF->insert(I, sinkMBB);
12670
12671   // Transfer the remainder of BB and its successor edges to sinkMBB.
12672   sinkMBB->splice(sinkMBB->begin(), MBB,
12673                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12674   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12675
12676   // thisMBB:
12677   //  xbegin sinkMBB
12678   //  # fallthrough to mainMBB
12679   //  # abortion to sinkMBB
12680   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12681   thisMBB->addSuccessor(mainMBB);
12682   thisMBB->addSuccessor(sinkMBB);
12683
12684   // mainMBB:
12685   //  EAX = -1
12686   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12687   mainMBB->addSuccessor(sinkMBB);
12688
12689   // sinkMBB:
12690   // EAX is live into the sinkMBB
12691   sinkMBB->addLiveIn(X86::EAX);
12692   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12693           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12694     .addReg(X86::EAX);
12695
12696   MI->eraseFromParent();
12697   return sinkMBB;
12698 }
12699
12700 // Get CMPXCHG opcode for the specified data type.
12701 static unsigned getCmpXChgOpcode(EVT VT) {
12702   switch (VT.getSimpleVT().SimpleTy) {
12703   case MVT::i8:  return X86::LCMPXCHG8;
12704   case MVT::i16: return X86::LCMPXCHG16;
12705   case MVT::i32: return X86::LCMPXCHG32;
12706   case MVT::i64: return X86::LCMPXCHG64;
12707   default:
12708     break;
12709   }
12710   llvm_unreachable("Invalid operand size!");
12711 }
12712
12713 // Get LOAD opcode for the specified data type.
12714 static unsigned getLoadOpcode(EVT VT) {
12715   switch (VT.getSimpleVT().SimpleTy) {
12716   case MVT::i8:  return X86::MOV8rm;
12717   case MVT::i16: return X86::MOV16rm;
12718   case MVT::i32: return X86::MOV32rm;
12719   case MVT::i64: return X86::MOV64rm;
12720   default:
12721     break;
12722   }
12723   llvm_unreachable("Invalid operand size!");
12724 }
12725
12726 // Get opcode of the non-atomic one from the specified atomic instruction.
12727 static unsigned getNonAtomicOpcode(unsigned Opc) {
12728   switch (Opc) {
12729   case X86::ATOMAND8:  return X86::AND8rr;
12730   case X86::ATOMAND16: return X86::AND16rr;
12731   case X86::ATOMAND32: return X86::AND32rr;
12732   case X86::ATOMAND64: return X86::AND64rr;
12733   case X86::ATOMOR8:   return X86::OR8rr;
12734   case X86::ATOMOR16:  return X86::OR16rr;
12735   case X86::ATOMOR32:  return X86::OR32rr;
12736   case X86::ATOMOR64:  return X86::OR64rr;
12737   case X86::ATOMXOR8:  return X86::XOR8rr;
12738   case X86::ATOMXOR16: return X86::XOR16rr;
12739   case X86::ATOMXOR32: return X86::XOR32rr;
12740   case X86::ATOMXOR64: return X86::XOR64rr;
12741   }
12742   llvm_unreachable("Unhandled atomic-load-op opcode!");
12743 }
12744
12745 // Get opcode of the non-atomic one from the specified atomic instruction with
12746 // extra opcode.
12747 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12748                                                unsigned &ExtraOpc) {
12749   switch (Opc) {
12750   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12751   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12752   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12753   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12754   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12755   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12756   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12757   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12758   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12759   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12760   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12761   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12762   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12763   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12764   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12765   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12766   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12767   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12768   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12769   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12770   }
12771   llvm_unreachable("Unhandled atomic-load-op opcode!");
12772 }
12773
12774 // Get opcode of the non-atomic one from the specified atomic instruction for
12775 // 64-bit data type on 32-bit target.
12776 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12777   switch (Opc) {
12778   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12779   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12780   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12781   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12782   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12783   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12784   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12785   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12786   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12787   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12788   }
12789   llvm_unreachable("Unhandled atomic-load-op opcode!");
12790 }
12791
12792 // Get opcode of the non-atomic one from the specified atomic instruction for
12793 // 64-bit data type on 32-bit target with extra opcode.
12794 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12795                                                    unsigned &HiOpc,
12796                                                    unsigned &ExtraOpc) {
12797   switch (Opc) {
12798   case X86::ATOMNAND6432:
12799     ExtraOpc = X86::NOT32r;
12800     HiOpc = X86::AND32rr;
12801     return X86::AND32rr;
12802   }
12803   llvm_unreachable("Unhandled atomic-load-op opcode!");
12804 }
12805
12806 // Get pseudo CMOV opcode from the specified data type.
12807 static unsigned getPseudoCMOVOpc(EVT VT) {
12808   switch (VT.getSimpleVT().SimpleTy) {
12809   case MVT::i8:  return X86::CMOV_GR8;
12810   case MVT::i16: return X86::CMOV_GR16;
12811   case MVT::i32: return X86::CMOV_GR32;
12812   default:
12813     break;
12814   }
12815   llvm_unreachable("Unknown CMOV opcode!");
12816 }
12817
12818 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12819 // They will be translated into a spin-loop or compare-exchange loop from
12820 //
12821 //    ...
12822 //    dst = atomic-fetch-op MI.addr, MI.val
12823 //    ...
12824 //
12825 // to
12826 //
12827 //    ...
12828 //    EAX = LOAD MI.addr
12829 // loop:
12830 //    t1 = OP MI.val, EAX
12831 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12832 //    JNE loop
12833 // sink:
12834 //    dst = EAX
12835 //    ...
12836 MachineBasicBlock *
12837 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12838                                        MachineBasicBlock *MBB) const {
12839   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12840   DebugLoc DL = MI->getDebugLoc();
12841
12842   MachineFunction *MF = MBB->getParent();
12843   MachineRegisterInfo &MRI = MF->getRegInfo();
12844
12845   const BasicBlock *BB = MBB->getBasicBlock();
12846   MachineFunction::iterator I = MBB;
12847   ++I;
12848
12849   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12850          "Unexpected number of operands");
12851
12852   assert(MI->hasOneMemOperand() &&
12853          "Expected atomic-load-op to have one memoperand");
12854
12855   // Memory Reference
12856   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12857   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12858
12859   unsigned DstReg, SrcReg;
12860   unsigned MemOpndSlot;
12861
12862   unsigned CurOp = 0;
12863
12864   DstReg = MI->getOperand(CurOp++).getReg();
12865   MemOpndSlot = CurOp;
12866   CurOp += X86::AddrNumOperands;
12867   SrcReg = MI->getOperand(CurOp++).getReg();
12868
12869   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12870   MVT::SimpleValueType VT = *RC->vt_begin();
12871   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12872
12873   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12874   unsigned LOADOpc = getLoadOpcode(VT);
12875
12876   // For the atomic load-arith operator, we generate
12877   //
12878   //  thisMBB:
12879   //    EAX = LOAD [MI.addr]
12880   //  mainMBB:
12881   //    t1 = OP MI.val, EAX
12882   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12883   //    JNE mainMBB
12884   //  sinkMBB:
12885
12886   MachineBasicBlock *thisMBB = MBB;
12887   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12888   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12889   MF->insert(I, mainMBB);
12890   MF->insert(I, sinkMBB);
12891
12892   MachineInstrBuilder MIB;
12893
12894   // Transfer the remainder of BB and its successor edges to sinkMBB.
12895   sinkMBB->splice(sinkMBB->begin(), MBB,
12896                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12897   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12898
12899   // thisMBB:
12900   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12901   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12902     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12903   MIB.setMemRefs(MMOBegin, MMOEnd);
12904
12905   thisMBB->addSuccessor(mainMBB);
12906
12907   // mainMBB:
12908   MachineBasicBlock *origMainMBB = mainMBB;
12909   mainMBB->addLiveIn(AccPhyReg);
12910
12911   // Copy AccPhyReg as it is used more than once.
12912   unsigned AccReg = MRI.createVirtualRegister(RC);
12913   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12914     .addReg(AccPhyReg);
12915
12916   unsigned t1 = MRI.createVirtualRegister(RC);
12917   unsigned Opc = MI->getOpcode();
12918   switch (Opc) {
12919   default:
12920     llvm_unreachable("Unhandled atomic-load-op opcode!");
12921   case X86::ATOMAND8:
12922   case X86::ATOMAND16:
12923   case X86::ATOMAND32:
12924   case X86::ATOMAND64:
12925   case X86::ATOMOR8:
12926   case X86::ATOMOR16:
12927   case X86::ATOMOR32:
12928   case X86::ATOMOR64:
12929   case X86::ATOMXOR8:
12930   case X86::ATOMXOR16:
12931   case X86::ATOMXOR32:
12932   case X86::ATOMXOR64: {
12933     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12934     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12935       .addReg(AccReg);
12936     break;
12937   }
12938   case X86::ATOMNAND8:
12939   case X86::ATOMNAND16:
12940   case X86::ATOMNAND32:
12941   case X86::ATOMNAND64: {
12942     unsigned t2 = MRI.createVirtualRegister(RC);
12943     unsigned NOTOpc;
12944     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12945     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12946       .addReg(AccReg);
12947     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12948     break;
12949   }
12950   case X86::ATOMMAX8:
12951   case X86::ATOMMAX16:
12952   case X86::ATOMMAX32:
12953   case X86::ATOMMAX64:
12954   case X86::ATOMMIN8:
12955   case X86::ATOMMIN16:
12956   case X86::ATOMMIN32:
12957   case X86::ATOMMIN64:
12958   case X86::ATOMUMAX8:
12959   case X86::ATOMUMAX16:
12960   case X86::ATOMUMAX32:
12961   case X86::ATOMUMAX64:
12962   case X86::ATOMUMIN8:
12963   case X86::ATOMUMIN16:
12964   case X86::ATOMUMIN32:
12965   case X86::ATOMUMIN64: {
12966     unsigned CMPOpc;
12967     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12968
12969     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12970       .addReg(SrcReg)
12971       .addReg(AccReg);
12972
12973     if (Subtarget->hasCMov()) {
12974       if (VT != MVT::i8) {
12975         // Native support
12976         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12977           .addReg(SrcReg)
12978           .addReg(AccReg);
12979       } else {
12980         // Promote i8 to i32 to use CMOV32
12981         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12982         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12983         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12984         unsigned t2 = MRI.createVirtualRegister(RC32);
12985
12986         unsigned Undef = MRI.createVirtualRegister(RC32);
12987         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12988
12989         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12990           .addReg(Undef)
12991           .addReg(SrcReg)
12992           .addImm(X86::sub_8bit);
12993         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12994           .addReg(Undef)
12995           .addReg(AccReg)
12996           .addImm(X86::sub_8bit);
12997
12998         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12999           .addReg(SrcReg32)
13000           .addReg(AccReg32);
13001
13002         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
13003           .addReg(t2, 0, X86::sub_8bit);
13004       }
13005     } else {
13006       // Use pseudo select and lower them.
13007       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13008              "Invalid atomic-load-op transformation!");
13009       unsigned SelOpc = getPseudoCMOVOpc(VT);
13010       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13011       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13012       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
13013               .addReg(SrcReg).addReg(AccReg)
13014               .addImm(CC);
13015       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13016     }
13017     break;
13018   }
13019   }
13020
13021   // Copy AccPhyReg back from virtual register.
13022   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
13023     .addReg(AccReg);
13024
13025   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13026   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13027     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13028   MIB.addReg(t1);
13029   MIB.setMemRefs(MMOBegin, MMOEnd);
13030
13031   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13032
13033   mainMBB->addSuccessor(origMainMBB);
13034   mainMBB->addSuccessor(sinkMBB);
13035
13036   // sinkMBB:
13037   sinkMBB->addLiveIn(AccPhyReg);
13038
13039   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13040           TII->get(TargetOpcode::COPY), DstReg)
13041     .addReg(AccPhyReg);
13042
13043   MI->eraseFromParent();
13044   return sinkMBB;
13045 }
13046
13047 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13048 // instructions. They will be translated into a spin-loop or compare-exchange
13049 // loop from
13050 //
13051 //    ...
13052 //    dst = atomic-fetch-op MI.addr, MI.val
13053 //    ...
13054 //
13055 // to
13056 //
13057 //    ...
13058 //    EAX = LOAD [MI.addr + 0]
13059 //    EDX = LOAD [MI.addr + 4]
13060 // loop:
13061 //    EBX = OP MI.val.lo, EAX
13062 //    ECX = OP MI.val.hi, EDX
13063 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13064 //    JNE loop
13065 // sink:
13066 //    dst = EDX:EAX
13067 //    ...
13068 MachineBasicBlock *
13069 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13070                                            MachineBasicBlock *MBB) const {
13071   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13072   DebugLoc DL = MI->getDebugLoc();
13073
13074   MachineFunction *MF = MBB->getParent();
13075   MachineRegisterInfo &MRI = MF->getRegInfo();
13076
13077   const BasicBlock *BB = MBB->getBasicBlock();
13078   MachineFunction::iterator I = MBB;
13079   ++I;
13080
13081   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13082          "Unexpected number of operands");
13083
13084   assert(MI->hasOneMemOperand() &&
13085          "Expected atomic-load-op32 to have one memoperand");
13086
13087   // Memory Reference
13088   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13089   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13090
13091   unsigned DstLoReg, DstHiReg;
13092   unsigned SrcLoReg, SrcHiReg;
13093   unsigned MemOpndSlot;
13094
13095   unsigned CurOp = 0;
13096
13097   DstLoReg = MI->getOperand(CurOp++).getReg();
13098   DstHiReg = MI->getOperand(CurOp++).getReg();
13099   MemOpndSlot = CurOp;
13100   CurOp += X86::AddrNumOperands;
13101   SrcLoReg = MI->getOperand(CurOp++).getReg();
13102   SrcHiReg = MI->getOperand(CurOp++).getReg();
13103
13104   const TargetRegisterClass *RC = &X86::GR32RegClass;
13105   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13106
13107   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13108   unsigned LOADOpc = X86::MOV32rm;
13109
13110   // For the atomic load-arith operator, we generate
13111   //
13112   //  thisMBB:
13113   //    EAX = LOAD [MI.addr + 0]
13114   //    EDX = LOAD [MI.addr + 4]
13115   //  mainMBB:
13116   //    EBX = OP MI.vallo, EAX
13117   //    ECX = OP MI.valhi, EDX
13118   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13119   //    JNE mainMBB
13120   //  sinkMBB:
13121
13122   MachineBasicBlock *thisMBB = MBB;
13123   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13124   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13125   MF->insert(I, mainMBB);
13126   MF->insert(I, sinkMBB);
13127
13128   MachineInstrBuilder MIB;
13129
13130   // Transfer the remainder of BB and its successor edges to sinkMBB.
13131   sinkMBB->splice(sinkMBB->begin(), MBB,
13132                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13133   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13134
13135   // thisMBB:
13136   // Lo
13137   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
13138   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13139     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13140   MIB.setMemRefs(MMOBegin, MMOEnd);
13141   // Hi
13142   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
13143   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13144     if (i == X86::AddrDisp)
13145       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13146     else
13147       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13148   }
13149   MIB.setMemRefs(MMOBegin, MMOEnd);
13150
13151   thisMBB->addSuccessor(mainMBB);
13152
13153   // mainMBB:
13154   MachineBasicBlock *origMainMBB = mainMBB;
13155   mainMBB->addLiveIn(X86::EAX);
13156   mainMBB->addLiveIn(X86::EDX);
13157
13158   // Copy EDX:EAX as they are used more than once.
13159   unsigned LoReg = MRI.createVirtualRegister(RC);
13160   unsigned HiReg = MRI.createVirtualRegister(RC);
13161   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
13162   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
13163
13164   unsigned t1L = MRI.createVirtualRegister(RC);
13165   unsigned t1H = MRI.createVirtualRegister(RC);
13166
13167   unsigned Opc = MI->getOpcode();
13168   switch (Opc) {
13169   default:
13170     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13171   case X86::ATOMAND6432:
13172   case X86::ATOMOR6432:
13173   case X86::ATOMXOR6432:
13174   case X86::ATOMADD6432:
13175   case X86::ATOMSUB6432: {
13176     unsigned HiOpc;
13177     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13178     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
13179     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
13180     break;
13181   }
13182   case X86::ATOMNAND6432: {
13183     unsigned HiOpc, NOTOpc;
13184     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13185     unsigned t2L = MRI.createVirtualRegister(RC);
13186     unsigned t2H = MRI.createVirtualRegister(RC);
13187     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
13188     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
13189     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
13190     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
13191     break;
13192   }
13193   case X86::ATOMMAX6432:
13194   case X86::ATOMMIN6432:
13195   case X86::ATOMUMAX6432:
13196   case X86::ATOMUMIN6432: {
13197     unsigned HiOpc;
13198     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13199     unsigned cL = MRI.createVirtualRegister(RC8);
13200     unsigned cH = MRI.createVirtualRegister(RC8);
13201     unsigned cL32 = MRI.createVirtualRegister(RC);
13202     unsigned cH32 = MRI.createVirtualRegister(RC);
13203     unsigned cc = MRI.createVirtualRegister(RC);
13204     // cl := cmp src_lo, lo
13205     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13206       .addReg(SrcLoReg).addReg(LoReg);
13207     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13208     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13209     // ch := cmp src_hi, hi
13210     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13211       .addReg(SrcHiReg).addReg(HiReg);
13212     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13213     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13214     // cc := if (src_hi == hi) ? cl : ch;
13215     if (Subtarget->hasCMov()) {
13216       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13217         .addReg(cH32).addReg(cL32);
13218     } else {
13219       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13220               .addReg(cH32).addReg(cL32)
13221               .addImm(X86::COND_E);
13222       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13223     }
13224     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13225     if (Subtarget->hasCMov()) {
13226       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
13227         .addReg(SrcLoReg).addReg(LoReg);
13228       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
13229         .addReg(SrcHiReg).addReg(HiReg);
13230     } else {
13231       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
13232               .addReg(SrcLoReg).addReg(LoReg)
13233               .addImm(X86::COND_NE);
13234       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13235       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
13236               .addReg(SrcHiReg).addReg(HiReg)
13237               .addImm(X86::COND_NE);
13238       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13239     }
13240     break;
13241   }
13242   case X86::ATOMSWAP6432: {
13243     unsigned HiOpc;
13244     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13245     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
13246     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
13247     break;
13248   }
13249   }
13250
13251   // Copy EDX:EAX back from HiReg:LoReg
13252   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
13253   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
13254   // Copy ECX:EBX from t1H:t1L
13255   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
13256   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
13257
13258   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13259   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13260     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13261   MIB.setMemRefs(MMOBegin, MMOEnd);
13262
13263   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13264
13265   mainMBB->addSuccessor(origMainMBB);
13266   mainMBB->addSuccessor(sinkMBB);
13267
13268   // sinkMBB:
13269   sinkMBB->addLiveIn(X86::EAX);
13270   sinkMBB->addLiveIn(X86::EDX);
13271
13272   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13273           TII->get(TargetOpcode::COPY), DstLoReg)
13274     .addReg(X86::EAX);
13275   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13276           TII->get(TargetOpcode::COPY), DstHiReg)
13277     .addReg(X86::EDX);
13278
13279   MI->eraseFromParent();
13280   return sinkMBB;
13281 }
13282
13283 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13284 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13285 // in the .td file.
13286 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13287                                        const TargetInstrInfo *TII) {
13288   unsigned Opc;
13289   switch (MI->getOpcode()) {
13290   default: llvm_unreachable("illegal opcode!");
13291   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13292   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13293   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13294   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13295   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13296   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13297   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13298   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13299   }
13300
13301   DebugLoc dl = MI->getDebugLoc();
13302   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13303
13304   unsigned NumArgs = MI->getNumOperands();
13305   for (unsigned i = 1; i < NumArgs; ++i) {
13306     MachineOperand &Op = MI->getOperand(i);
13307     if (!(Op.isReg() && Op.isImplicit()))
13308       MIB.addOperand(Op);
13309   }
13310   if (MI->hasOneMemOperand())
13311     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13312
13313   BuildMI(*BB, MI, dl,
13314     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13315     .addReg(X86::XMM0);
13316
13317   MI->eraseFromParent();
13318   return BB;
13319 }
13320
13321 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13322 // defs in an instruction pattern
13323 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13324                                        const TargetInstrInfo *TII) {
13325   unsigned Opc;
13326   switch (MI->getOpcode()) {
13327   default: llvm_unreachable("illegal opcode!");
13328   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13329   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13330   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13331   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13332   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13333   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13334   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13335   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13336   }
13337
13338   DebugLoc dl = MI->getDebugLoc();
13339   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13340
13341   unsigned NumArgs = MI->getNumOperands(); // remove the results
13342   for (unsigned i = 1; i < NumArgs; ++i) {
13343     MachineOperand &Op = MI->getOperand(i);
13344     if (!(Op.isReg() && Op.isImplicit()))
13345       MIB.addOperand(Op);
13346   }
13347   if (MI->hasOneMemOperand())
13348     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13349
13350   BuildMI(*BB, MI, dl,
13351     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13352     .addReg(X86::ECX);
13353
13354   MI->eraseFromParent();
13355   return BB;
13356 }
13357
13358 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13359                                        const TargetInstrInfo *TII,
13360                                        const X86Subtarget* Subtarget) {
13361   DebugLoc dl = MI->getDebugLoc();
13362
13363   // Address into RAX/EAX, other two args into ECX, EDX.
13364   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13365   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13366   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13367   for (int i = 0; i < X86::AddrNumOperands; ++i)
13368     MIB.addOperand(MI->getOperand(i));
13369
13370   unsigned ValOps = X86::AddrNumOperands;
13371   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13372     .addReg(MI->getOperand(ValOps).getReg());
13373   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13374     .addReg(MI->getOperand(ValOps+1).getReg());
13375
13376   // The instruction doesn't actually take any operands though.
13377   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13378
13379   MI->eraseFromParent(); // The pseudo is gone now.
13380   return BB;
13381 }
13382
13383 MachineBasicBlock *
13384 X86TargetLowering::EmitVAARG64WithCustomInserter(
13385                    MachineInstr *MI,
13386                    MachineBasicBlock *MBB) const {
13387   // Emit va_arg instruction on X86-64.
13388
13389   // Operands to this pseudo-instruction:
13390   // 0  ) Output        : destination address (reg)
13391   // 1-5) Input         : va_list address (addr, i64mem)
13392   // 6  ) ArgSize       : Size (in bytes) of vararg type
13393   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13394   // 8  ) Align         : Alignment of type
13395   // 9  ) EFLAGS (implicit-def)
13396
13397   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13398   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13399
13400   unsigned DestReg = MI->getOperand(0).getReg();
13401   MachineOperand &Base = MI->getOperand(1);
13402   MachineOperand &Scale = MI->getOperand(2);
13403   MachineOperand &Index = MI->getOperand(3);
13404   MachineOperand &Disp = MI->getOperand(4);
13405   MachineOperand &Segment = MI->getOperand(5);
13406   unsigned ArgSize = MI->getOperand(6).getImm();
13407   unsigned ArgMode = MI->getOperand(7).getImm();
13408   unsigned Align = MI->getOperand(8).getImm();
13409
13410   // Memory Reference
13411   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13412   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13413   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13414
13415   // Machine Information
13416   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13417   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13418   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13419   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13420   DebugLoc DL = MI->getDebugLoc();
13421
13422   // struct va_list {
13423   //   i32   gp_offset
13424   //   i32   fp_offset
13425   //   i64   overflow_area (address)
13426   //   i64   reg_save_area (address)
13427   // }
13428   // sizeof(va_list) = 24
13429   // alignment(va_list) = 8
13430
13431   unsigned TotalNumIntRegs = 6;
13432   unsigned TotalNumXMMRegs = 8;
13433   bool UseGPOffset = (ArgMode == 1);
13434   bool UseFPOffset = (ArgMode == 2);
13435   unsigned MaxOffset = TotalNumIntRegs * 8 +
13436                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13437
13438   /* Align ArgSize to a multiple of 8 */
13439   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13440   bool NeedsAlign = (Align > 8);
13441
13442   MachineBasicBlock *thisMBB = MBB;
13443   MachineBasicBlock *overflowMBB;
13444   MachineBasicBlock *offsetMBB;
13445   MachineBasicBlock *endMBB;
13446
13447   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13448   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13449   unsigned OffsetReg = 0;
13450
13451   if (!UseGPOffset && !UseFPOffset) {
13452     // If we only pull from the overflow region, we don't create a branch.
13453     // We don't need to alter control flow.
13454     OffsetDestReg = 0; // unused
13455     OverflowDestReg = DestReg;
13456
13457     offsetMBB = NULL;
13458     overflowMBB = thisMBB;
13459     endMBB = thisMBB;
13460   } else {
13461     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13462     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13463     // If not, pull from overflow_area. (branch to overflowMBB)
13464     //
13465     //       thisMBB
13466     //         |     .
13467     //         |        .
13468     //     offsetMBB   overflowMBB
13469     //         |        .
13470     //         |     .
13471     //        endMBB
13472
13473     // Registers for the PHI in endMBB
13474     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13475     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13476
13477     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13478     MachineFunction *MF = MBB->getParent();
13479     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13480     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13481     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13482
13483     MachineFunction::iterator MBBIter = MBB;
13484     ++MBBIter;
13485
13486     // Insert the new basic blocks
13487     MF->insert(MBBIter, offsetMBB);
13488     MF->insert(MBBIter, overflowMBB);
13489     MF->insert(MBBIter, endMBB);
13490
13491     // Transfer the remainder of MBB and its successor edges to endMBB.
13492     endMBB->splice(endMBB->begin(), thisMBB,
13493                     llvm::next(MachineBasicBlock::iterator(MI)),
13494                     thisMBB->end());
13495     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13496
13497     // Make offsetMBB and overflowMBB successors of thisMBB
13498     thisMBB->addSuccessor(offsetMBB);
13499     thisMBB->addSuccessor(overflowMBB);
13500
13501     // endMBB is a successor of both offsetMBB and overflowMBB
13502     offsetMBB->addSuccessor(endMBB);
13503     overflowMBB->addSuccessor(endMBB);
13504
13505     // Load the offset value into a register
13506     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13507     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13508       .addOperand(Base)
13509       .addOperand(Scale)
13510       .addOperand(Index)
13511       .addDisp(Disp, UseFPOffset ? 4 : 0)
13512       .addOperand(Segment)
13513       .setMemRefs(MMOBegin, MMOEnd);
13514
13515     // Check if there is enough room left to pull this argument.
13516     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13517       .addReg(OffsetReg)
13518       .addImm(MaxOffset + 8 - ArgSizeA8);
13519
13520     // Branch to "overflowMBB" if offset >= max
13521     // Fall through to "offsetMBB" otherwise
13522     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13523       .addMBB(overflowMBB);
13524   }
13525
13526   // In offsetMBB, emit code to use the reg_save_area.
13527   if (offsetMBB) {
13528     assert(OffsetReg != 0);
13529
13530     // Read the reg_save_area address.
13531     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13532     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13533       .addOperand(Base)
13534       .addOperand(Scale)
13535       .addOperand(Index)
13536       .addDisp(Disp, 16)
13537       .addOperand(Segment)
13538       .setMemRefs(MMOBegin, MMOEnd);
13539
13540     // Zero-extend the offset
13541     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13542       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13543         .addImm(0)
13544         .addReg(OffsetReg)
13545         .addImm(X86::sub_32bit);
13546
13547     // Add the offset to the reg_save_area to get the final address.
13548     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13549       .addReg(OffsetReg64)
13550       .addReg(RegSaveReg);
13551
13552     // Compute the offset for the next argument
13553     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13554     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13555       .addReg(OffsetReg)
13556       .addImm(UseFPOffset ? 16 : 8);
13557
13558     // Store it back into the va_list.
13559     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13560       .addOperand(Base)
13561       .addOperand(Scale)
13562       .addOperand(Index)
13563       .addDisp(Disp, UseFPOffset ? 4 : 0)
13564       .addOperand(Segment)
13565       .addReg(NextOffsetReg)
13566       .setMemRefs(MMOBegin, MMOEnd);
13567
13568     // Jump to endMBB
13569     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13570       .addMBB(endMBB);
13571   }
13572
13573   //
13574   // Emit code to use overflow area
13575   //
13576
13577   // Load the overflow_area address into a register.
13578   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13579   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13580     .addOperand(Base)
13581     .addOperand(Scale)
13582     .addOperand(Index)
13583     .addDisp(Disp, 8)
13584     .addOperand(Segment)
13585     .setMemRefs(MMOBegin, MMOEnd);
13586
13587   // If we need to align it, do so. Otherwise, just copy the address
13588   // to OverflowDestReg.
13589   if (NeedsAlign) {
13590     // Align the overflow address
13591     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13592     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13593
13594     // aligned_addr = (addr + (align-1)) & ~(align-1)
13595     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13596       .addReg(OverflowAddrReg)
13597       .addImm(Align-1);
13598
13599     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13600       .addReg(TmpReg)
13601       .addImm(~(uint64_t)(Align-1));
13602   } else {
13603     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13604       .addReg(OverflowAddrReg);
13605   }
13606
13607   // Compute the next overflow address after this argument.
13608   // (the overflow address should be kept 8-byte aligned)
13609   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13610   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13611     .addReg(OverflowDestReg)
13612     .addImm(ArgSizeA8);
13613
13614   // Store the new overflow address.
13615   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13616     .addOperand(Base)
13617     .addOperand(Scale)
13618     .addOperand(Index)
13619     .addDisp(Disp, 8)
13620     .addOperand(Segment)
13621     .addReg(NextAddrReg)
13622     .setMemRefs(MMOBegin, MMOEnd);
13623
13624   // If we branched, emit the PHI to the front of endMBB.
13625   if (offsetMBB) {
13626     BuildMI(*endMBB, endMBB->begin(), DL,
13627             TII->get(X86::PHI), DestReg)
13628       .addReg(OffsetDestReg).addMBB(offsetMBB)
13629       .addReg(OverflowDestReg).addMBB(overflowMBB);
13630   }
13631
13632   // Erase the pseudo instruction
13633   MI->eraseFromParent();
13634
13635   return endMBB;
13636 }
13637
13638 MachineBasicBlock *
13639 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13640                                                  MachineInstr *MI,
13641                                                  MachineBasicBlock *MBB) const {
13642   // Emit code to save XMM registers to the stack. The ABI says that the
13643   // number of registers to save is given in %al, so it's theoretically
13644   // possible to do an indirect jump trick to avoid saving all of them,
13645   // however this code takes a simpler approach and just executes all
13646   // of the stores if %al is non-zero. It's less code, and it's probably
13647   // easier on the hardware branch predictor, and stores aren't all that
13648   // expensive anyway.
13649
13650   // Create the new basic blocks. One block contains all the XMM stores,
13651   // and one block is the final destination regardless of whether any
13652   // stores were performed.
13653   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13654   MachineFunction *F = MBB->getParent();
13655   MachineFunction::iterator MBBIter = MBB;
13656   ++MBBIter;
13657   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13658   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13659   F->insert(MBBIter, XMMSaveMBB);
13660   F->insert(MBBIter, EndMBB);
13661
13662   // Transfer the remainder of MBB and its successor edges to EndMBB.
13663   EndMBB->splice(EndMBB->begin(), MBB,
13664                  llvm::next(MachineBasicBlock::iterator(MI)),
13665                  MBB->end());
13666   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13667
13668   // The original block will now fall through to the XMM save block.
13669   MBB->addSuccessor(XMMSaveMBB);
13670   // The XMMSaveMBB will fall through to the end block.
13671   XMMSaveMBB->addSuccessor(EndMBB);
13672
13673   // Now add the instructions.
13674   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13675   DebugLoc DL = MI->getDebugLoc();
13676
13677   unsigned CountReg = MI->getOperand(0).getReg();
13678   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13679   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13680
13681   if (!Subtarget->isTargetWin64()) {
13682     // If %al is 0, branch around the XMM save block.
13683     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13684     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13685     MBB->addSuccessor(EndMBB);
13686   }
13687
13688   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13689   // In the XMM save block, save all the XMM argument registers.
13690   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13691     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13692     MachineMemOperand *MMO =
13693       F->getMachineMemOperand(
13694           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13695         MachineMemOperand::MOStore,
13696         /*Size=*/16, /*Align=*/16);
13697     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13698       .addFrameIndex(RegSaveFrameIndex)
13699       .addImm(/*Scale=*/1)
13700       .addReg(/*IndexReg=*/0)
13701       .addImm(/*Disp=*/Offset)
13702       .addReg(/*Segment=*/0)
13703       .addReg(MI->getOperand(i).getReg())
13704       .addMemOperand(MMO);
13705   }
13706
13707   MI->eraseFromParent();   // The pseudo instruction is gone now.
13708
13709   return EndMBB;
13710 }
13711
13712 // The EFLAGS operand of SelectItr might be missing a kill marker
13713 // because there were multiple uses of EFLAGS, and ISel didn't know
13714 // which to mark. Figure out whether SelectItr should have had a
13715 // kill marker, and set it if it should. Returns the correct kill
13716 // marker value.
13717 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13718                                      MachineBasicBlock* BB,
13719                                      const TargetRegisterInfo* TRI) {
13720   // Scan forward through BB for a use/def of EFLAGS.
13721   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13722   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13723     const MachineInstr& mi = *miI;
13724     if (mi.readsRegister(X86::EFLAGS))
13725       return false;
13726     if (mi.definesRegister(X86::EFLAGS))
13727       break; // Should have kill-flag - update below.
13728   }
13729
13730   // If we hit the end of the block, check whether EFLAGS is live into a
13731   // successor.
13732   if (miI == BB->end()) {
13733     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13734                                           sEnd = BB->succ_end();
13735          sItr != sEnd; ++sItr) {
13736       MachineBasicBlock* succ = *sItr;
13737       if (succ->isLiveIn(X86::EFLAGS))
13738         return false;
13739     }
13740   }
13741
13742   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13743   // out. SelectMI should have a kill flag on EFLAGS.
13744   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13745   return true;
13746 }
13747
13748 MachineBasicBlock *
13749 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13750                                      MachineBasicBlock *BB) const {
13751   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13752   DebugLoc DL = MI->getDebugLoc();
13753
13754   // To "insert" a SELECT_CC instruction, we actually have to insert the
13755   // diamond control-flow pattern.  The incoming instruction knows the
13756   // destination vreg to set, the condition code register to branch on, the
13757   // true/false values to select between, and a branch opcode to use.
13758   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13759   MachineFunction::iterator It = BB;
13760   ++It;
13761
13762   //  thisMBB:
13763   //  ...
13764   //   TrueVal = ...
13765   //   cmpTY ccX, r1, r2
13766   //   bCC copy1MBB
13767   //   fallthrough --> copy0MBB
13768   MachineBasicBlock *thisMBB = BB;
13769   MachineFunction *F = BB->getParent();
13770   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13771   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13772   F->insert(It, copy0MBB);
13773   F->insert(It, sinkMBB);
13774
13775   // If the EFLAGS register isn't dead in the terminator, then claim that it's
13776   // live into the sink and copy blocks.
13777   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13778   if (!MI->killsRegister(X86::EFLAGS) &&
13779       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13780     copy0MBB->addLiveIn(X86::EFLAGS);
13781     sinkMBB->addLiveIn(X86::EFLAGS);
13782   }
13783
13784   // Transfer the remainder of BB and its successor edges to sinkMBB.
13785   sinkMBB->splice(sinkMBB->begin(), BB,
13786                   llvm::next(MachineBasicBlock::iterator(MI)),
13787                   BB->end());
13788   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13789
13790   // Add the true and fallthrough blocks as its successors.
13791   BB->addSuccessor(copy0MBB);
13792   BB->addSuccessor(sinkMBB);
13793
13794   // Create the conditional branch instruction.
13795   unsigned Opc =
13796     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13797   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13798
13799   //  copy0MBB:
13800   //   %FalseValue = ...
13801   //   # fallthrough to sinkMBB
13802   copy0MBB->addSuccessor(sinkMBB);
13803
13804   //  sinkMBB:
13805   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13806   //  ...
13807   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13808           TII->get(X86::PHI), MI->getOperand(0).getReg())
13809     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13810     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13811
13812   MI->eraseFromParent();   // The pseudo instruction is gone now.
13813   return sinkMBB;
13814 }
13815
13816 MachineBasicBlock *
13817 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13818                                         bool Is64Bit) const {
13819   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13820   DebugLoc DL = MI->getDebugLoc();
13821   MachineFunction *MF = BB->getParent();
13822   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13823
13824   assert(getTargetMachine().Options.EnableSegmentedStacks);
13825
13826   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13827   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13828
13829   // BB:
13830   //  ... [Till the alloca]
13831   // If stacklet is not large enough, jump to mallocMBB
13832   //
13833   // bumpMBB:
13834   //  Allocate by subtracting from RSP
13835   //  Jump to continueMBB
13836   //
13837   // mallocMBB:
13838   //  Allocate by call to runtime
13839   //
13840   // continueMBB:
13841   //  ...
13842   //  [rest of original BB]
13843   //
13844
13845   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13846   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13847   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13848
13849   MachineRegisterInfo &MRI = MF->getRegInfo();
13850   const TargetRegisterClass *AddrRegClass =
13851     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13852
13853   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13854     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13855     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13856     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13857     sizeVReg = MI->getOperand(1).getReg(),
13858     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13859
13860   MachineFunction::iterator MBBIter = BB;
13861   ++MBBIter;
13862
13863   MF->insert(MBBIter, bumpMBB);
13864   MF->insert(MBBIter, mallocMBB);
13865   MF->insert(MBBIter, continueMBB);
13866
13867   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13868                       (MachineBasicBlock::iterator(MI)), BB->end());
13869   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13870
13871   // Add code to the main basic block to check if the stack limit has been hit,
13872   // and if so, jump to mallocMBB otherwise to bumpMBB.
13873   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13874   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13875     .addReg(tmpSPVReg).addReg(sizeVReg);
13876   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13877     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13878     .addReg(SPLimitVReg);
13879   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13880
13881   // bumpMBB simply decreases the stack pointer, since we know the current
13882   // stacklet has enough space.
13883   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13884     .addReg(SPLimitVReg);
13885   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13886     .addReg(SPLimitVReg);
13887   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13888
13889   // Calls into a routine in libgcc to allocate more space from the heap.
13890   const uint32_t *RegMask =
13891     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13892   if (Is64Bit) {
13893     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13894       .addReg(sizeVReg);
13895     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13896       .addExternalSymbol("__morestack_allocate_stack_space")
13897       .addRegMask(RegMask)
13898       .addReg(X86::RDI, RegState::Implicit)
13899       .addReg(X86::RAX, RegState::ImplicitDefine);
13900   } else {
13901     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13902       .addImm(12);
13903     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13904     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13905       .addExternalSymbol("__morestack_allocate_stack_space")
13906       .addRegMask(RegMask)
13907       .addReg(X86::EAX, RegState::ImplicitDefine);
13908   }
13909
13910   if (!Is64Bit)
13911     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13912       .addImm(16);
13913
13914   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13915     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13916   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13917
13918   // Set up the CFG correctly.
13919   BB->addSuccessor(bumpMBB);
13920   BB->addSuccessor(mallocMBB);
13921   mallocMBB->addSuccessor(continueMBB);
13922   bumpMBB->addSuccessor(continueMBB);
13923
13924   // Take care of the PHI nodes.
13925   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13926           MI->getOperand(0).getReg())
13927     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13928     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13929
13930   // Delete the original pseudo instruction.
13931   MI->eraseFromParent();
13932
13933   // And we're done.
13934   return continueMBB;
13935 }
13936
13937 MachineBasicBlock *
13938 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13939                                           MachineBasicBlock *BB) const {
13940   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13941   DebugLoc DL = MI->getDebugLoc();
13942
13943   assert(!Subtarget->isTargetEnvMacho());
13944
13945   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13946   // non-trivial part is impdef of ESP.
13947
13948   if (Subtarget->isTargetWin64()) {
13949     if (Subtarget->isTargetCygMing()) {
13950       // ___chkstk(Mingw64):
13951       // Clobbers R10, R11, RAX and EFLAGS.
13952       // Updates RSP.
13953       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13954         .addExternalSymbol("___chkstk")
13955         .addReg(X86::RAX, RegState::Implicit)
13956         .addReg(X86::RSP, RegState::Implicit)
13957         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13958         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13959         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13960     } else {
13961       // __chkstk(MSVCRT): does not update stack pointer.
13962       // Clobbers R10, R11 and EFLAGS.
13963       // FIXME: RAX(allocated size) might be reused and not killed.
13964       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13965         .addExternalSymbol("__chkstk")
13966         .addReg(X86::RAX, RegState::Implicit)
13967         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13968       // RAX has the offset to subtracted from RSP.
13969       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13970         .addReg(X86::RSP)
13971         .addReg(X86::RAX);
13972     }
13973   } else {
13974     const char *StackProbeSymbol =
13975       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13976
13977     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13978       .addExternalSymbol(StackProbeSymbol)
13979       .addReg(X86::EAX, RegState::Implicit)
13980       .addReg(X86::ESP, RegState::Implicit)
13981       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13982       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13983       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13984   }
13985
13986   MI->eraseFromParent();   // The pseudo instruction is gone now.
13987   return BB;
13988 }
13989
13990 MachineBasicBlock *
13991 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13992                                       MachineBasicBlock *BB) const {
13993   // This is pretty easy.  We're taking the value that we received from
13994   // our load from the relocation, sticking it in either RDI (x86-64)
13995   // or EAX and doing an indirect call.  The return value will then
13996   // be in the normal return register.
13997   const X86InstrInfo *TII
13998     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13999   DebugLoc DL = MI->getDebugLoc();
14000   MachineFunction *F = BB->getParent();
14001
14002   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14003   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14004
14005   // Get a register mask for the lowered call.
14006   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14007   // proper register mask.
14008   const uint32_t *RegMask =
14009     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14010   if (Subtarget->is64Bit()) {
14011     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14012                                       TII->get(X86::MOV64rm), X86::RDI)
14013     .addReg(X86::RIP)
14014     .addImm(0).addReg(0)
14015     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14016                       MI->getOperand(3).getTargetFlags())
14017     .addReg(0);
14018     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14019     addDirectMem(MIB, X86::RDI);
14020     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14021   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14022     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14023                                       TII->get(X86::MOV32rm), X86::EAX)
14024     .addReg(0)
14025     .addImm(0).addReg(0)
14026     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14027                       MI->getOperand(3).getTargetFlags())
14028     .addReg(0);
14029     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14030     addDirectMem(MIB, X86::EAX);
14031     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14032   } else {
14033     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14034                                       TII->get(X86::MOV32rm), X86::EAX)
14035     .addReg(TII->getGlobalBaseReg(F))
14036     .addImm(0).addReg(0)
14037     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14038                       MI->getOperand(3).getTargetFlags())
14039     .addReg(0);
14040     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14041     addDirectMem(MIB, X86::EAX);
14042     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14043   }
14044
14045   MI->eraseFromParent(); // The pseudo instruction is gone now.
14046   return BB;
14047 }
14048
14049 MachineBasicBlock *
14050 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14051                                     MachineBasicBlock *MBB) const {
14052   DebugLoc DL = MI->getDebugLoc();
14053   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14054
14055   MachineFunction *MF = MBB->getParent();
14056   MachineRegisterInfo &MRI = MF->getRegInfo();
14057
14058   const BasicBlock *BB = MBB->getBasicBlock();
14059   MachineFunction::iterator I = MBB;
14060   ++I;
14061
14062   // Memory Reference
14063   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14064   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14065
14066   unsigned DstReg;
14067   unsigned MemOpndSlot = 0;
14068
14069   unsigned CurOp = 0;
14070
14071   DstReg = MI->getOperand(CurOp++).getReg();
14072   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14073   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14074   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14075   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14076
14077   MemOpndSlot = CurOp;
14078
14079   MVT PVT = getPointerTy();
14080   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14081          "Invalid Pointer Size!");
14082
14083   // For v = setjmp(buf), we generate
14084   //
14085   // thisMBB:
14086   //  buf[LabelOffset] = restoreMBB
14087   //  SjLjSetup restoreMBB
14088   //
14089   // mainMBB:
14090   //  v_main = 0
14091   //
14092   // sinkMBB:
14093   //  v = phi(main, restore)
14094   //
14095   // restoreMBB:
14096   //  v_restore = 1
14097
14098   MachineBasicBlock *thisMBB = MBB;
14099   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14100   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14101   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14102   MF->insert(I, mainMBB);
14103   MF->insert(I, sinkMBB);
14104   MF->push_back(restoreMBB);
14105
14106   MachineInstrBuilder MIB;
14107
14108   // Transfer the remainder of BB and its successor edges to sinkMBB.
14109   sinkMBB->splice(sinkMBB->begin(), MBB,
14110                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14111   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14112
14113   // thisMBB:
14114   unsigned PtrStoreOpc = 0;
14115   unsigned LabelReg = 0;
14116   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14117   Reloc::Model RM = getTargetMachine().getRelocationModel();
14118   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14119                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14120
14121   // Prepare IP either in reg or imm.
14122   if (!UseImmLabel) {
14123     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14124     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14125     LabelReg = MRI.createVirtualRegister(PtrRC);
14126     if (Subtarget->is64Bit()) {
14127       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14128               .addReg(X86::RIP)
14129               .addImm(0)
14130               .addReg(0)
14131               .addMBB(restoreMBB)
14132               .addReg(0);
14133     } else {
14134       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14135       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14136               .addReg(XII->getGlobalBaseReg(MF))
14137               .addImm(0)
14138               .addReg(0)
14139               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14140               .addReg(0);
14141     }
14142   } else
14143     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14144   // Store IP
14145   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14146   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14147     if (i == X86::AddrDisp)
14148       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14149     else
14150       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14151   }
14152   if (!UseImmLabel)
14153     MIB.addReg(LabelReg);
14154   else
14155     MIB.addMBB(restoreMBB);
14156   MIB.setMemRefs(MMOBegin, MMOEnd);
14157   // Setup
14158   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14159           .addMBB(restoreMBB);
14160   MIB.addRegMask(RegInfo->getNoPreservedMask());
14161   thisMBB->addSuccessor(mainMBB);
14162   thisMBB->addSuccessor(restoreMBB);
14163
14164   // mainMBB:
14165   //  EAX = 0
14166   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14167   mainMBB->addSuccessor(sinkMBB);
14168
14169   // sinkMBB:
14170   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14171           TII->get(X86::PHI), DstReg)
14172     .addReg(mainDstReg).addMBB(mainMBB)
14173     .addReg(restoreDstReg).addMBB(restoreMBB);
14174
14175   // restoreMBB:
14176   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14177   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14178   restoreMBB->addSuccessor(sinkMBB);
14179
14180   MI->eraseFromParent();
14181   return sinkMBB;
14182 }
14183
14184 MachineBasicBlock *
14185 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14186                                      MachineBasicBlock *MBB) const {
14187   DebugLoc DL = MI->getDebugLoc();
14188   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14189
14190   MachineFunction *MF = MBB->getParent();
14191   MachineRegisterInfo &MRI = MF->getRegInfo();
14192
14193   // Memory Reference
14194   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14195   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14196
14197   MVT PVT = getPointerTy();
14198   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14199          "Invalid Pointer Size!");
14200
14201   const TargetRegisterClass *RC =
14202     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14203   unsigned Tmp = MRI.createVirtualRegister(RC);
14204   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14205   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14206   unsigned SP = RegInfo->getStackRegister();
14207
14208   MachineInstrBuilder MIB;
14209
14210   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14211   const int64_t SPOffset = 2 * PVT.getStoreSize();
14212
14213   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14214   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14215
14216   // Reload FP
14217   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14218   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14219     MIB.addOperand(MI->getOperand(i));
14220   MIB.setMemRefs(MMOBegin, MMOEnd);
14221   // Reload IP
14222   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14223   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14224     if (i == X86::AddrDisp)
14225       MIB.addDisp(MI->getOperand(i), LabelOffset);
14226     else
14227       MIB.addOperand(MI->getOperand(i));
14228   }
14229   MIB.setMemRefs(MMOBegin, MMOEnd);
14230   // Reload SP
14231   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14232   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14233     if (i == X86::AddrDisp)
14234       MIB.addDisp(MI->getOperand(i), SPOffset);
14235     else
14236       MIB.addOperand(MI->getOperand(i));
14237   }
14238   MIB.setMemRefs(MMOBegin, MMOEnd);
14239   // Jump
14240   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14241
14242   MI->eraseFromParent();
14243   return MBB;
14244 }
14245
14246 MachineBasicBlock *
14247 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14248                                                MachineBasicBlock *BB) const {
14249   switch (MI->getOpcode()) {
14250   default: llvm_unreachable("Unexpected instr type to insert");
14251   case X86::TAILJMPd64:
14252   case X86::TAILJMPr64:
14253   case X86::TAILJMPm64:
14254     llvm_unreachable("TAILJMP64 would not be touched here.");
14255   case X86::TCRETURNdi64:
14256   case X86::TCRETURNri64:
14257   case X86::TCRETURNmi64:
14258     return BB;
14259   case X86::WIN_ALLOCA:
14260     return EmitLoweredWinAlloca(MI, BB);
14261   case X86::SEG_ALLOCA_32:
14262     return EmitLoweredSegAlloca(MI, BB, false);
14263   case X86::SEG_ALLOCA_64:
14264     return EmitLoweredSegAlloca(MI, BB, true);
14265   case X86::TLSCall_32:
14266   case X86::TLSCall_64:
14267     return EmitLoweredTLSCall(MI, BB);
14268   case X86::CMOV_GR8:
14269   case X86::CMOV_FR32:
14270   case X86::CMOV_FR64:
14271   case X86::CMOV_V4F32:
14272   case X86::CMOV_V2F64:
14273   case X86::CMOV_V2I64:
14274   case X86::CMOV_V8F32:
14275   case X86::CMOV_V4F64:
14276   case X86::CMOV_V4I64:
14277   case X86::CMOV_GR16:
14278   case X86::CMOV_GR32:
14279   case X86::CMOV_RFP32:
14280   case X86::CMOV_RFP64:
14281   case X86::CMOV_RFP80:
14282     return EmitLoweredSelect(MI, BB);
14283
14284   case X86::FP32_TO_INT16_IN_MEM:
14285   case X86::FP32_TO_INT32_IN_MEM:
14286   case X86::FP32_TO_INT64_IN_MEM:
14287   case X86::FP64_TO_INT16_IN_MEM:
14288   case X86::FP64_TO_INT32_IN_MEM:
14289   case X86::FP64_TO_INT64_IN_MEM:
14290   case X86::FP80_TO_INT16_IN_MEM:
14291   case X86::FP80_TO_INT32_IN_MEM:
14292   case X86::FP80_TO_INT64_IN_MEM: {
14293     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14294     DebugLoc DL = MI->getDebugLoc();
14295
14296     // Change the floating point control register to use "round towards zero"
14297     // mode when truncating to an integer value.
14298     MachineFunction *F = BB->getParent();
14299     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14300     addFrameReference(BuildMI(*BB, MI, DL,
14301                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
14302
14303     // Load the old value of the high byte of the control word...
14304     unsigned OldCW =
14305       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14306     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14307                       CWFrameIdx);
14308
14309     // Set the high part to be round to zero...
14310     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14311       .addImm(0xC7F);
14312
14313     // Reload the modified control word now...
14314     addFrameReference(BuildMI(*BB, MI, DL,
14315                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14316
14317     // Restore the memory image of control word to original value
14318     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14319       .addReg(OldCW);
14320
14321     // Get the X86 opcode to use.
14322     unsigned Opc;
14323     switch (MI->getOpcode()) {
14324     default: llvm_unreachable("illegal opcode!");
14325     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14326     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14327     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14328     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14329     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14330     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14331     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14332     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14333     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14334     }
14335
14336     X86AddressMode AM;
14337     MachineOperand &Op = MI->getOperand(0);
14338     if (Op.isReg()) {
14339       AM.BaseType = X86AddressMode::RegBase;
14340       AM.Base.Reg = Op.getReg();
14341     } else {
14342       AM.BaseType = X86AddressMode::FrameIndexBase;
14343       AM.Base.FrameIndex = Op.getIndex();
14344     }
14345     Op = MI->getOperand(1);
14346     if (Op.isImm())
14347       AM.Scale = Op.getImm();
14348     Op = MI->getOperand(2);
14349     if (Op.isImm())
14350       AM.IndexReg = Op.getImm();
14351     Op = MI->getOperand(3);
14352     if (Op.isGlobal()) {
14353       AM.GV = Op.getGlobal();
14354     } else {
14355       AM.Disp = Op.getImm();
14356     }
14357     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14358                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14359
14360     // Reload the original control word now.
14361     addFrameReference(BuildMI(*BB, MI, DL,
14362                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14363
14364     MI->eraseFromParent();   // The pseudo instruction is gone now.
14365     return BB;
14366   }
14367     // String/text processing lowering.
14368   case X86::PCMPISTRM128REG:
14369   case X86::VPCMPISTRM128REG:
14370   case X86::PCMPISTRM128MEM:
14371   case X86::VPCMPISTRM128MEM:
14372   case X86::PCMPESTRM128REG:
14373   case X86::VPCMPESTRM128REG:
14374   case X86::PCMPESTRM128MEM:
14375   case X86::VPCMPESTRM128MEM:
14376     assert(Subtarget->hasSSE42() &&
14377            "Target must have SSE4.2 or AVX features enabled");
14378     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14379
14380   // String/text processing lowering.
14381   case X86::PCMPISTRIREG:
14382   case X86::VPCMPISTRIREG:
14383   case X86::PCMPISTRIMEM:
14384   case X86::VPCMPISTRIMEM:
14385   case X86::PCMPESTRIREG:
14386   case X86::VPCMPESTRIREG:
14387   case X86::PCMPESTRIMEM:
14388   case X86::VPCMPESTRIMEM:
14389     assert(Subtarget->hasSSE42() &&
14390            "Target must have SSE4.2 or AVX features enabled");
14391     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14392
14393   // Thread synchronization.
14394   case X86::MONITOR:
14395     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14396
14397   // xbegin
14398   case X86::XBEGIN:
14399     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14400
14401   // Atomic Lowering.
14402   case X86::ATOMAND8:
14403   case X86::ATOMAND16:
14404   case X86::ATOMAND32:
14405   case X86::ATOMAND64:
14406     // Fall through
14407   case X86::ATOMOR8:
14408   case X86::ATOMOR16:
14409   case X86::ATOMOR32:
14410   case X86::ATOMOR64:
14411     // Fall through
14412   case X86::ATOMXOR16:
14413   case X86::ATOMXOR8:
14414   case X86::ATOMXOR32:
14415   case X86::ATOMXOR64:
14416     // Fall through
14417   case X86::ATOMNAND8:
14418   case X86::ATOMNAND16:
14419   case X86::ATOMNAND32:
14420   case X86::ATOMNAND64:
14421     // Fall through
14422   case X86::ATOMMAX8:
14423   case X86::ATOMMAX16:
14424   case X86::ATOMMAX32:
14425   case X86::ATOMMAX64:
14426     // Fall through
14427   case X86::ATOMMIN8:
14428   case X86::ATOMMIN16:
14429   case X86::ATOMMIN32:
14430   case X86::ATOMMIN64:
14431     // Fall through
14432   case X86::ATOMUMAX8:
14433   case X86::ATOMUMAX16:
14434   case X86::ATOMUMAX32:
14435   case X86::ATOMUMAX64:
14436     // Fall through
14437   case X86::ATOMUMIN8:
14438   case X86::ATOMUMIN16:
14439   case X86::ATOMUMIN32:
14440   case X86::ATOMUMIN64:
14441     return EmitAtomicLoadArith(MI, BB);
14442
14443   // This group does 64-bit operations on a 32-bit host.
14444   case X86::ATOMAND6432:
14445   case X86::ATOMOR6432:
14446   case X86::ATOMXOR6432:
14447   case X86::ATOMNAND6432:
14448   case X86::ATOMADD6432:
14449   case X86::ATOMSUB6432:
14450   case X86::ATOMMAX6432:
14451   case X86::ATOMMIN6432:
14452   case X86::ATOMUMAX6432:
14453   case X86::ATOMUMIN6432:
14454   case X86::ATOMSWAP6432:
14455     return EmitAtomicLoadArith6432(MI, BB);
14456
14457   case X86::VASTART_SAVE_XMM_REGS:
14458     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14459
14460   case X86::VAARG_64:
14461     return EmitVAARG64WithCustomInserter(MI, BB);
14462
14463   case X86::EH_SjLj_SetJmp32:
14464   case X86::EH_SjLj_SetJmp64:
14465     return emitEHSjLjSetJmp(MI, BB);
14466
14467   case X86::EH_SjLj_LongJmp32:
14468   case X86::EH_SjLj_LongJmp64:
14469     return emitEHSjLjLongJmp(MI, BB);
14470   }
14471 }
14472
14473 //===----------------------------------------------------------------------===//
14474 //                           X86 Optimization Hooks
14475 //===----------------------------------------------------------------------===//
14476
14477 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14478                                                        APInt &KnownZero,
14479                                                        APInt &KnownOne,
14480                                                        const SelectionDAG &DAG,
14481                                                        unsigned Depth) const {
14482   unsigned BitWidth = KnownZero.getBitWidth();
14483   unsigned Opc = Op.getOpcode();
14484   assert((Opc >= ISD::BUILTIN_OP_END ||
14485           Opc == ISD::INTRINSIC_WO_CHAIN ||
14486           Opc == ISD::INTRINSIC_W_CHAIN ||
14487           Opc == ISD::INTRINSIC_VOID) &&
14488          "Should use MaskedValueIsZero if you don't know whether Op"
14489          " is a target node!");
14490
14491   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14492   switch (Opc) {
14493   default: break;
14494   case X86ISD::ADD:
14495   case X86ISD::SUB:
14496   case X86ISD::ADC:
14497   case X86ISD::SBB:
14498   case X86ISD::SMUL:
14499   case X86ISD::UMUL:
14500   case X86ISD::INC:
14501   case X86ISD::DEC:
14502   case X86ISD::OR:
14503   case X86ISD::XOR:
14504   case X86ISD::AND:
14505     // These nodes' second result is a boolean.
14506     if (Op.getResNo() == 0)
14507       break;
14508     // Fallthrough
14509   case X86ISD::SETCC:
14510     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14511     break;
14512   case ISD::INTRINSIC_WO_CHAIN: {
14513     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14514     unsigned NumLoBits = 0;
14515     switch (IntId) {
14516     default: break;
14517     case Intrinsic::x86_sse_movmsk_ps:
14518     case Intrinsic::x86_avx_movmsk_ps_256:
14519     case Intrinsic::x86_sse2_movmsk_pd:
14520     case Intrinsic::x86_avx_movmsk_pd_256:
14521     case Intrinsic::x86_mmx_pmovmskb:
14522     case Intrinsic::x86_sse2_pmovmskb_128:
14523     case Intrinsic::x86_avx2_pmovmskb: {
14524       // High bits of movmskp{s|d}, pmovmskb are known zero.
14525       switch (IntId) {
14526         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14527         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14528         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14529         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14530         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14531         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14532         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14533         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14534       }
14535       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14536       break;
14537     }
14538     }
14539     break;
14540   }
14541   }
14542 }
14543
14544 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14545                                                          unsigned Depth) const {
14546   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14547   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14548     return Op.getValueType().getScalarType().getSizeInBits();
14549
14550   // Fallback case.
14551   return 1;
14552 }
14553
14554 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14555 /// node is a GlobalAddress + offset.
14556 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14557                                        const GlobalValue* &GA,
14558                                        int64_t &Offset) const {
14559   if (N->getOpcode() == X86ISD::Wrapper) {
14560     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14561       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14562       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14563       return true;
14564     }
14565   }
14566   return TargetLowering::isGAPlusOffset(N, GA, Offset);
14567 }
14568
14569 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14570 /// same as extracting the high 128-bit part of 256-bit vector and then
14571 /// inserting the result into the low part of a new 256-bit vector
14572 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14573   EVT VT = SVOp->getValueType(0);
14574   unsigned NumElems = VT.getVectorNumElements();
14575
14576   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14577   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14578     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14579         SVOp->getMaskElt(j) >= 0)
14580       return false;
14581
14582   return true;
14583 }
14584
14585 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14586 /// same as extracting the low 128-bit part of 256-bit vector and then
14587 /// inserting the result into the high part of a new 256-bit vector
14588 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14589   EVT VT = SVOp->getValueType(0);
14590   unsigned NumElems = VT.getVectorNumElements();
14591
14592   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14593   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14594     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14595         SVOp->getMaskElt(j) >= 0)
14596       return false;
14597
14598   return true;
14599 }
14600
14601 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14602 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14603                                         TargetLowering::DAGCombinerInfo &DCI,
14604                                         const X86Subtarget* Subtarget) {
14605   DebugLoc dl = N->getDebugLoc();
14606   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14607   SDValue V1 = SVOp->getOperand(0);
14608   SDValue V2 = SVOp->getOperand(1);
14609   EVT VT = SVOp->getValueType(0);
14610   unsigned NumElems = VT.getVectorNumElements();
14611
14612   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14613       V2.getOpcode() == ISD::CONCAT_VECTORS) {
14614     //
14615     //                   0,0,0,...
14616     //                      |
14617     //    V      UNDEF    BUILD_VECTOR    UNDEF
14618     //     \      /           \           /
14619     //  CONCAT_VECTOR         CONCAT_VECTOR
14620     //         \                  /
14621     //          \                /
14622     //          RESULT: V + zero extended
14623     //
14624     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14625         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14626         V1.getOperand(1).getOpcode() != ISD::UNDEF)
14627       return SDValue();
14628
14629     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14630       return SDValue();
14631
14632     // To match the shuffle mask, the first half of the mask should
14633     // be exactly the first vector, and all the rest a splat with the
14634     // first element of the second one.
14635     for (unsigned i = 0; i != NumElems/2; ++i)
14636       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14637           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14638         return SDValue();
14639
14640     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14641     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14642       if (Ld->hasNUsesOfValue(1, 0)) {
14643         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14644         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14645         SDValue ResNode =
14646           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14647                                   Ld->getMemoryVT(),
14648                                   Ld->getPointerInfo(),
14649                                   Ld->getAlignment(),
14650                                   false/*isVolatile*/, true/*ReadMem*/,
14651                                   false/*WriteMem*/);
14652
14653         // Make sure the newly-created LOAD is in the same position as Ld in
14654         // terms of dependency. We create a TokenFactor for Ld and ResNode,
14655         // and update uses of Ld's output chain to use the TokenFactor.
14656         if (Ld->hasAnyUseOfValue(1)) {
14657           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14658                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14659           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14660           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14661                                  SDValue(ResNode.getNode(), 1));
14662         }
14663
14664         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14665       }
14666     }
14667
14668     // Emit a zeroed vector and insert the desired subvector on its
14669     // first half.
14670     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14671     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14672     return DCI.CombineTo(N, InsV);
14673   }
14674
14675   //===--------------------------------------------------------------------===//
14676   // Combine some shuffles into subvector extracts and inserts:
14677   //
14678
14679   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14680   if (isShuffleHigh128VectorInsertLow(SVOp)) {
14681     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14682     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14683     return DCI.CombineTo(N, InsV);
14684   }
14685
14686   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14687   if (isShuffleLow128VectorInsertHigh(SVOp)) {
14688     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14689     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14690     return DCI.CombineTo(N, InsV);
14691   }
14692
14693   return SDValue();
14694 }
14695
14696 /// PerformShuffleCombine - Performs several different shuffle combines.
14697 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14698                                      TargetLowering::DAGCombinerInfo &DCI,
14699                                      const X86Subtarget *Subtarget) {
14700   DebugLoc dl = N->getDebugLoc();
14701   EVT VT = N->getValueType(0);
14702
14703   // Don't create instructions with illegal types after legalize types has run.
14704   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14705   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14706     return SDValue();
14707
14708   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14709   if (Subtarget->hasFp256() && VT.is256BitVector() &&
14710       N->getOpcode() == ISD::VECTOR_SHUFFLE)
14711     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14712
14713   // Only handle 128 wide vector from here on.
14714   if (!VT.is128BitVector())
14715     return SDValue();
14716
14717   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14718   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14719   // consecutive, non-overlapping, and in the right order.
14720   SmallVector<SDValue, 16> Elts;
14721   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14722     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14723
14724   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14725 }
14726
14727 /// PerformTruncateCombine - Converts truncate operation to
14728 /// a sequence of vector shuffle operations.
14729 /// It is possible when we truncate 256-bit vector to 128-bit vector
14730 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14731                                       TargetLowering::DAGCombinerInfo &DCI,
14732                                       const X86Subtarget *Subtarget)  {
14733   return SDValue();
14734 }
14735
14736 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14737 /// specific shuffle of a load can be folded into a single element load.
14738 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14739 /// shuffles have been customed lowered so we need to handle those here.
14740 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14741                                          TargetLowering::DAGCombinerInfo &DCI) {
14742   if (DCI.isBeforeLegalizeOps())
14743     return SDValue();
14744
14745   SDValue InVec = N->getOperand(0);
14746   SDValue EltNo = N->getOperand(1);
14747
14748   if (!isa<ConstantSDNode>(EltNo))
14749     return SDValue();
14750
14751   EVT VT = InVec.getValueType();
14752
14753   bool HasShuffleIntoBitcast = false;
14754   if (InVec.getOpcode() == ISD::BITCAST) {
14755     // Don't duplicate a load with other uses.
14756     if (!InVec.hasOneUse())
14757       return SDValue();
14758     EVT BCVT = InVec.getOperand(0).getValueType();
14759     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14760       return SDValue();
14761     InVec = InVec.getOperand(0);
14762     HasShuffleIntoBitcast = true;
14763   }
14764
14765   if (!isTargetShuffle(InVec.getOpcode()))
14766     return SDValue();
14767
14768   // Don't duplicate a load with other uses.
14769   if (!InVec.hasOneUse())
14770     return SDValue();
14771
14772   SmallVector<int, 16> ShuffleMask;
14773   bool UnaryShuffle;
14774   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14775                             UnaryShuffle))
14776     return SDValue();
14777
14778   // Select the input vector, guarding against out of range extract vector.
14779   unsigned NumElems = VT.getVectorNumElements();
14780   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14781   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14782   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14783                                          : InVec.getOperand(1);
14784
14785   // If inputs to shuffle are the same for both ops, then allow 2 uses
14786   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14787
14788   if (LdNode.getOpcode() == ISD::BITCAST) {
14789     // Don't duplicate a load with other uses.
14790     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14791       return SDValue();
14792
14793     AllowedUses = 1; // only allow 1 load use if we have a bitcast
14794     LdNode = LdNode.getOperand(0);
14795   }
14796
14797   if (!ISD::isNormalLoad(LdNode.getNode()))
14798     return SDValue();
14799
14800   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14801
14802   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14803     return SDValue();
14804
14805   if (HasShuffleIntoBitcast) {
14806     // If there's a bitcast before the shuffle, check if the load type and
14807     // alignment is valid.
14808     unsigned Align = LN0->getAlignment();
14809     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14810     unsigned NewAlign = TLI.getDataLayout()->
14811       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14812
14813     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14814       return SDValue();
14815   }
14816
14817   // All checks match so transform back to vector_shuffle so that DAG combiner
14818   // can finish the job
14819   DebugLoc dl = N->getDebugLoc();
14820
14821   // Create shuffle node taking into account the case that its a unary shuffle
14822   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14823   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14824                                  InVec.getOperand(0), Shuffle,
14825                                  &ShuffleMask[0]);
14826   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14827   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14828                      EltNo);
14829 }
14830
14831 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14832 /// generation and convert it from being a bunch of shuffles and extracts
14833 /// to a simple store and scalar loads to extract the elements.
14834 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14835                                          TargetLowering::DAGCombinerInfo &DCI) {
14836   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14837   if (NewOp.getNode())
14838     return NewOp;
14839
14840   SDValue InputVector = N->getOperand(0);
14841   // Detect whether we are trying to convert from mmx to i32 and the bitcast
14842   // from mmx to v2i32 has a single usage.
14843   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14844       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14845       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14846     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14847                        N->getValueType(0),
14848                        InputVector.getNode()->getOperand(0));
14849
14850   // Only operate on vectors of 4 elements, where the alternative shuffling
14851   // gets to be more expensive.
14852   if (InputVector.getValueType() != MVT::v4i32)
14853     return SDValue();
14854
14855   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14856   // single use which is a sign-extend or zero-extend, and all elements are
14857   // used.
14858   SmallVector<SDNode *, 4> Uses;
14859   unsigned ExtractedElements = 0;
14860   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14861        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14862     if (UI.getUse().getResNo() != InputVector.getResNo())
14863       return SDValue();
14864
14865     SDNode *Extract = *UI;
14866     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14867       return SDValue();
14868
14869     if (Extract->getValueType(0) != MVT::i32)
14870       return SDValue();
14871     if (!Extract->hasOneUse())
14872       return SDValue();
14873     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14874         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14875       return SDValue();
14876     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14877       return SDValue();
14878
14879     // Record which element was extracted.
14880     ExtractedElements |=
14881       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14882
14883     Uses.push_back(Extract);
14884   }
14885
14886   // If not all the elements were used, this may not be worthwhile.
14887   if (ExtractedElements != 15)
14888     return SDValue();
14889
14890   // Ok, we've now decided to do the transformation.
14891   DebugLoc dl = InputVector.getDebugLoc();
14892
14893   // Store the value to a temporary stack slot.
14894   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14895   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14896                             MachinePointerInfo(), false, false, 0);
14897
14898   // Replace each use (extract) with a load of the appropriate element.
14899   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14900        UE = Uses.end(); UI != UE; ++UI) {
14901     SDNode *Extract = *UI;
14902
14903     // cOMpute the element's address.
14904     SDValue Idx = Extract->getOperand(1);
14905     unsigned EltSize =
14906         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14907     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14908     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14909     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14910
14911     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14912                                      StackPtr, OffsetVal);
14913
14914     // Load the scalar.
14915     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14916                                      ScalarAddr, MachinePointerInfo(),
14917                                      false, false, false, 0);
14918
14919     // Replace the exact with the load.
14920     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14921   }
14922
14923   // The replacement was made in place; don't return anything.
14924   return SDValue();
14925 }
14926
14927 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
14928 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
14929                                    SDValue RHS, SelectionDAG &DAG,
14930                                    const X86Subtarget *Subtarget) {
14931   if (!VT.isVector())
14932     return 0;
14933
14934   switch (VT.getSimpleVT().SimpleTy) {
14935   default: return 0;
14936   case MVT::v32i8:
14937   case MVT::v16i16:
14938   case MVT::v8i32:
14939     if (!Subtarget->hasAVX2())
14940       return 0;
14941   case MVT::v16i8:
14942   case MVT::v8i16:
14943   case MVT::v4i32:
14944     if (!Subtarget->hasSSE2())
14945       return 0;
14946   }
14947
14948   // SSE2 has only a small subset of the operations.
14949   bool hasUnsigned = Subtarget->hasSSE41() ||
14950                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
14951   bool hasSigned = Subtarget->hasSSE41() ||
14952                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
14953
14954   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14955
14956   // Check for x CC y ? x : y.
14957   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14958       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14959     switch (CC) {
14960     default: break;
14961     case ISD::SETULT:
14962     case ISD::SETULE:
14963       return hasUnsigned ? X86ISD::UMIN : 0;
14964     case ISD::SETUGT:
14965     case ISD::SETUGE:
14966       return hasUnsigned ? X86ISD::UMAX : 0;
14967     case ISD::SETLT:
14968     case ISD::SETLE:
14969       return hasSigned ? X86ISD::SMIN : 0;
14970     case ISD::SETGT:
14971     case ISD::SETGE:
14972       return hasSigned ? X86ISD::SMAX : 0;
14973     }
14974   // Check for x CC y ? y : x -- a min/max with reversed arms.
14975   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14976              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14977     switch (CC) {
14978     default: break;
14979     case ISD::SETULT:
14980     case ISD::SETULE:
14981       return hasUnsigned ? X86ISD::UMAX : 0;
14982     case ISD::SETUGT:
14983     case ISD::SETUGE:
14984       return hasUnsigned ? X86ISD::UMIN : 0;
14985     case ISD::SETLT:
14986     case ISD::SETLE:
14987       return hasSigned ? X86ISD::SMAX : 0;
14988     case ISD::SETGT:
14989     case ISD::SETGE:
14990       return hasSigned ? X86ISD::SMIN : 0;
14991     }
14992   }
14993
14994   return 0;
14995 }
14996
14997 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14998 /// nodes.
14999 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15000                                     TargetLowering::DAGCombinerInfo &DCI,
15001                                     const X86Subtarget *Subtarget) {
15002   DebugLoc DL = N->getDebugLoc();
15003   SDValue Cond = N->getOperand(0);
15004   // Get the LHS/RHS of the select.
15005   SDValue LHS = N->getOperand(1);
15006   SDValue RHS = N->getOperand(2);
15007   EVT VT = LHS.getValueType();
15008
15009   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15010   // instructions match the semantics of the common C idiom x<y?x:y but not
15011   // x<=y?x:y, because of how they handle negative zero (which can be
15012   // ignored in unsafe-math mode).
15013   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15014       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15015       (Subtarget->hasSSE2() ||
15016        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15017     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15018
15019     unsigned Opcode = 0;
15020     // Check for x CC y ? x : y.
15021     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15022         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15023       switch (CC) {
15024       default: break;
15025       case ISD::SETULT:
15026         // Converting this to a min would handle NaNs incorrectly, and swapping
15027         // the operands would cause it to handle comparisons between positive
15028         // and negative zero incorrectly.
15029         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15030           if (!DAG.getTarget().Options.UnsafeFPMath &&
15031               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15032             break;
15033           std::swap(LHS, RHS);
15034         }
15035         Opcode = X86ISD::FMIN;
15036         break;
15037       case ISD::SETOLE:
15038         // Converting this to a min would handle comparisons between positive
15039         // and negative zero incorrectly.
15040         if (!DAG.getTarget().Options.UnsafeFPMath &&
15041             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15042           break;
15043         Opcode = X86ISD::FMIN;
15044         break;
15045       case ISD::SETULE:
15046         // Converting this to a min would handle both negative zeros and NaNs
15047         // incorrectly, but we can swap the operands to fix both.
15048         std::swap(LHS, RHS);
15049       case ISD::SETOLT:
15050       case ISD::SETLT:
15051       case ISD::SETLE:
15052         Opcode = X86ISD::FMIN;
15053         break;
15054
15055       case ISD::SETOGE:
15056         // Converting this to a max would handle comparisons between positive
15057         // and negative zero incorrectly.
15058         if (!DAG.getTarget().Options.UnsafeFPMath &&
15059             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15060           break;
15061         Opcode = X86ISD::FMAX;
15062         break;
15063       case ISD::SETUGT:
15064         // Converting this to a max would handle NaNs incorrectly, and swapping
15065         // the operands would cause it to handle comparisons between positive
15066         // and negative zero incorrectly.
15067         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15068           if (!DAG.getTarget().Options.UnsafeFPMath &&
15069               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15070             break;
15071           std::swap(LHS, RHS);
15072         }
15073         Opcode = X86ISD::FMAX;
15074         break;
15075       case ISD::SETUGE:
15076         // Converting this to a max would handle both negative zeros and NaNs
15077         // incorrectly, but we can swap the operands to fix both.
15078         std::swap(LHS, RHS);
15079       case ISD::SETOGT:
15080       case ISD::SETGT:
15081       case ISD::SETGE:
15082         Opcode = X86ISD::FMAX;
15083         break;
15084       }
15085     // Check for x CC y ? y : x -- a min/max with reversed arms.
15086     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15087                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15088       switch (CC) {
15089       default: break;
15090       case ISD::SETOGE:
15091         // Converting this to a min would handle comparisons between positive
15092         // and negative zero incorrectly, and swapping the operands would
15093         // cause it to handle NaNs incorrectly.
15094         if (!DAG.getTarget().Options.UnsafeFPMath &&
15095             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15096           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15097             break;
15098           std::swap(LHS, RHS);
15099         }
15100         Opcode = X86ISD::FMIN;
15101         break;
15102       case ISD::SETUGT:
15103         // Converting this to a min would handle NaNs incorrectly.
15104         if (!DAG.getTarget().Options.UnsafeFPMath &&
15105             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15106           break;
15107         Opcode = X86ISD::FMIN;
15108         break;
15109       case ISD::SETUGE:
15110         // Converting this to a min would handle both negative zeros and NaNs
15111         // incorrectly, but we can swap the operands to fix both.
15112         std::swap(LHS, RHS);
15113       case ISD::SETOGT:
15114       case ISD::SETGT:
15115       case ISD::SETGE:
15116         Opcode = X86ISD::FMIN;
15117         break;
15118
15119       case ISD::SETULT:
15120         // Converting this to a max would handle NaNs incorrectly.
15121         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15122           break;
15123         Opcode = X86ISD::FMAX;
15124         break;
15125       case ISD::SETOLE:
15126         // Converting this to a max would handle comparisons between positive
15127         // and negative zero incorrectly, and swapping the operands would
15128         // cause it to handle NaNs incorrectly.
15129         if (!DAG.getTarget().Options.UnsafeFPMath &&
15130             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15131           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15132             break;
15133           std::swap(LHS, RHS);
15134         }
15135         Opcode = X86ISD::FMAX;
15136         break;
15137       case ISD::SETULE:
15138         // Converting this to a max would handle both negative zeros and NaNs
15139         // incorrectly, but we can swap the operands to fix both.
15140         std::swap(LHS, RHS);
15141       case ISD::SETOLT:
15142       case ISD::SETLT:
15143       case ISD::SETLE:
15144         Opcode = X86ISD::FMAX;
15145         break;
15146       }
15147     }
15148
15149     if (Opcode)
15150       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15151   }
15152
15153   // If this is a select between two integer constants, try to do some
15154   // optimizations.
15155   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15156     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15157       // Don't do this for crazy integer types.
15158       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15159         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15160         // so that TrueC (the true value) is larger than FalseC.
15161         bool NeedsCondInvert = false;
15162
15163         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15164             // Efficiently invertible.
15165             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15166              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15167               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15168           NeedsCondInvert = true;
15169           std::swap(TrueC, FalseC);
15170         }
15171
15172         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15173         if (FalseC->getAPIntValue() == 0 &&
15174             TrueC->getAPIntValue().isPowerOf2()) {
15175           if (NeedsCondInvert) // Invert the condition if needed.
15176             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15177                                DAG.getConstant(1, Cond.getValueType()));
15178
15179           // Zero extend the condition if needed.
15180           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15181
15182           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15183           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15184                              DAG.getConstant(ShAmt, MVT::i8));
15185         }
15186
15187         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15188         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15189           if (NeedsCondInvert) // Invert the condition if needed.
15190             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15191                                DAG.getConstant(1, Cond.getValueType()));
15192
15193           // Zero extend the condition if needed.
15194           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15195                              FalseC->getValueType(0), Cond);
15196           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15197                              SDValue(FalseC, 0));
15198         }
15199
15200         // Optimize cases that will turn into an LEA instruction.  This requires
15201         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15202         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15203           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15204           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15205
15206           bool isFastMultiplier = false;
15207           if (Diff < 10) {
15208             switch ((unsigned char)Diff) {
15209               default: break;
15210               case 1:  // result = add base, cond
15211               case 2:  // result = lea base(    , cond*2)
15212               case 3:  // result = lea base(cond, cond*2)
15213               case 4:  // result = lea base(    , cond*4)
15214               case 5:  // result = lea base(cond, cond*4)
15215               case 8:  // result = lea base(    , cond*8)
15216               case 9:  // result = lea base(cond, cond*8)
15217                 isFastMultiplier = true;
15218                 break;
15219             }
15220           }
15221
15222           if (isFastMultiplier) {
15223             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15224             if (NeedsCondInvert) // Invert the condition if needed.
15225               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15226                                  DAG.getConstant(1, Cond.getValueType()));
15227
15228             // Zero extend the condition if needed.
15229             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15230                                Cond);
15231             // Scale the condition by the difference.
15232             if (Diff != 1)
15233               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15234                                  DAG.getConstant(Diff, Cond.getValueType()));
15235
15236             // Add the base if non-zero.
15237             if (FalseC->getAPIntValue() != 0)
15238               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15239                                  SDValue(FalseC, 0));
15240             return Cond;
15241           }
15242         }
15243       }
15244   }
15245
15246   // Canonicalize max and min:
15247   // (x > y) ? x : y -> (x >= y) ? x : y
15248   // (x < y) ? x : y -> (x <= y) ? x : y
15249   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15250   // the need for an extra compare
15251   // against zero. e.g.
15252   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15253   // subl   %esi, %edi
15254   // testl  %edi, %edi
15255   // movl   $0, %eax
15256   // cmovgl %edi, %eax
15257   // =>
15258   // xorl   %eax, %eax
15259   // subl   %esi, $edi
15260   // cmovsl %eax, %edi
15261   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15262       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15263       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15264     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15265     switch (CC) {
15266     default: break;
15267     case ISD::SETLT:
15268     case ISD::SETGT: {
15269       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15270       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15271                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15272       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15273     }
15274     }
15275   }
15276
15277   // Match VSELECTs into subs with unsigned saturation.
15278   if (!DCI.isBeforeLegalize() &&
15279       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15280       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15281       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15282        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15283     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15284
15285     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15286     // left side invert the predicate to simplify logic below.
15287     SDValue Other;
15288     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15289       Other = RHS;
15290       CC = ISD::getSetCCInverse(CC, true);
15291     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15292       Other = LHS;
15293     }
15294
15295     if (Other.getNode() && Other->getNumOperands() == 2 &&
15296         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15297       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15298       SDValue CondRHS = Cond->getOperand(1);
15299
15300       // Look for a general sub with unsigned saturation first.
15301       // x >= y ? x-y : 0 --> subus x, y
15302       // x >  y ? x-y : 0 --> subus x, y
15303       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15304           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15305         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15306
15307       // If the RHS is a constant we have to reverse the const canonicalization.
15308       // x > C-1 ? x+-C : 0 --> subus x, C
15309       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15310           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15311         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15312         if (CondRHS.getConstantOperandVal(0) == -A-1) {
15313           SmallVector<SDValue, 32> V(VT.getVectorNumElements(),
15314                                      DAG.getConstant(-A, VT.getScalarType()));
15315           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15316                              DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
15317                                          V.data(), V.size()));
15318         }
15319       }
15320
15321       // Another special case: If C was a sign bit, the sub has been
15322       // canonicalized into a xor.
15323       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15324       //        it's safe to decanonicalize the xor?
15325       // x s< 0 ? x^C : 0 --> subus x, C
15326       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15327           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15328           isSplatVector(OpRHS.getNode())) {
15329         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15330         if (A.isSignBit())
15331           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15332       }
15333     }
15334   }
15335
15336   // Try to match a min/max vector operation.
15337   if (!DCI.isBeforeLegalize() &&
15338       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15339     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15340       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15341
15342   // If we know that this node is legal then we know that it is going to be
15343   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15344   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15345   // to simplify previous instructions.
15346   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15347   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15348       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15349     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15350
15351     // Don't optimize vector selects that map to mask-registers.
15352     if (BitWidth == 1)
15353       return SDValue();
15354
15355     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15356     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15357
15358     APInt KnownZero, KnownOne;
15359     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15360                                           DCI.isBeforeLegalizeOps());
15361     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15362         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15363       DCI.CommitTargetLoweringOpt(TLO);
15364   }
15365
15366   return SDValue();
15367 }
15368
15369 // Check whether a boolean test is testing a boolean value generated by
15370 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15371 // code.
15372 //
15373 // Simplify the following patterns:
15374 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15375 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15376 // to (Op EFLAGS Cond)
15377 //
15378 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15379 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15380 // to (Op EFLAGS !Cond)
15381 //
15382 // where Op could be BRCOND or CMOV.
15383 //
15384 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15385   // Quit if not CMP and SUB with its value result used.
15386   if (Cmp.getOpcode() != X86ISD::CMP &&
15387       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15388       return SDValue();
15389
15390   // Quit if not used as a boolean value.
15391   if (CC != X86::COND_E && CC != X86::COND_NE)
15392     return SDValue();
15393
15394   // Check CMP operands. One of them should be 0 or 1 and the other should be
15395   // an SetCC or extended from it.
15396   SDValue Op1 = Cmp.getOperand(0);
15397   SDValue Op2 = Cmp.getOperand(1);
15398
15399   SDValue SetCC;
15400   const ConstantSDNode* C = 0;
15401   bool needOppositeCond = (CC == X86::COND_E);
15402
15403   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15404     SetCC = Op2;
15405   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15406     SetCC = Op1;
15407   else // Quit if all operands are not constants.
15408     return SDValue();
15409
15410   if (C->getZExtValue() == 1)
15411     needOppositeCond = !needOppositeCond;
15412   else if (C->getZExtValue() != 0)
15413     // Quit if the constant is neither 0 or 1.
15414     return SDValue();
15415
15416   // Skip 'zext' node.
15417   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15418     SetCC = SetCC.getOperand(0);
15419
15420   switch (SetCC.getOpcode()) {
15421   case X86ISD::SETCC:
15422     // Set the condition code or opposite one if necessary.
15423     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15424     if (needOppositeCond)
15425       CC = X86::GetOppositeBranchCondition(CC);
15426     return SetCC.getOperand(1);
15427   case X86ISD::CMOV: {
15428     // Check whether false/true value has canonical one, i.e. 0 or 1.
15429     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15430     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15431     // Quit if true value is not a constant.
15432     if (!TVal)
15433       return SDValue();
15434     // Quit if false value is not a constant.
15435     if (!FVal) {
15436       // A special case for rdrand, where 0 is set if false cond is found.
15437       SDValue Op = SetCC.getOperand(0);
15438       if (Op.getOpcode() != X86ISD::RDRAND)
15439         return SDValue();
15440     }
15441     // Quit if false value is not the constant 0 or 1.
15442     bool FValIsFalse = true;
15443     if (FVal && FVal->getZExtValue() != 0) {
15444       if (FVal->getZExtValue() != 1)
15445         return SDValue();
15446       // If FVal is 1, opposite cond is needed.
15447       needOppositeCond = !needOppositeCond;
15448       FValIsFalse = false;
15449     }
15450     // Quit if TVal is not the constant opposite of FVal.
15451     if (FValIsFalse && TVal->getZExtValue() != 1)
15452       return SDValue();
15453     if (!FValIsFalse && TVal->getZExtValue() != 0)
15454       return SDValue();
15455     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15456     if (needOppositeCond)
15457       CC = X86::GetOppositeBranchCondition(CC);
15458     return SetCC.getOperand(3);
15459   }
15460   }
15461
15462   return SDValue();
15463 }
15464
15465 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15466 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15467                                   TargetLowering::DAGCombinerInfo &DCI,
15468                                   const X86Subtarget *Subtarget) {
15469   DebugLoc DL = N->getDebugLoc();
15470
15471   // If the flag operand isn't dead, don't touch this CMOV.
15472   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15473     return SDValue();
15474
15475   SDValue FalseOp = N->getOperand(0);
15476   SDValue TrueOp = N->getOperand(1);
15477   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15478   SDValue Cond = N->getOperand(3);
15479
15480   if (CC == X86::COND_E || CC == X86::COND_NE) {
15481     switch (Cond.getOpcode()) {
15482     default: break;
15483     case X86ISD::BSR:
15484     case X86ISD::BSF:
15485       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15486       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15487         return (CC == X86::COND_E) ? FalseOp : TrueOp;
15488     }
15489   }
15490
15491   SDValue Flags;
15492
15493   Flags = checkBoolTestSetCCCombine(Cond, CC);
15494   if (Flags.getNode() &&
15495       // Extra check as FCMOV only supports a subset of X86 cond.
15496       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15497     SDValue Ops[] = { FalseOp, TrueOp,
15498                       DAG.getConstant(CC, MVT::i8), Flags };
15499     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15500                        Ops, array_lengthof(Ops));
15501   }
15502
15503   // If this is a select between two integer constants, try to do some
15504   // optimizations.  Note that the operands are ordered the opposite of SELECT
15505   // operands.
15506   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15507     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15508       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15509       // larger than FalseC (the false value).
15510       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15511         CC = X86::GetOppositeBranchCondition(CC);
15512         std::swap(TrueC, FalseC);
15513         std::swap(TrueOp, FalseOp);
15514       }
15515
15516       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
15517       // This is efficient for any integer data type (including i8/i16) and
15518       // shift amount.
15519       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15520         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15521                            DAG.getConstant(CC, MVT::i8), Cond);
15522
15523         // Zero extend the condition if needed.
15524         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15525
15526         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15527         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15528                            DAG.getConstant(ShAmt, MVT::i8));
15529         if (N->getNumValues() == 2)  // Dead flag value?
15530           return DCI.CombineTo(N, Cond, SDValue());
15531         return Cond;
15532       }
15533
15534       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
15535       // for any integer data type, including i8/i16.
15536       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15537         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15538                            DAG.getConstant(CC, MVT::i8), Cond);
15539
15540         // Zero extend the condition if needed.
15541         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15542                            FalseC->getValueType(0), Cond);
15543         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15544                            SDValue(FalseC, 0));
15545
15546         if (N->getNumValues() == 2)  // Dead flag value?
15547           return DCI.CombineTo(N, Cond, SDValue());
15548         return Cond;
15549       }
15550
15551       // Optimize cases that will turn into an LEA instruction.  This requires
15552       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15553       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15554         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15555         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15556
15557         bool isFastMultiplier = false;
15558         if (Diff < 10) {
15559           switch ((unsigned char)Diff) {
15560           default: break;
15561           case 1:  // result = add base, cond
15562           case 2:  // result = lea base(    , cond*2)
15563           case 3:  // result = lea base(cond, cond*2)
15564           case 4:  // result = lea base(    , cond*4)
15565           case 5:  // result = lea base(cond, cond*4)
15566           case 8:  // result = lea base(    , cond*8)
15567           case 9:  // result = lea base(cond, cond*8)
15568             isFastMultiplier = true;
15569             break;
15570           }
15571         }
15572
15573         if (isFastMultiplier) {
15574           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15575           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15576                              DAG.getConstant(CC, MVT::i8), Cond);
15577           // Zero extend the condition if needed.
15578           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15579                              Cond);
15580           // Scale the condition by the difference.
15581           if (Diff != 1)
15582             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15583                                DAG.getConstant(Diff, Cond.getValueType()));
15584
15585           // Add the base if non-zero.
15586           if (FalseC->getAPIntValue() != 0)
15587             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15588                                SDValue(FalseC, 0));
15589           if (N->getNumValues() == 2)  // Dead flag value?
15590             return DCI.CombineTo(N, Cond, SDValue());
15591           return Cond;
15592         }
15593       }
15594     }
15595   }
15596
15597   // Handle these cases:
15598   //   (select (x != c), e, c) -> select (x != c), e, x),
15599   //   (select (x == c), c, e) -> select (x == c), x, e)
15600   // where the c is an integer constant, and the "select" is the combination
15601   // of CMOV and CMP.
15602   //
15603   // The rationale for this change is that the conditional-move from a constant
15604   // needs two instructions, however, conditional-move from a register needs
15605   // only one instruction.
15606   //
15607   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15608   //  some instruction-combining opportunities. This opt needs to be
15609   //  postponed as late as possible.
15610   //
15611   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15612     // the DCI.xxxx conditions are provided to postpone the optimization as
15613     // late as possible.
15614
15615     ConstantSDNode *CmpAgainst = 0;
15616     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15617         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15618         dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15619
15620       if (CC == X86::COND_NE &&
15621           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15622         CC = X86::GetOppositeBranchCondition(CC);
15623         std::swap(TrueOp, FalseOp);
15624       }
15625
15626       if (CC == X86::COND_E &&
15627           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15628         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15629                           DAG.getConstant(CC, MVT::i8), Cond };
15630         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15631                            array_lengthof(Ops));
15632       }
15633     }
15634   }
15635
15636   return SDValue();
15637 }
15638
15639 /// PerformMulCombine - Optimize a single multiply with constant into two
15640 /// in order to implement it with two cheaper instructions, e.g.
15641 /// LEA + SHL, LEA + LEA.
15642 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15643                                  TargetLowering::DAGCombinerInfo &DCI) {
15644   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15645     return SDValue();
15646
15647   EVT VT = N->getValueType(0);
15648   if (VT != MVT::i64)
15649     return SDValue();
15650
15651   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15652   if (!C)
15653     return SDValue();
15654   uint64_t MulAmt = C->getZExtValue();
15655   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15656     return SDValue();
15657
15658   uint64_t MulAmt1 = 0;
15659   uint64_t MulAmt2 = 0;
15660   if ((MulAmt % 9) == 0) {
15661     MulAmt1 = 9;
15662     MulAmt2 = MulAmt / 9;
15663   } else if ((MulAmt % 5) == 0) {
15664     MulAmt1 = 5;
15665     MulAmt2 = MulAmt / 5;
15666   } else if ((MulAmt % 3) == 0) {
15667     MulAmt1 = 3;
15668     MulAmt2 = MulAmt / 3;
15669   }
15670   if (MulAmt2 &&
15671       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15672     DebugLoc DL = N->getDebugLoc();
15673
15674     if (isPowerOf2_64(MulAmt2) &&
15675         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15676       // If second multiplifer is pow2, issue it first. We want the multiply by
15677       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15678       // is an add.
15679       std::swap(MulAmt1, MulAmt2);
15680
15681     SDValue NewMul;
15682     if (isPowerOf2_64(MulAmt1))
15683       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15684                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15685     else
15686       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15687                            DAG.getConstant(MulAmt1, VT));
15688
15689     if (isPowerOf2_64(MulAmt2))
15690       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15691                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15692     else
15693       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15694                            DAG.getConstant(MulAmt2, VT));
15695
15696     // Do not add new nodes to DAG combiner worklist.
15697     DCI.CombineTo(N, NewMul, false);
15698   }
15699   return SDValue();
15700 }
15701
15702 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15703   SDValue N0 = N->getOperand(0);
15704   SDValue N1 = N->getOperand(1);
15705   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15706   EVT VT = N0.getValueType();
15707
15708   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15709   // since the result of setcc_c is all zero's or all ones.
15710   if (VT.isInteger() && !VT.isVector() &&
15711       N1C && N0.getOpcode() == ISD::AND &&
15712       N0.getOperand(1).getOpcode() == ISD::Constant) {
15713     SDValue N00 = N0.getOperand(0);
15714     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15715         ((N00.getOpcode() == ISD::ANY_EXTEND ||
15716           N00.getOpcode() == ISD::ZERO_EXTEND) &&
15717          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15718       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15719       APInt ShAmt = N1C->getAPIntValue();
15720       Mask = Mask.shl(ShAmt);
15721       if (Mask != 0)
15722         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15723                            N00, DAG.getConstant(Mask, VT));
15724     }
15725   }
15726
15727   // Hardware support for vector shifts is sparse which makes us scalarize the
15728   // vector operations in many cases. Also, on sandybridge ADD is faster than
15729   // shl.
15730   // (shl V, 1) -> add V,V
15731   if (isSplatVector(N1.getNode())) {
15732     assert(N0.getValueType().isVector() && "Invalid vector shift type");
15733     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15734     // We shift all of the values by one. In many cases we do not have
15735     // hardware support for this operation. This is better expressed as an ADD
15736     // of two values.
15737     if (N1C && (1 == N1C->getZExtValue())) {
15738       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15739     }
15740   }
15741
15742   return SDValue();
15743 }
15744
15745 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15746 ///                       when possible.
15747 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15748                                    TargetLowering::DAGCombinerInfo &DCI,
15749                                    const X86Subtarget *Subtarget) {
15750   EVT VT = N->getValueType(0);
15751   if (N->getOpcode() == ISD::SHL) {
15752     SDValue V = PerformSHLCombine(N, DAG);
15753     if (V.getNode()) return V;
15754   }
15755
15756   // On X86 with SSE2 support, we can transform this to a vector shift if
15757   // all elements are shifted by the same amount.  We can't do this in legalize
15758   // because the a constant vector is typically transformed to a constant pool
15759   // so we have no knowledge of the shift amount.
15760   if (!Subtarget->hasSSE2())
15761     return SDValue();
15762
15763   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15764       (!Subtarget->hasInt256() ||
15765        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15766     return SDValue();
15767
15768   SDValue ShAmtOp = N->getOperand(1);
15769   EVT EltVT = VT.getVectorElementType();
15770   DebugLoc DL = N->getDebugLoc();
15771   SDValue BaseShAmt = SDValue();
15772   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15773     unsigned NumElts = VT.getVectorNumElements();
15774     unsigned i = 0;
15775     for (; i != NumElts; ++i) {
15776       SDValue Arg = ShAmtOp.getOperand(i);
15777       if (Arg.getOpcode() == ISD::UNDEF) continue;
15778       BaseShAmt = Arg;
15779       break;
15780     }
15781     // Handle the case where the build_vector is all undef
15782     // FIXME: Should DAG allow this?
15783     if (i == NumElts)
15784       return SDValue();
15785
15786     for (; i != NumElts; ++i) {
15787       SDValue Arg = ShAmtOp.getOperand(i);
15788       if (Arg.getOpcode() == ISD::UNDEF) continue;
15789       if (Arg != BaseShAmt) {
15790         return SDValue();
15791       }
15792     }
15793   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15794              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15795     SDValue InVec = ShAmtOp.getOperand(0);
15796     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15797       unsigned NumElts = InVec.getValueType().getVectorNumElements();
15798       unsigned i = 0;
15799       for (; i != NumElts; ++i) {
15800         SDValue Arg = InVec.getOperand(i);
15801         if (Arg.getOpcode() == ISD::UNDEF) continue;
15802         BaseShAmt = Arg;
15803         break;
15804       }
15805     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15806        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15807          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15808          if (C->getZExtValue() == SplatIdx)
15809            BaseShAmt = InVec.getOperand(1);
15810        }
15811     }
15812     if (BaseShAmt.getNode() == 0) {
15813       // Don't create instructions with illegal types after legalize
15814       // types has run.
15815       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15816           !DCI.isBeforeLegalize())
15817         return SDValue();
15818
15819       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15820                               DAG.getIntPtrConstant(0));
15821     }
15822   } else
15823     return SDValue();
15824
15825   // The shift amount is an i32.
15826   if (EltVT.bitsGT(MVT::i32))
15827     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15828   else if (EltVT.bitsLT(MVT::i32))
15829     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15830
15831   // The shift amount is identical so we can do a vector shift.
15832   SDValue  ValOp = N->getOperand(0);
15833   switch (N->getOpcode()) {
15834   default:
15835     llvm_unreachable("Unknown shift opcode!");
15836   case ISD::SHL:
15837     switch (VT.getSimpleVT().SimpleTy) {
15838     default: return SDValue();
15839     case MVT::v2i64:
15840     case MVT::v4i32:
15841     case MVT::v8i16:
15842     case MVT::v4i64:
15843     case MVT::v8i32:
15844     case MVT::v16i16:
15845       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15846     }
15847   case ISD::SRA:
15848     switch (VT.getSimpleVT().SimpleTy) {
15849     default: return SDValue();
15850     case MVT::v4i32:
15851     case MVT::v8i16:
15852     case MVT::v8i32:
15853     case MVT::v16i16:
15854       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15855     }
15856   case ISD::SRL:
15857     switch (VT.getSimpleVT().SimpleTy) {
15858     default: return SDValue();
15859     case MVT::v2i64:
15860     case MVT::v4i32:
15861     case MVT::v8i16:
15862     case MVT::v4i64:
15863     case MVT::v8i32:
15864     case MVT::v16i16:
15865       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15866     }
15867   }
15868 }
15869
15870 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15871 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15872 // and friends.  Likewise for OR -> CMPNEQSS.
15873 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15874                             TargetLowering::DAGCombinerInfo &DCI,
15875                             const X86Subtarget *Subtarget) {
15876   unsigned opcode;
15877
15878   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15879   // we're requiring SSE2 for both.
15880   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15881     SDValue N0 = N->getOperand(0);
15882     SDValue N1 = N->getOperand(1);
15883     SDValue CMP0 = N0->getOperand(1);
15884     SDValue CMP1 = N1->getOperand(1);
15885     DebugLoc DL = N->getDebugLoc();
15886
15887     // The SETCCs should both refer to the same CMP.
15888     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15889       return SDValue();
15890
15891     SDValue CMP00 = CMP0->getOperand(0);
15892     SDValue CMP01 = CMP0->getOperand(1);
15893     EVT     VT    = CMP00.getValueType();
15894
15895     if (VT == MVT::f32 || VT == MVT::f64) {
15896       bool ExpectingFlags = false;
15897       // Check for any users that want flags:
15898       for (SDNode::use_iterator UI = N->use_begin(),
15899              UE = N->use_end();
15900            !ExpectingFlags && UI != UE; ++UI)
15901         switch (UI->getOpcode()) {
15902         default:
15903         case ISD::BR_CC:
15904         case ISD::BRCOND:
15905         case ISD::SELECT:
15906           ExpectingFlags = true;
15907           break;
15908         case ISD::CopyToReg:
15909         case ISD::SIGN_EXTEND:
15910         case ISD::ZERO_EXTEND:
15911         case ISD::ANY_EXTEND:
15912           break;
15913         }
15914
15915       if (!ExpectingFlags) {
15916         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15917         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15918
15919         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15920           X86::CondCode tmp = cc0;
15921           cc0 = cc1;
15922           cc1 = tmp;
15923         }
15924
15925         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15926             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15927           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15928           X86ISD::NodeType NTOperator = is64BitFP ?
15929             X86ISD::FSETCCsd : X86ISD::FSETCCss;
15930           // FIXME: need symbolic constants for these magic numbers.
15931           // See X86ATTInstPrinter.cpp:printSSECC().
15932           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15933           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15934                                               DAG.getConstant(x86cc, MVT::i8));
15935           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15936                                               OnesOrZeroesF);
15937           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15938                                       DAG.getConstant(1, MVT::i32));
15939           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15940           return OneBitOfTruth;
15941         }
15942       }
15943     }
15944   }
15945   return SDValue();
15946 }
15947
15948 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15949 /// so it can be folded inside ANDNP.
15950 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15951   EVT VT = N->getValueType(0);
15952
15953   // Match direct AllOnes for 128 and 256-bit vectors
15954   if (ISD::isBuildVectorAllOnes(N))
15955     return true;
15956
15957   // Look through a bit convert.
15958   if (N->getOpcode() == ISD::BITCAST)
15959     N = N->getOperand(0).getNode();
15960
15961   // Sometimes the operand may come from a insert_subvector building a 256-bit
15962   // allones vector
15963   if (VT.is256BitVector() &&
15964       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15965     SDValue V1 = N->getOperand(0);
15966     SDValue V2 = N->getOperand(1);
15967
15968     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15969         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15970         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15971         ISD::isBuildVectorAllOnes(V2.getNode()))
15972       return true;
15973   }
15974
15975   return false;
15976 }
15977
15978 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
15979 // register. In most cases we actually compare or select YMM-sized registers
15980 // and mixing the two types creates horrible code. This method optimizes
15981 // some of the transition sequences.
15982 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
15983                                  TargetLowering::DAGCombinerInfo &DCI,
15984                                  const X86Subtarget *Subtarget) {
15985   EVT VT = N->getValueType(0);
15986   if (!VT.is256BitVector())
15987     return SDValue();
15988
15989   assert((N->getOpcode() == ISD::ANY_EXTEND ||
15990           N->getOpcode() == ISD::ZERO_EXTEND ||
15991           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
15992
15993   SDValue Narrow = N->getOperand(0);
15994   EVT NarrowVT = Narrow->getValueType(0);
15995   if (!NarrowVT.is128BitVector())
15996     return SDValue();
15997
15998   if (Narrow->getOpcode() != ISD::XOR &&
15999       Narrow->getOpcode() != ISD::AND &&
16000       Narrow->getOpcode() != ISD::OR)
16001     return SDValue();
16002
16003   SDValue N0  = Narrow->getOperand(0);
16004   SDValue N1  = Narrow->getOperand(1);
16005   DebugLoc DL = Narrow->getDebugLoc();
16006
16007   // The Left side has to be a trunc.
16008   if (N0.getOpcode() != ISD::TRUNCATE)
16009     return SDValue();
16010
16011   // The type of the truncated inputs.
16012   EVT WideVT = N0->getOperand(0)->getValueType(0);
16013   if (WideVT != VT)
16014     return SDValue();
16015
16016   // The right side has to be a 'trunc' or a constant vector.
16017   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16018   bool RHSConst = (isSplatVector(N1.getNode()) &&
16019                    isa<ConstantSDNode>(N1->getOperand(0)));
16020   if (!RHSTrunc && !RHSConst)
16021     return SDValue();
16022
16023   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16024
16025   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16026     return SDValue();
16027
16028   // Set N0 and N1 to hold the inputs to the new wide operation.
16029   N0 = N0->getOperand(0);
16030   if (RHSConst) {
16031     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16032                      N1->getOperand(0));
16033     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16034     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16035   } else if (RHSTrunc) {
16036     N1 = N1->getOperand(0);
16037   }
16038
16039   // Generate the wide operation.
16040   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16041   unsigned Opcode = N->getOpcode();
16042   switch (Opcode) {
16043   case ISD::ANY_EXTEND:
16044     return Op;
16045   case ISD::ZERO_EXTEND: {
16046     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16047     APInt Mask = APInt::getAllOnesValue(InBits);
16048     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16049     return DAG.getNode(ISD::AND, DL, VT,
16050                        Op, DAG.getConstant(Mask, VT));
16051   }
16052   case ISD::SIGN_EXTEND:
16053     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16054                        Op, DAG.getValueType(NarrowVT));
16055   default:
16056     llvm_unreachable("Unexpected opcode");
16057   }
16058 }
16059
16060 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16061                                  TargetLowering::DAGCombinerInfo &DCI,
16062                                  const X86Subtarget *Subtarget) {
16063   EVT VT = N->getValueType(0);
16064   if (DCI.isBeforeLegalizeOps())
16065     return SDValue();
16066
16067   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16068   if (R.getNode())
16069     return R;
16070
16071   // Create BLSI, and BLSR instructions
16072   // BLSI is X & (-X)
16073   // BLSR is X & (X-1)
16074   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16075     SDValue N0 = N->getOperand(0);
16076     SDValue N1 = N->getOperand(1);
16077     DebugLoc DL = N->getDebugLoc();
16078
16079     // Check LHS for neg
16080     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16081         isZero(N0.getOperand(0)))
16082       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16083
16084     // Check RHS for neg
16085     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16086         isZero(N1.getOperand(0)))
16087       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16088
16089     // Check LHS for X-1
16090     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16091         isAllOnes(N0.getOperand(1)))
16092       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16093
16094     // Check RHS for X-1
16095     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16096         isAllOnes(N1.getOperand(1)))
16097       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16098
16099     return SDValue();
16100   }
16101
16102   // Want to form ANDNP nodes:
16103   // 1) In the hopes of then easily combining them with OR and AND nodes
16104   //    to form PBLEND/PSIGN.
16105   // 2) To match ANDN packed intrinsics
16106   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16107     return SDValue();
16108
16109   SDValue N0 = N->getOperand(0);
16110   SDValue N1 = N->getOperand(1);
16111   DebugLoc DL = N->getDebugLoc();
16112
16113   // Check LHS for vnot
16114   if (N0.getOpcode() == ISD::XOR &&
16115       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16116       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16117     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16118
16119   // Check RHS for vnot
16120   if (N1.getOpcode() == ISD::XOR &&
16121       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16122       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16123     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16124
16125   return SDValue();
16126 }
16127
16128 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16129                                 TargetLowering::DAGCombinerInfo &DCI,
16130                                 const X86Subtarget *Subtarget) {
16131   EVT VT = N->getValueType(0);
16132   if (DCI.isBeforeLegalizeOps())
16133     return SDValue();
16134
16135   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16136   if (R.getNode())
16137     return R;
16138
16139   SDValue N0 = N->getOperand(0);
16140   SDValue N1 = N->getOperand(1);
16141
16142   // look for psign/blend
16143   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16144     if (!Subtarget->hasSSSE3() ||
16145         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16146       return SDValue();
16147
16148     // Canonicalize pandn to RHS
16149     if (N0.getOpcode() == X86ISD::ANDNP)
16150       std::swap(N0, N1);
16151     // or (and (m, y), (pandn m, x))
16152     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16153       SDValue Mask = N1.getOperand(0);
16154       SDValue X    = N1.getOperand(1);
16155       SDValue Y;
16156       if (N0.getOperand(0) == Mask)
16157         Y = N0.getOperand(1);
16158       if (N0.getOperand(1) == Mask)
16159         Y = N0.getOperand(0);
16160
16161       // Check to see if the mask appeared in both the AND and ANDNP and
16162       if (!Y.getNode())
16163         return SDValue();
16164
16165       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16166       // Look through mask bitcast.
16167       if (Mask.getOpcode() == ISD::BITCAST)
16168         Mask = Mask.getOperand(0);
16169       if (X.getOpcode() == ISD::BITCAST)
16170         X = X.getOperand(0);
16171       if (Y.getOpcode() == ISD::BITCAST)
16172         Y = Y.getOperand(0);
16173
16174       EVT MaskVT = Mask.getValueType();
16175
16176       // Validate that the Mask operand is a vector sra node.
16177       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16178       // there is no psrai.b
16179       if (Mask.getOpcode() != X86ISD::VSRAI)
16180         return SDValue();
16181
16182       // Check that the SRA is all signbits.
16183       SDValue SraC = Mask.getOperand(1);
16184       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16185       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16186       if ((SraAmt + 1) != EltBits)
16187         return SDValue();
16188
16189       DebugLoc DL = N->getDebugLoc();
16190
16191       // We are going to replace the AND, OR, NAND with either BLEND
16192       // or PSIGN, which only look at the MSB. The VSRAI instruction
16193       // does not affect the highest bit, so we can get rid of it.
16194       Mask = Mask.getOperand(0);
16195
16196       // Now we know we at least have a plendvb with the mask val.  See if
16197       // we can form a psignb/w/d.
16198       // psign = x.type == y.type == mask.type && y = sub(0, x);
16199       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16200           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16201           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16202         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16203                "Unsupported VT for PSIGN");
16204         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask);
16205         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16206       }
16207       // PBLENDVB only available on SSE 4.1
16208       if (!Subtarget->hasSSE41())
16209         return SDValue();
16210
16211       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16212
16213       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16214       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16215       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16216       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16217       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16218     }
16219   }
16220
16221   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16222     return SDValue();
16223
16224   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16225   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16226     std::swap(N0, N1);
16227   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16228     return SDValue();
16229   if (!N0.hasOneUse() || !N1.hasOneUse())
16230     return SDValue();
16231
16232   SDValue ShAmt0 = N0.getOperand(1);
16233   if (ShAmt0.getValueType() != MVT::i8)
16234     return SDValue();
16235   SDValue ShAmt1 = N1.getOperand(1);
16236   if (ShAmt1.getValueType() != MVT::i8)
16237     return SDValue();
16238   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16239     ShAmt0 = ShAmt0.getOperand(0);
16240   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16241     ShAmt1 = ShAmt1.getOperand(0);
16242
16243   DebugLoc DL = N->getDebugLoc();
16244   unsigned Opc = X86ISD::SHLD;
16245   SDValue Op0 = N0.getOperand(0);
16246   SDValue Op1 = N1.getOperand(0);
16247   if (ShAmt0.getOpcode() == ISD::SUB) {
16248     Opc = X86ISD::SHRD;
16249     std::swap(Op0, Op1);
16250     std::swap(ShAmt0, ShAmt1);
16251   }
16252
16253   unsigned Bits = VT.getSizeInBits();
16254   if (ShAmt1.getOpcode() == ISD::SUB) {
16255     SDValue Sum = ShAmt1.getOperand(0);
16256     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16257       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16258       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16259         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16260       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16261         return DAG.getNode(Opc, DL, VT,
16262                            Op0, Op1,
16263                            DAG.getNode(ISD::TRUNCATE, DL,
16264                                        MVT::i8, ShAmt0));
16265     }
16266   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16267     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16268     if (ShAmt0C &&
16269         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16270       return DAG.getNode(Opc, DL, VT,
16271                          N0.getOperand(0), N1.getOperand(0),
16272                          DAG.getNode(ISD::TRUNCATE, DL,
16273                                        MVT::i8, ShAmt0));
16274   }
16275
16276   return SDValue();
16277 }
16278
16279 // Generate NEG and CMOV for integer abs.
16280 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16281   EVT VT = N->getValueType(0);
16282
16283   // Since X86 does not have CMOV for 8-bit integer, we don't convert
16284   // 8-bit integer abs to NEG and CMOV.
16285   if (VT.isInteger() && VT.getSizeInBits() == 8)
16286     return SDValue();
16287
16288   SDValue N0 = N->getOperand(0);
16289   SDValue N1 = N->getOperand(1);
16290   DebugLoc DL = N->getDebugLoc();
16291
16292   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16293   // and change it to SUB and CMOV.
16294   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16295       N0.getOpcode() == ISD::ADD &&
16296       N0.getOperand(1) == N1 &&
16297       N1.getOpcode() == ISD::SRA &&
16298       N1.getOperand(0) == N0.getOperand(0))
16299     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16300       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16301         // Generate SUB & CMOV.
16302         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16303                                   DAG.getConstant(0, VT), N0.getOperand(0));
16304
16305         SDValue Ops[] = { N0.getOperand(0), Neg,
16306                           DAG.getConstant(X86::COND_GE, MVT::i8),
16307                           SDValue(Neg.getNode(), 1) };
16308         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16309                            Ops, array_lengthof(Ops));
16310       }
16311   return SDValue();
16312 }
16313
16314 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16315 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16316                                  TargetLowering::DAGCombinerInfo &DCI,
16317                                  const X86Subtarget *Subtarget) {
16318   EVT VT = N->getValueType(0);
16319   if (DCI.isBeforeLegalizeOps())
16320     return SDValue();
16321
16322   if (Subtarget->hasCMov()) {
16323     SDValue RV = performIntegerAbsCombine(N, DAG);
16324     if (RV.getNode())
16325       return RV;
16326   }
16327
16328   // Try forming BMI if it is available.
16329   if (!Subtarget->hasBMI())
16330     return SDValue();
16331
16332   if (VT != MVT::i32 && VT != MVT::i64)
16333     return SDValue();
16334
16335   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16336
16337   // Create BLSMSK instructions by finding X ^ (X-1)
16338   SDValue N0 = N->getOperand(0);
16339   SDValue N1 = N->getOperand(1);
16340   DebugLoc DL = N->getDebugLoc();
16341
16342   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16343       isAllOnes(N0.getOperand(1)))
16344     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16345
16346   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16347       isAllOnes(N1.getOperand(1)))
16348     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16349
16350   return SDValue();
16351 }
16352
16353 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16354 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16355                                   TargetLowering::DAGCombinerInfo &DCI,
16356                                   const X86Subtarget *Subtarget) {
16357   LoadSDNode *Ld = cast<LoadSDNode>(N);
16358   EVT RegVT = Ld->getValueType(0);
16359   EVT MemVT = Ld->getMemoryVT();
16360   DebugLoc dl = Ld->getDebugLoc();
16361   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16362   unsigned RegSz = RegVT.getSizeInBits();
16363
16364   ISD::LoadExtType Ext = Ld->getExtensionType();
16365   unsigned Alignment = Ld->getAlignment();
16366   bool IsAligned = Alignment == 0 || Alignment == MemVT.getSizeInBits()/8;
16367
16368   // On Sandybridge unaligned 256bit loads are inefficient.
16369   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16370       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16371     unsigned NumElems = RegVT.getVectorNumElements();
16372     if (NumElems < 2)
16373       return SDValue();
16374
16375     SDValue Ptr = Ld->getBasePtr();
16376     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16377
16378     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16379                                   NumElems/2);
16380     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16381                                 Ld->getPointerInfo(), Ld->isVolatile(),
16382                                 Ld->isNonTemporal(), Ld->isInvariant(),
16383                                 Alignment);
16384     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16385     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16386                                 Ld->getPointerInfo(), Ld->isVolatile(),
16387                                 Ld->isNonTemporal(), Ld->isInvariant(),
16388                                 std::max(Alignment/2U, 1U));
16389     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16390                              Load1.getValue(1),
16391                              Load2.getValue(1));
16392
16393     SDValue NewVec = DAG.getUNDEF(RegVT);
16394     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16395     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16396     return DCI.CombineTo(N, NewVec, TF, true);
16397   }
16398
16399   // If this is a vector EXT Load then attempt to optimize it using a
16400   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16401   // expansion is still better than scalar code.
16402   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16403   // emit a shuffle and a arithmetic shift.
16404   // TODO: It is possible to support ZExt by zeroing the undef values
16405   // during the shuffle phase or after the shuffle.
16406   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16407       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16408     assert(MemVT != RegVT && "Cannot extend to the same type");
16409     assert(MemVT.isVector() && "Must load a vector from memory");
16410
16411     unsigned NumElems = RegVT.getVectorNumElements();
16412     unsigned MemSz = MemVT.getSizeInBits();
16413     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16414
16415     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16416       return SDValue();
16417
16418     // All sizes must be a power of two.
16419     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16420       return SDValue();
16421
16422     // Attempt to load the original value using scalar loads.
16423     // Find the largest scalar type that divides the total loaded size.
16424     MVT SclrLoadTy = MVT::i8;
16425     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16426          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16427       MVT Tp = (MVT::SimpleValueType)tp;
16428       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16429         SclrLoadTy = Tp;
16430       }
16431     }
16432
16433     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16434     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16435         (64 <= MemSz))
16436       SclrLoadTy = MVT::f64;
16437
16438     // Calculate the number of scalar loads that we need to perform
16439     // in order to load our vector from memory.
16440     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16441     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16442       return SDValue();
16443
16444     unsigned loadRegZize = RegSz;
16445     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16446       loadRegZize /= 2;
16447
16448     // Represent our vector as a sequence of elements which are the
16449     // largest scalar that we can load.
16450     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16451       loadRegZize/SclrLoadTy.getSizeInBits());
16452
16453     // Represent the data using the same element type that is stored in
16454     // memory. In practice, we ''widen'' MemVT.
16455     EVT WideVecVT = 
16456           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16457                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16458
16459     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16460       "Invalid vector type");
16461
16462     // We can't shuffle using an illegal type.
16463     if (!TLI.isTypeLegal(WideVecVT))
16464       return SDValue();
16465
16466     SmallVector<SDValue, 8> Chains;
16467     SDValue Ptr = Ld->getBasePtr();
16468     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16469                                         TLI.getPointerTy());
16470     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16471
16472     for (unsigned i = 0; i < NumLoads; ++i) {
16473       // Perform a single load.
16474       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16475                                        Ptr, Ld->getPointerInfo(),
16476                                        Ld->isVolatile(), Ld->isNonTemporal(),
16477                                        Ld->isInvariant(), Ld->getAlignment());
16478       Chains.push_back(ScalarLoad.getValue(1));
16479       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16480       // another round of DAGCombining.
16481       if (i == 0)
16482         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16483       else
16484         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16485                           ScalarLoad, DAG.getIntPtrConstant(i));
16486
16487       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16488     }
16489
16490     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16491                                Chains.size());
16492
16493     // Bitcast the loaded value to a vector of the original element type, in
16494     // the size of the target vector type.
16495     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16496     unsigned SizeRatio = RegSz/MemSz;
16497
16498     if (Ext == ISD::SEXTLOAD) {
16499       // If we have SSE4.1 we can directly emit a VSEXT node.
16500       if (Subtarget->hasSSE41()) {
16501         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16502         return DCI.CombineTo(N, Sext, TF, true);
16503       }
16504
16505       // Otherwise we'll shuffle the small elements in the high bits of the
16506       // larger type and perform an arithmetic shift. If the shift is not legal
16507       // it's better to scalarize.
16508       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16509         return SDValue();
16510
16511       // Redistribute the loaded elements into the different locations.
16512       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16513       for (unsigned i = 0; i != NumElems; ++i)
16514         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16515
16516       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16517                                            DAG.getUNDEF(WideVecVT),
16518                                            &ShuffleVec[0]);
16519
16520       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16521
16522       // Build the arithmetic shift.
16523       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16524                      MemVT.getVectorElementType().getSizeInBits();
16525       SmallVector<SDValue, 8> C(NumElems,
16526                                 DAG.getConstant(Amt, RegVT.getScalarType()));
16527       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, RegVT, &C[0], C.size());
16528       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff, BV);
16529
16530       return DCI.CombineTo(N, Shuff, TF, true);
16531     }
16532
16533     // Redistribute the loaded elements into the different locations.
16534     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16535     for (unsigned i = 0; i != NumElems; ++i)
16536       ShuffleVec[i*SizeRatio] = i;
16537
16538     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16539                                          DAG.getUNDEF(WideVecVT),
16540                                          &ShuffleVec[0]);
16541
16542     // Bitcast to the requested type.
16543     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16544     // Replace the original load with the new sequence
16545     // and return the new chain.
16546     return DCI.CombineTo(N, Shuff, TF, true);
16547   }
16548
16549   return SDValue();
16550 }
16551
16552 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16553 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16554                                    const X86Subtarget *Subtarget) {
16555   StoreSDNode *St = cast<StoreSDNode>(N);
16556   EVT VT = St->getValue().getValueType();
16557   EVT StVT = St->getMemoryVT();
16558   DebugLoc dl = St->getDebugLoc();
16559   SDValue StoredVal = St->getOperand(1);
16560   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16561   unsigned Alignment = St->getAlignment();
16562   bool IsAligned = Alignment == 0 || Alignment == VT.getSizeInBits()/8;
16563
16564   // If we are saving a concatenation of two XMM registers, perform two stores.
16565   // On Sandy Bridge, 256-bit memory operations are executed by two
16566   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16567   // memory  operation.
16568   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16569       StVT == VT && !IsAligned) {
16570     unsigned NumElems = VT.getVectorNumElements();
16571     if (NumElems < 2)
16572       return SDValue();
16573
16574     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16575     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16576
16577     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16578     SDValue Ptr0 = St->getBasePtr();
16579     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16580
16581     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16582                                 St->getPointerInfo(), St->isVolatile(),
16583                                 St->isNonTemporal(), Alignment);
16584     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16585                                 St->getPointerInfo(), St->isVolatile(),
16586                                 St->isNonTemporal(),
16587                                 std::max(Alignment/2U, 1U));
16588     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16589   }
16590
16591   // Optimize trunc store (of multiple scalars) to shuffle and store.
16592   // First, pack all of the elements in one place. Next, store to memory
16593   // in fewer chunks.
16594   if (St->isTruncatingStore() && VT.isVector()) {
16595     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16596     unsigned NumElems = VT.getVectorNumElements();
16597     assert(StVT != VT && "Cannot truncate to the same type");
16598     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16599     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16600
16601     // From, To sizes and ElemCount must be pow of two
16602     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16603     // We are going to use the original vector elt for storing.
16604     // Accumulated smaller vector elements must be a multiple of the store size.
16605     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16606
16607     unsigned SizeRatio  = FromSz / ToSz;
16608
16609     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16610
16611     // Create a type on which we perform the shuffle
16612     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16613             StVT.getScalarType(), NumElems*SizeRatio);
16614
16615     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16616
16617     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16618     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16619     for (unsigned i = 0; i != NumElems; ++i)
16620       ShuffleVec[i] = i * SizeRatio;
16621
16622     // Can't shuffle using an illegal type.
16623     if (!TLI.isTypeLegal(WideVecVT))
16624       return SDValue();
16625
16626     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16627                                          DAG.getUNDEF(WideVecVT),
16628                                          &ShuffleVec[0]);
16629     // At this point all of the data is stored at the bottom of the
16630     // register. We now need to save it to mem.
16631
16632     // Find the largest store unit
16633     MVT StoreType = MVT::i8;
16634     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16635          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16636       MVT Tp = (MVT::SimpleValueType)tp;
16637       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16638         StoreType = Tp;
16639     }
16640
16641     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16642     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16643         (64 <= NumElems * ToSz))
16644       StoreType = MVT::f64;
16645
16646     // Bitcast the original vector into a vector of store-size units
16647     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16648             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16649     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16650     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16651     SmallVector<SDValue, 8> Chains;
16652     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16653                                         TLI.getPointerTy());
16654     SDValue Ptr = St->getBasePtr();
16655
16656     // Perform one or more big stores into memory.
16657     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16658       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16659                                    StoreType, ShuffWide,
16660                                    DAG.getIntPtrConstant(i));
16661       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16662                                 St->getPointerInfo(), St->isVolatile(),
16663                                 St->isNonTemporal(), St->getAlignment());
16664       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16665       Chains.push_back(Ch);
16666     }
16667
16668     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16669                                Chains.size());
16670   }
16671
16672   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
16673   // the FP state in cases where an emms may be missing.
16674   // A preferable solution to the general problem is to figure out the right
16675   // places to insert EMMS.  This qualifies as a quick hack.
16676
16677   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16678   if (VT.getSizeInBits() != 64)
16679     return SDValue();
16680
16681   const Function *F = DAG.getMachineFunction().getFunction();
16682   bool NoImplicitFloatOps = F->getAttributes().
16683     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
16684   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16685                      && Subtarget->hasSSE2();
16686   if ((VT.isVector() ||
16687        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16688       isa<LoadSDNode>(St->getValue()) &&
16689       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16690       St->getChain().hasOneUse() && !St->isVolatile()) {
16691     SDNode* LdVal = St->getValue().getNode();
16692     LoadSDNode *Ld = 0;
16693     int TokenFactorIndex = -1;
16694     SmallVector<SDValue, 8> Ops;
16695     SDNode* ChainVal = St->getChain().getNode();
16696     // Must be a store of a load.  We currently handle two cases:  the load
16697     // is a direct child, and it's under an intervening TokenFactor.  It is
16698     // possible to dig deeper under nested TokenFactors.
16699     if (ChainVal == LdVal)
16700       Ld = cast<LoadSDNode>(St->getChain());
16701     else if (St->getValue().hasOneUse() &&
16702              ChainVal->getOpcode() == ISD::TokenFactor) {
16703       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16704         if (ChainVal->getOperand(i).getNode() == LdVal) {
16705           TokenFactorIndex = i;
16706           Ld = cast<LoadSDNode>(St->getValue());
16707         } else
16708           Ops.push_back(ChainVal->getOperand(i));
16709       }
16710     }
16711
16712     if (!Ld || !ISD::isNormalLoad(Ld))
16713       return SDValue();
16714
16715     // If this is not the MMX case, i.e. we are just turning i64 load/store
16716     // into f64 load/store, avoid the transformation if there are multiple
16717     // uses of the loaded value.
16718     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16719       return SDValue();
16720
16721     DebugLoc LdDL = Ld->getDebugLoc();
16722     DebugLoc StDL = N->getDebugLoc();
16723     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16724     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16725     // pair instead.
16726     if (Subtarget->is64Bit() || F64IsLegal) {
16727       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16728       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16729                                   Ld->getPointerInfo(), Ld->isVolatile(),
16730                                   Ld->isNonTemporal(), Ld->isInvariant(),
16731                                   Ld->getAlignment());
16732       SDValue NewChain = NewLd.getValue(1);
16733       if (TokenFactorIndex != -1) {
16734         Ops.push_back(NewChain);
16735         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16736                                Ops.size());
16737       }
16738       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16739                           St->getPointerInfo(),
16740                           St->isVolatile(), St->isNonTemporal(),
16741                           St->getAlignment());
16742     }
16743
16744     // Otherwise, lower to two pairs of 32-bit loads / stores.
16745     SDValue LoAddr = Ld->getBasePtr();
16746     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16747                                  DAG.getConstant(4, MVT::i32));
16748
16749     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16750                                Ld->getPointerInfo(),
16751                                Ld->isVolatile(), Ld->isNonTemporal(),
16752                                Ld->isInvariant(), Ld->getAlignment());
16753     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16754                                Ld->getPointerInfo().getWithOffset(4),
16755                                Ld->isVolatile(), Ld->isNonTemporal(),
16756                                Ld->isInvariant(),
16757                                MinAlign(Ld->getAlignment(), 4));
16758
16759     SDValue NewChain = LoLd.getValue(1);
16760     if (TokenFactorIndex != -1) {
16761       Ops.push_back(LoLd);
16762       Ops.push_back(HiLd);
16763       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16764                              Ops.size());
16765     }
16766
16767     LoAddr = St->getBasePtr();
16768     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16769                          DAG.getConstant(4, MVT::i32));
16770
16771     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16772                                 St->getPointerInfo(),
16773                                 St->isVolatile(), St->isNonTemporal(),
16774                                 St->getAlignment());
16775     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16776                                 St->getPointerInfo().getWithOffset(4),
16777                                 St->isVolatile(),
16778                                 St->isNonTemporal(),
16779                                 MinAlign(St->getAlignment(), 4));
16780     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16781   }
16782   return SDValue();
16783 }
16784
16785 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16786 /// and return the operands for the horizontal operation in LHS and RHS.  A
16787 /// horizontal operation performs the binary operation on successive elements
16788 /// of its first operand, then on successive elements of its second operand,
16789 /// returning the resulting values in a vector.  For example, if
16790 ///   A = < float a0, float a1, float a2, float a3 >
16791 /// and
16792 ///   B = < float b0, float b1, float b2, float b3 >
16793 /// then the result of doing a horizontal operation on A and B is
16794 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16795 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16796 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16797 /// set to A, RHS to B, and the routine returns 'true'.
16798 /// Note that the binary operation should have the property that if one of the
16799 /// operands is UNDEF then the result is UNDEF.
16800 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16801   // Look for the following pattern: if
16802   //   A = < float a0, float a1, float a2, float a3 >
16803   //   B = < float b0, float b1, float b2, float b3 >
16804   // and
16805   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16806   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16807   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16808   // which is A horizontal-op B.
16809
16810   // At least one of the operands should be a vector shuffle.
16811   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16812       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16813     return false;
16814
16815   EVT VT = LHS.getValueType();
16816
16817   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16818          "Unsupported vector type for horizontal add/sub");
16819
16820   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16821   // operate independently on 128-bit lanes.
16822   unsigned NumElts = VT.getVectorNumElements();
16823   unsigned NumLanes = VT.getSizeInBits()/128;
16824   unsigned NumLaneElts = NumElts / NumLanes;
16825   assert((NumLaneElts % 2 == 0) &&
16826          "Vector type should have an even number of elements in each lane");
16827   unsigned HalfLaneElts = NumLaneElts/2;
16828
16829   // View LHS in the form
16830   //   LHS = VECTOR_SHUFFLE A, B, LMask
16831   // If LHS is not a shuffle then pretend it is the shuffle
16832   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16833   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16834   // type VT.
16835   SDValue A, B;
16836   SmallVector<int, 16> LMask(NumElts);
16837   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16838     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16839       A = LHS.getOperand(0);
16840     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16841       B = LHS.getOperand(1);
16842     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16843     std::copy(Mask.begin(), Mask.end(), LMask.begin());
16844   } else {
16845     if (LHS.getOpcode() != ISD::UNDEF)
16846       A = LHS;
16847     for (unsigned i = 0; i != NumElts; ++i)
16848       LMask[i] = i;
16849   }
16850
16851   // Likewise, view RHS in the form
16852   //   RHS = VECTOR_SHUFFLE C, D, RMask
16853   SDValue C, D;
16854   SmallVector<int, 16> RMask(NumElts);
16855   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16856     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16857       C = RHS.getOperand(0);
16858     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16859       D = RHS.getOperand(1);
16860     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16861     std::copy(Mask.begin(), Mask.end(), RMask.begin());
16862   } else {
16863     if (RHS.getOpcode() != ISD::UNDEF)
16864       C = RHS;
16865     for (unsigned i = 0; i != NumElts; ++i)
16866       RMask[i] = i;
16867   }
16868
16869   // Check that the shuffles are both shuffling the same vectors.
16870   if (!(A == C && B == D) && !(A == D && B == C))
16871     return false;
16872
16873   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16874   if (!A.getNode() && !B.getNode())
16875     return false;
16876
16877   // If A and B occur in reverse order in RHS, then "swap" them (which means
16878   // rewriting the mask).
16879   if (A != C)
16880     CommuteVectorShuffleMask(RMask, NumElts);
16881
16882   // At this point LHS and RHS are equivalent to
16883   //   LHS = VECTOR_SHUFFLE A, B, LMask
16884   //   RHS = VECTOR_SHUFFLE A, B, RMask
16885   // Check that the masks correspond to performing a horizontal operation.
16886   for (unsigned i = 0; i != NumElts; ++i) {
16887     int LIdx = LMask[i], RIdx = RMask[i];
16888
16889     // Ignore any UNDEF components.
16890     if (LIdx < 0 || RIdx < 0 ||
16891         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16892         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16893       continue;
16894
16895     // Check that successive elements are being operated on.  If not, this is
16896     // not a horizontal operation.
16897     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16898     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16899     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16900     if (!(LIdx == Index && RIdx == Index + 1) &&
16901         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16902       return false;
16903   }
16904
16905   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16906   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16907   return true;
16908 }
16909
16910 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16911 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16912                                   const X86Subtarget *Subtarget) {
16913   EVT VT = N->getValueType(0);
16914   SDValue LHS = N->getOperand(0);
16915   SDValue RHS = N->getOperand(1);
16916
16917   // Try to synthesize horizontal adds from adds of shuffles.
16918   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16919        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16920       isHorizontalBinOp(LHS, RHS, true))
16921     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16922   return SDValue();
16923 }
16924
16925 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16926 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16927                                   const X86Subtarget *Subtarget) {
16928   EVT VT = N->getValueType(0);
16929   SDValue LHS = N->getOperand(0);
16930   SDValue RHS = N->getOperand(1);
16931
16932   // Try to synthesize horizontal subs from subs of shuffles.
16933   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16934        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16935       isHorizontalBinOp(LHS, RHS, false))
16936     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16937   return SDValue();
16938 }
16939
16940 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16941 /// X86ISD::FXOR nodes.
16942 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16943   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16944   // F[X]OR(0.0, x) -> x
16945   // F[X]OR(x, 0.0) -> x
16946   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16947     if (C->getValueAPF().isPosZero())
16948       return N->getOperand(1);
16949   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16950     if (C->getValueAPF().isPosZero())
16951       return N->getOperand(0);
16952   return SDValue();
16953 }
16954
16955 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16956 /// X86ISD::FMAX nodes.
16957 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16958   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16959
16960   // Only perform optimizations if UnsafeMath is used.
16961   if (!DAG.getTarget().Options.UnsafeFPMath)
16962     return SDValue();
16963
16964   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16965   // into FMINC and FMAXC, which are Commutative operations.
16966   unsigned NewOp = 0;
16967   switch (N->getOpcode()) {
16968     default: llvm_unreachable("unknown opcode");
16969     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
16970     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
16971   }
16972
16973   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16974                      N->getOperand(0), N->getOperand(1));
16975 }
16976
16977 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16978 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16979   // FAND(0.0, x) -> 0.0
16980   // FAND(x, 0.0) -> 0.0
16981   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16982     if (C->getValueAPF().isPosZero())
16983       return N->getOperand(0);
16984   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16985     if (C->getValueAPF().isPosZero())
16986       return N->getOperand(1);
16987   return SDValue();
16988 }
16989
16990 static SDValue PerformBTCombine(SDNode *N,
16991                                 SelectionDAG &DAG,
16992                                 TargetLowering::DAGCombinerInfo &DCI) {
16993   // BT ignores high bits in the bit index operand.
16994   SDValue Op1 = N->getOperand(1);
16995   if (Op1.hasOneUse()) {
16996     unsigned BitWidth = Op1.getValueSizeInBits();
16997     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16998     APInt KnownZero, KnownOne;
16999     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17000                                           !DCI.isBeforeLegalizeOps());
17001     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17002     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17003         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17004       DCI.CommitTargetLoweringOpt(TLO);
17005   }
17006   return SDValue();
17007 }
17008
17009 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17010   SDValue Op = N->getOperand(0);
17011   if (Op.getOpcode() == ISD::BITCAST)
17012     Op = Op.getOperand(0);
17013   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17014   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17015       VT.getVectorElementType().getSizeInBits() ==
17016       OpVT.getVectorElementType().getSizeInBits()) {
17017     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17018   }
17019   return SDValue();
17020 }
17021
17022 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17023                                   TargetLowering::DAGCombinerInfo &DCI,
17024                                   const X86Subtarget *Subtarget) {
17025   if (!DCI.isBeforeLegalizeOps())
17026     return SDValue();
17027
17028   if (!Subtarget->hasFp256())
17029     return SDValue();
17030
17031   EVT VT = N->getValueType(0);
17032   if (VT.isVector() && VT.getSizeInBits() == 256) {
17033     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17034     if (R.getNode())
17035       return R;
17036   }
17037
17038   return SDValue();
17039 }
17040
17041 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17042                                  const X86Subtarget* Subtarget) {
17043   DebugLoc dl = N->getDebugLoc();
17044   EVT VT = N->getValueType(0);
17045
17046   // Let legalize expand this if it isn't a legal type yet.
17047   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17048     return SDValue();
17049
17050   EVT ScalarVT = VT.getScalarType();
17051   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17052       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17053     return SDValue();
17054
17055   SDValue A = N->getOperand(0);
17056   SDValue B = N->getOperand(1);
17057   SDValue C = N->getOperand(2);
17058
17059   bool NegA = (A.getOpcode() == ISD::FNEG);
17060   bool NegB = (B.getOpcode() == ISD::FNEG);
17061   bool NegC = (C.getOpcode() == ISD::FNEG);
17062
17063   // Negative multiplication when NegA xor NegB
17064   bool NegMul = (NegA != NegB);
17065   if (NegA)
17066     A = A.getOperand(0);
17067   if (NegB)
17068     B = B.getOperand(0);
17069   if (NegC)
17070     C = C.getOperand(0);
17071
17072   unsigned Opcode;
17073   if (!NegMul)
17074     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17075   else
17076     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17077
17078   return DAG.getNode(Opcode, dl, VT, A, B, C);
17079 }
17080
17081 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17082                                   TargetLowering::DAGCombinerInfo &DCI,
17083                                   const X86Subtarget *Subtarget) {
17084   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17085   //           (and (i32 x86isd::setcc_carry), 1)
17086   // This eliminates the zext. This transformation is necessary because
17087   // ISD::SETCC is always legalized to i8.
17088   DebugLoc dl = N->getDebugLoc();
17089   SDValue N0 = N->getOperand(0);
17090   EVT VT = N->getValueType(0);
17091
17092   if (N0.getOpcode() == ISD::AND &&
17093       N0.hasOneUse() &&
17094       N0.getOperand(0).hasOneUse()) {
17095     SDValue N00 = N0.getOperand(0);
17096     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17097       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17098       if (!C || C->getZExtValue() != 1)
17099         return SDValue();
17100       return DAG.getNode(ISD::AND, dl, VT,
17101                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17102                                      N00.getOperand(0), N00.getOperand(1)),
17103                          DAG.getConstant(1, VT));
17104     }
17105   }
17106
17107   if (VT.is256BitVector()) {
17108     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17109     if (R.getNode())
17110       return R;
17111   }
17112
17113   return SDValue();
17114 }
17115
17116 // Optimize x == -y --> x+y == 0
17117 //          x != -y --> x+y != 0
17118 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17119   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17120   SDValue LHS = N->getOperand(0);
17121   SDValue RHS = N->getOperand(1);
17122
17123   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17124     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17125       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17126         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17127                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17128         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17129                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17130       }
17131   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17132     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17133       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17134         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17135                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17136         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17137                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17138       }
17139   return SDValue();
17140 }
17141
17142 // Helper function of PerformSETCCCombine. It is to materialize "setb reg" 
17143 // as "sbb reg,reg", since it can be extended without zext and produces 
17144 // an all-ones bit which is more useful than 0/1 in some cases.
17145 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17146   return DAG.getNode(ISD::AND, DL, MVT::i8,
17147                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17148                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17149                      DAG.getConstant(1, MVT::i8));
17150 }
17151
17152 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17153 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17154                                    TargetLowering::DAGCombinerInfo &DCI,
17155                                    const X86Subtarget *Subtarget) {
17156   DebugLoc DL = N->getDebugLoc();
17157   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17158   SDValue EFLAGS = N->getOperand(1);
17159
17160   if (CC == X86::COND_A) {
17161     // Try to convert COND_A into COND_B in an attempt to facilitate 
17162     // materializing "setb reg".
17163     //
17164     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17165     // cannot take an immediate as its first operand.
17166     //
17167     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() && 
17168         EFLAGS.getValueType().isInteger() &&
17169         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17170       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17171                                    EFLAGS.getNode()->getVTList(),
17172                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17173       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17174       return MaterializeSETB(DL, NewEFLAGS, DAG);
17175     }
17176   }
17177
17178   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17179   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17180   // cases.
17181   if (CC == X86::COND_B)
17182     return MaterializeSETB(DL, EFLAGS, DAG);
17183
17184   SDValue Flags;
17185
17186   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17187   if (Flags.getNode()) {
17188     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17189     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17190   }
17191
17192   return SDValue();
17193 }
17194
17195 // Optimize branch condition evaluation.
17196 //
17197 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17198                                     TargetLowering::DAGCombinerInfo &DCI,
17199                                     const X86Subtarget *Subtarget) {
17200   DebugLoc DL = N->getDebugLoc();
17201   SDValue Chain = N->getOperand(0);
17202   SDValue Dest = N->getOperand(1);
17203   SDValue EFLAGS = N->getOperand(3);
17204   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17205
17206   SDValue Flags;
17207
17208   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17209   if (Flags.getNode()) {
17210     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17211     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17212                        Flags);
17213   }
17214
17215   return SDValue();
17216 }
17217
17218 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17219                                         const X86TargetLowering *XTLI) {
17220   SDValue Op0 = N->getOperand(0);
17221   EVT InVT = Op0->getValueType(0);
17222
17223   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17224   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17225     DebugLoc dl = N->getDebugLoc();
17226     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17227     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17228     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17229   }
17230
17231   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17232   // a 32-bit target where SSE doesn't support i64->FP operations.
17233   if (Op0.getOpcode() == ISD::LOAD) {
17234     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17235     EVT VT = Ld->getValueType(0);
17236     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17237         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17238         !XTLI->getSubtarget()->is64Bit() &&
17239         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17240       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17241                                           Ld->getChain(), Op0, DAG);
17242       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17243       return FILDChain;
17244     }
17245   }
17246   return SDValue();
17247 }
17248
17249 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17250 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17251                                  X86TargetLowering::DAGCombinerInfo &DCI) {
17252   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17253   // the result is either zero or one (depending on the input carry bit).
17254   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17255   if (X86::isZeroNode(N->getOperand(0)) &&
17256       X86::isZeroNode(N->getOperand(1)) &&
17257       // We don't have a good way to replace an EFLAGS use, so only do this when
17258       // dead right now.
17259       SDValue(N, 1).use_empty()) {
17260     DebugLoc DL = N->getDebugLoc();
17261     EVT VT = N->getValueType(0);
17262     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17263     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17264                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17265                                            DAG.getConstant(X86::COND_B,MVT::i8),
17266                                            N->getOperand(2)),
17267                                DAG.getConstant(1, VT));
17268     return DCI.CombineTo(N, Res1, CarryOut);
17269   }
17270
17271   return SDValue();
17272 }
17273
17274 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17275 //      (add Y, (setne X, 0)) -> sbb -1, Y
17276 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17277 //      (sub (setne X, 0), Y) -> adc -1, Y
17278 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17279   DebugLoc DL = N->getDebugLoc();
17280
17281   // Look through ZExts.
17282   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17283   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17284     return SDValue();
17285
17286   SDValue SetCC = Ext.getOperand(0);
17287   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17288     return SDValue();
17289
17290   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17291   if (CC != X86::COND_E && CC != X86::COND_NE)
17292     return SDValue();
17293
17294   SDValue Cmp = SetCC.getOperand(1);
17295   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17296       !X86::isZeroNode(Cmp.getOperand(1)) ||
17297       !Cmp.getOperand(0).getValueType().isInteger())
17298     return SDValue();
17299
17300   SDValue CmpOp0 = Cmp.getOperand(0);
17301   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17302                                DAG.getConstant(1, CmpOp0.getValueType()));
17303
17304   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17305   if (CC == X86::COND_NE)
17306     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17307                        DL, OtherVal.getValueType(), OtherVal,
17308                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17309   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17310                      DL, OtherVal.getValueType(), OtherVal,
17311                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17312 }
17313
17314 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17315 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17316                                  const X86Subtarget *Subtarget) {
17317   EVT VT = N->getValueType(0);
17318   SDValue Op0 = N->getOperand(0);
17319   SDValue Op1 = N->getOperand(1);
17320
17321   // Try to synthesize horizontal adds from adds of shuffles.
17322   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17323        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17324       isHorizontalBinOp(Op0, Op1, true))
17325     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17326
17327   return OptimizeConditionalInDecrement(N, DAG);
17328 }
17329
17330 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17331                                  const X86Subtarget *Subtarget) {
17332   SDValue Op0 = N->getOperand(0);
17333   SDValue Op1 = N->getOperand(1);
17334
17335   // X86 can't encode an immediate LHS of a sub. See if we can push the
17336   // negation into a preceding instruction.
17337   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17338     // If the RHS of the sub is a XOR with one use and a constant, invert the
17339     // immediate. Then add one to the LHS of the sub so we can turn
17340     // X-Y -> X+~Y+1, saving one register.
17341     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17342         isa<ConstantSDNode>(Op1.getOperand(1))) {
17343       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17344       EVT VT = Op0.getValueType();
17345       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17346                                    Op1.getOperand(0),
17347                                    DAG.getConstant(~XorC, VT));
17348       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17349                          DAG.getConstant(C->getAPIntValue()+1, VT));
17350     }
17351   }
17352
17353   // Try to synthesize horizontal adds from adds of shuffles.
17354   EVT VT = N->getValueType(0);
17355   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17356        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17357       isHorizontalBinOp(Op0, Op1, true))
17358     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17359
17360   return OptimizeConditionalInDecrement(N, DAG);
17361 }
17362
17363 /// performVZEXTCombine - Performs build vector combines
17364 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17365                                         TargetLowering::DAGCombinerInfo &DCI,
17366                                         const X86Subtarget *Subtarget) {
17367   // (vzext (bitcast (vzext (x)) -> (vzext x)
17368   SDValue In = N->getOperand(0);
17369   while (In.getOpcode() == ISD::BITCAST)
17370     In = In.getOperand(0);
17371
17372   if (In.getOpcode() != X86ISD::VZEXT)
17373     return SDValue();
17374
17375   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
17376 }
17377
17378 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17379                                              DAGCombinerInfo &DCI) const {
17380   SelectionDAG &DAG = DCI.DAG;
17381   switch (N->getOpcode()) {
17382   default: break;
17383   case ISD::EXTRACT_VECTOR_ELT:
17384     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17385   case ISD::VSELECT:
17386   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17387   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17388   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17389   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17390   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17391   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17392   case ISD::SHL:
17393   case ISD::SRA:
17394   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17395   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17396   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17397   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17398   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17399   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17400   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17401   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17402   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17403   case X86ISD::FXOR:
17404   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17405   case X86ISD::FMIN:
17406   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17407   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17408   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17409   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17410   case ISD::ANY_EXTEND:
17411   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17412   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17413   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17414   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17415   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17416   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17417   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17418   case X86ISD::SHUFP:       // Handle all target specific shuffles
17419   case X86ISD::PALIGNR:
17420   case X86ISD::UNPCKH:
17421   case X86ISD::UNPCKL:
17422   case X86ISD::MOVHLPS:
17423   case X86ISD::MOVLHPS:
17424   case X86ISD::PSHUFD:
17425   case X86ISD::PSHUFHW:
17426   case X86ISD::PSHUFLW:
17427   case X86ISD::MOVSS:
17428   case X86ISD::MOVSD:
17429   case X86ISD::VPERMILP:
17430   case X86ISD::VPERM2X128:
17431   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17432   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17433   }
17434
17435   return SDValue();
17436 }
17437
17438 /// isTypeDesirableForOp - Return true if the target has native support for
17439 /// the specified value type and it is 'desirable' to use the type for the
17440 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17441 /// instruction encodings are longer and some i16 instructions are slow.
17442 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17443   if (!isTypeLegal(VT))
17444     return false;
17445   if (VT != MVT::i16)
17446     return true;
17447
17448   switch (Opc) {
17449   default:
17450     return true;
17451   case ISD::LOAD:
17452   case ISD::SIGN_EXTEND:
17453   case ISD::ZERO_EXTEND:
17454   case ISD::ANY_EXTEND:
17455   case ISD::SHL:
17456   case ISD::SRL:
17457   case ISD::SUB:
17458   case ISD::ADD:
17459   case ISD::MUL:
17460   case ISD::AND:
17461   case ISD::OR:
17462   case ISD::XOR:
17463     return false;
17464   }
17465 }
17466
17467 /// IsDesirableToPromoteOp - This method query the target whether it is
17468 /// beneficial for dag combiner to promote the specified node. If true, it
17469 /// should return the desired promotion type by reference.
17470 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17471   EVT VT = Op.getValueType();
17472   if (VT != MVT::i16)
17473     return false;
17474
17475   bool Promote = false;
17476   bool Commute = false;
17477   switch (Op.getOpcode()) {
17478   default: break;
17479   case ISD::LOAD: {
17480     LoadSDNode *LD = cast<LoadSDNode>(Op);
17481     // If the non-extending load has a single use and it's not live out, then it
17482     // might be folded.
17483     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17484                                                      Op.hasOneUse()*/) {
17485       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17486              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17487         // The only case where we'd want to promote LOAD (rather then it being
17488         // promoted as an operand is when it's only use is liveout.
17489         if (UI->getOpcode() != ISD::CopyToReg)
17490           return false;
17491       }
17492     }
17493     Promote = true;
17494     break;
17495   }
17496   case ISD::SIGN_EXTEND:
17497   case ISD::ZERO_EXTEND:
17498   case ISD::ANY_EXTEND:
17499     Promote = true;
17500     break;
17501   case ISD::SHL:
17502   case ISD::SRL: {
17503     SDValue N0 = Op.getOperand(0);
17504     // Look out for (store (shl (load), x)).
17505     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17506       return false;
17507     Promote = true;
17508     break;
17509   }
17510   case ISD::ADD:
17511   case ISD::MUL:
17512   case ISD::AND:
17513   case ISD::OR:
17514   case ISD::XOR:
17515     Commute = true;
17516     // fallthrough
17517   case ISD::SUB: {
17518     SDValue N0 = Op.getOperand(0);
17519     SDValue N1 = Op.getOperand(1);
17520     if (!Commute && MayFoldLoad(N1))
17521       return false;
17522     // Avoid disabling potential load folding opportunities.
17523     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17524       return false;
17525     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17526       return false;
17527     Promote = true;
17528   }
17529   }
17530
17531   PVT = MVT::i32;
17532   return Promote;
17533 }
17534
17535 //===----------------------------------------------------------------------===//
17536 //                           X86 Inline Assembly Support
17537 //===----------------------------------------------------------------------===//
17538
17539 namespace {
17540   // Helper to match a string separated by whitespace.
17541   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17542     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17543
17544     for (unsigned i = 0, e = args.size(); i != e; ++i) {
17545       StringRef piece(*args[i]);
17546       if (!s.startswith(piece)) // Check if the piece matches.
17547         return false;
17548
17549       s = s.substr(piece.size());
17550       StringRef::size_type pos = s.find_first_not_of(" \t");
17551       if (pos == 0) // We matched a prefix.
17552         return false;
17553
17554       s = s.substr(pos);
17555     }
17556
17557     return s.empty();
17558   }
17559   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17560 }
17561
17562 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17563   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17564
17565   std::string AsmStr = IA->getAsmString();
17566
17567   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17568   if (!Ty || Ty->getBitWidth() % 16 != 0)
17569     return false;
17570
17571   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17572   SmallVector<StringRef, 4> AsmPieces;
17573   SplitString(AsmStr, AsmPieces, ";\n");
17574
17575   switch (AsmPieces.size()) {
17576   default: return false;
17577   case 1:
17578     // FIXME: this should verify that we are targeting a 486 or better.  If not,
17579     // we will turn this bswap into something that will be lowered to logical
17580     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
17581     // lower so don't worry about this.
17582     // bswap $0
17583     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17584         matchAsm(AsmPieces[0], "bswapl", "$0") ||
17585         matchAsm(AsmPieces[0], "bswapq", "$0") ||
17586         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17587         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17588         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17589       // No need to check constraints, nothing other than the equivalent of
17590       // "=r,0" would be valid here.
17591       return IntrinsicLowering::LowerToByteSwap(CI);
17592     }
17593
17594     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
17595     if (CI->getType()->isIntegerTy(16) &&
17596         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17597         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17598          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17599       AsmPieces.clear();
17600       const std::string &ConstraintsStr = IA->getConstraintString();
17601       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17602       std::sort(AsmPieces.begin(), AsmPieces.end());
17603       if (AsmPieces.size() == 4 &&
17604           AsmPieces[0] == "~{cc}" &&
17605           AsmPieces[1] == "~{dirflag}" &&
17606           AsmPieces[2] == "~{flags}" &&
17607           AsmPieces[3] == "~{fpsr}")
17608       return IntrinsicLowering::LowerToByteSwap(CI);
17609     }
17610     break;
17611   case 3:
17612     if (CI->getType()->isIntegerTy(32) &&
17613         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17614         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17615         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17616         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17617       AsmPieces.clear();
17618       const std::string &ConstraintsStr = IA->getConstraintString();
17619       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17620       std::sort(AsmPieces.begin(), AsmPieces.end());
17621       if (AsmPieces.size() == 4 &&
17622           AsmPieces[0] == "~{cc}" &&
17623           AsmPieces[1] == "~{dirflag}" &&
17624           AsmPieces[2] == "~{flags}" &&
17625           AsmPieces[3] == "~{fpsr}")
17626         return IntrinsicLowering::LowerToByteSwap(CI);
17627     }
17628
17629     if (CI->getType()->isIntegerTy(64)) {
17630       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17631       if (Constraints.size() >= 2 &&
17632           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17633           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17634         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
17635         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17636             matchAsm(AsmPieces[1], "bswap", "%edx") &&
17637             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17638           return IntrinsicLowering::LowerToByteSwap(CI);
17639       }
17640     }
17641     break;
17642   }
17643   return false;
17644 }
17645
17646 /// getConstraintType - Given a constraint letter, return the type of
17647 /// constraint it is for this target.
17648 X86TargetLowering::ConstraintType
17649 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17650   if (Constraint.size() == 1) {
17651     switch (Constraint[0]) {
17652     case 'R':
17653     case 'q':
17654     case 'Q':
17655     case 'f':
17656     case 't':
17657     case 'u':
17658     case 'y':
17659     case 'x':
17660     case 'Y':
17661     case 'l':
17662       return C_RegisterClass;
17663     case 'a':
17664     case 'b':
17665     case 'c':
17666     case 'd':
17667     case 'S':
17668     case 'D':
17669     case 'A':
17670       return C_Register;
17671     case 'I':
17672     case 'J':
17673     case 'K':
17674     case 'L':
17675     case 'M':
17676     case 'N':
17677     case 'G':
17678     case 'C':
17679     case 'e':
17680     case 'Z':
17681       return C_Other;
17682     default:
17683       break;
17684     }
17685   }
17686   return TargetLowering::getConstraintType(Constraint);
17687 }
17688
17689 /// Examine constraint type and operand type and determine a weight value.
17690 /// This object must already have been set up with the operand type
17691 /// and the current alternative constraint selected.
17692 TargetLowering::ConstraintWeight
17693   X86TargetLowering::getSingleConstraintMatchWeight(
17694     AsmOperandInfo &info, const char *constraint) const {
17695   ConstraintWeight weight = CW_Invalid;
17696   Value *CallOperandVal = info.CallOperandVal;
17697     // If we don't have a value, we can't do a match,
17698     // but allow it at the lowest weight.
17699   if (CallOperandVal == NULL)
17700     return CW_Default;
17701   Type *type = CallOperandVal->getType();
17702   // Look at the constraint type.
17703   switch (*constraint) {
17704   default:
17705     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17706   case 'R':
17707   case 'q':
17708   case 'Q':
17709   case 'a':
17710   case 'b':
17711   case 'c':
17712   case 'd':
17713   case 'S':
17714   case 'D':
17715   case 'A':
17716     if (CallOperandVal->getType()->isIntegerTy())
17717       weight = CW_SpecificReg;
17718     break;
17719   case 'f':
17720   case 't':
17721   case 'u':
17722     if (type->isFloatingPointTy())
17723       weight = CW_SpecificReg;
17724     break;
17725   case 'y':
17726     if (type->isX86_MMXTy() && Subtarget->hasMMX())
17727       weight = CW_SpecificReg;
17728     break;
17729   case 'x':
17730   case 'Y':
17731     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17732         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17733       weight = CW_Register;
17734     break;
17735   case 'I':
17736     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17737       if (C->getZExtValue() <= 31)
17738         weight = CW_Constant;
17739     }
17740     break;
17741   case 'J':
17742     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17743       if (C->getZExtValue() <= 63)
17744         weight = CW_Constant;
17745     }
17746     break;
17747   case 'K':
17748     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17749       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17750         weight = CW_Constant;
17751     }
17752     break;
17753   case 'L':
17754     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17755       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17756         weight = CW_Constant;
17757     }
17758     break;
17759   case 'M':
17760     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17761       if (C->getZExtValue() <= 3)
17762         weight = CW_Constant;
17763     }
17764     break;
17765   case 'N':
17766     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17767       if (C->getZExtValue() <= 0xff)
17768         weight = CW_Constant;
17769     }
17770     break;
17771   case 'G':
17772   case 'C':
17773     if (dyn_cast<ConstantFP>(CallOperandVal)) {
17774       weight = CW_Constant;
17775     }
17776     break;
17777   case 'e':
17778     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17779       if ((C->getSExtValue() >= -0x80000000LL) &&
17780           (C->getSExtValue() <= 0x7fffffffLL))
17781         weight = CW_Constant;
17782     }
17783     break;
17784   case 'Z':
17785     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17786       if (C->getZExtValue() <= 0xffffffff)
17787         weight = CW_Constant;
17788     }
17789     break;
17790   }
17791   return weight;
17792 }
17793
17794 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17795 /// with another that has more specific requirements based on the type of the
17796 /// corresponding operand.
17797 const char *X86TargetLowering::
17798 LowerXConstraint(EVT ConstraintVT) const {
17799   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17800   // 'f' like normal targets.
17801   if (ConstraintVT.isFloatingPoint()) {
17802     if (Subtarget->hasSSE2())
17803       return "Y";
17804     if (Subtarget->hasSSE1())
17805       return "x";
17806   }
17807
17808   return TargetLowering::LowerXConstraint(ConstraintVT);
17809 }
17810
17811 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17812 /// vector.  If it is invalid, don't add anything to Ops.
17813 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17814                                                      std::string &Constraint,
17815                                                      std::vector<SDValue>&Ops,
17816                                                      SelectionDAG &DAG) const {
17817   SDValue Result(0, 0);
17818
17819   // Only support length 1 constraints for now.
17820   if (Constraint.length() > 1) return;
17821
17822   char ConstraintLetter = Constraint[0];
17823   switch (ConstraintLetter) {
17824   default: break;
17825   case 'I':
17826     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17827       if (C->getZExtValue() <= 31) {
17828         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17829         break;
17830       }
17831     }
17832     return;
17833   case 'J':
17834     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17835       if (C->getZExtValue() <= 63) {
17836         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17837         break;
17838       }
17839     }
17840     return;
17841   case 'K':
17842     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17843       if (isInt<8>(C->getSExtValue())) {
17844         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17845         break;
17846       }
17847     }
17848     return;
17849   case 'N':
17850     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17851       if (C->getZExtValue() <= 255) {
17852         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17853         break;
17854       }
17855     }
17856     return;
17857   case 'e': {
17858     // 32-bit signed value
17859     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17860       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17861                                            C->getSExtValue())) {
17862         // Widen to 64 bits here to get it sign extended.
17863         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17864         break;
17865       }
17866     // FIXME gcc accepts some relocatable values here too, but only in certain
17867     // memory models; it's complicated.
17868     }
17869     return;
17870   }
17871   case 'Z': {
17872     // 32-bit unsigned value
17873     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17874       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17875                                            C->getZExtValue())) {
17876         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17877         break;
17878       }
17879     }
17880     // FIXME gcc accepts some relocatable values here too, but only in certain
17881     // memory models; it's complicated.
17882     return;
17883   }
17884   case 'i': {
17885     // Literal immediates are always ok.
17886     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17887       // Widen to 64 bits here to get it sign extended.
17888       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17889       break;
17890     }
17891
17892     // In any sort of PIC mode addresses need to be computed at runtime by
17893     // adding in a register or some sort of table lookup.  These can't
17894     // be used as immediates.
17895     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17896       return;
17897
17898     // If we are in non-pic codegen mode, we allow the address of a global (with
17899     // an optional displacement) to be used with 'i'.
17900     GlobalAddressSDNode *GA = 0;
17901     int64_t Offset = 0;
17902
17903     // Match either (GA), (GA+C), (GA+C1+C2), etc.
17904     while (1) {
17905       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17906         Offset += GA->getOffset();
17907         break;
17908       } else if (Op.getOpcode() == ISD::ADD) {
17909         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17910           Offset += C->getZExtValue();
17911           Op = Op.getOperand(0);
17912           continue;
17913         }
17914       } else if (Op.getOpcode() == ISD::SUB) {
17915         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17916           Offset += -C->getZExtValue();
17917           Op = Op.getOperand(0);
17918           continue;
17919         }
17920       }
17921
17922       // Otherwise, this isn't something we can handle, reject it.
17923       return;
17924     }
17925
17926     const GlobalValue *GV = GA->getGlobal();
17927     // If we require an extra load to get this address, as in PIC mode, we
17928     // can't accept it.
17929     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17930                                                         getTargetMachine())))
17931       return;
17932
17933     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17934                                         GA->getValueType(0), Offset);
17935     break;
17936   }
17937   }
17938
17939   if (Result.getNode()) {
17940     Ops.push_back(Result);
17941     return;
17942   }
17943   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17944 }
17945
17946 std::pair<unsigned, const TargetRegisterClass*>
17947 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17948                                                 EVT VT) const {
17949   // First, see if this is a constraint that directly corresponds to an LLVM
17950   // register class.
17951   if (Constraint.size() == 1) {
17952     // GCC Constraint Letters
17953     switch (Constraint[0]) {
17954     default: break;
17955       // TODO: Slight differences here in allocation order and leaving
17956       // RIP in the class. Do they matter any more here than they do
17957       // in the normal allocation?
17958     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17959       if (Subtarget->is64Bit()) {
17960         if (VT == MVT::i32 || VT == MVT::f32)
17961           return std::make_pair(0U, &X86::GR32RegClass);
17962         if (VT == MVT::i16)
17963           return std::make_pair(0U, &X86::GR16RegClass);
17964         if (VT == MVT::i8 || VT == MVT::i1)
17965           return std::make_pair(0U, &X86::GR8RegClass);
17966         if (VT == MVT::i64 || VT == MVT::f64)
17967           return std::make_pair(0U, &X86::GR64RegClass);
17968         break;
17969       }
17970       // 32-bit fallthrough
17971     case 'Q':   // Q_REGS
17972       if (VT == MVT::i32 || VT == MVT::f32)
17973         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17974       if (VT == MVT::i16)
17975         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17976       if (VT == MVT::i8 || VT == MVT::i1)
17977         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17978       if (VT == MVT::i64)
17979         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17980       break;
17981     case 'r':   // GENERAL_REGS
17982     case 'l':   // INDEX_REGS
17983       if (VT == MVT::i8 || VT == MVT::i1)
17984         return std::make_pair(0U, &X86::GR8RegClass);
17985       if (VT == MVT::i16)
17986         return std::make_pair(0U, &X86::GR16RegClass);
17987       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17988         return std::make_pair(0U, &X86::GR32RegClass);
17989       return std::make_pair(0U, &X86::GR64RegClass);
17990     case 'R':   // LEGACY_REGS
17991       if (VT == MVT::i8 || VT == MVT::i1)
17992         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17993       if (VT == MVT::i16)
17994         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17995       if (VT == MVT::i32 || !Subtarget->is64Bit())
17996         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17997       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17998     case 'f':  // FP Stack registers.
17999       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18000       // value to the correct fpstack register class.
18001       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18002         return std::make_pair(0U, &X86::RFP32RegClass);
18003       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18004         return std::make_pair(0U, &X86::RFP64RegClass);
18005       return std::make_pair(0U, &X86::RFP80RegClass);
18006     case 'y':   // MMX_REGS if MMX allowed.
18007       if (!Subtarget->hasMMX()) break;
18008       return std::make_pair(0U, &X86::VR64RegClass);
18009     case 'Y':   // SSE_REGS if SSE2 allowed
18010       if (!Subtarget->hasSSE2()) break;
18011       // FALL THROUGH.
18012     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18013       if (!Subtarget->hasSSE1()) break;
18014
18015       switch (VT.getSimpleVT().SimpleTy) {
18016       default: break;
18017       // Scalar SSE types.
18018       case MVT::f32:
18019       case MVT::i32:
18020         return std::make_pair(0U, &X86::FR32RegClass);
18021       case MVT::f64:
18022       case MVT::i64:
18023         return std::make_pair(0U, &X86::FR64RegClass);
18024       // Vector types.
18025       case MVT::v16i8:
18026       case MVT::v8i16:
18027       case MVT::v4i32:
18028       case MVT::v2i64:
18029       case MVT::v4f32:
18030       case MVT::v2f64:
18031         return std::make_pair(0U, &X86::VR128RegClass);
18032       // AVX types.
18033       case MVT::v32i8:
18034       case MVT::v16i16:
18035       case MVT::v8i32:
18036       case MVT::v4i64:
18037       case MVT::v8f32:
18038       case MVT::v4f64:
18039         return std::make_pair(0U, &X86::VR256RegClass);
18040       }
18041       break;
18042     }
18043   }
18044
18045   // Use the default implementation in TargetLowering to convert the register
18046   // constraint into a member of a register class.
18047   std::pair<unsigned, const TargetRegisterClass*> Res;
18048   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18049
18050   // Not found as a standard register?
18051   if (Res.second == 0) {
18052     // Map st(0) -> st(7) -> ST0
18053     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18054         tolower(Constraint[1]) == 's' &&
18055         tolower(Constraint[2]) == 't' &&
18056         Constraint[3] == '(' &&
18057         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18058         Constraint[5] == ')' &&
18059         Constraint[6] == '}') {
18060
18061       Res.first = X86::ST0+Constraint[4]-'0';
18062       Res.second = &X86::RFP80RegClass;
18063       return Res;
18064     }
18065
18066     // GCC allows "st(0)" to be called just plain "st".
18067     if (StringRef("{st}").equals_lower(Constraint)) {
18068       Res.first = X86::ST0;
18069       Res.second = &X86::RFP80RegClass;
18070       return Res;
18071     }
18072
18073     // flags -> EFLAGS
18074     if (StringRef("{flags}").equals_lower(Constraint)) {
18075       Res.first = X86::EFLAGS;
18076       Res.second = &X86::CCRRegClass;
18077       return Res;
18078     }
18079
18080     // 'A' means EAX + EDX.
18081     if (Constraint == "A") {
18082       Res.first = X86::EAX;
18083       Res.second = &X86::GR32_ADRegClass;
18084       return Res;
18085     }
18086     return Res;
18087   }
18088
18089   // Otherwise, check to see if this is a register class of the wrong value
18090   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18091   // turn into {ax},{dx}.
18092   if (Res.second->hasType(VT))
18093     return Res;   // Correct type already, nothing to do.
18094
18095   // All of the single-register GCC register classes map their values onto
18096   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18097   // really want an 8-bit or 32-bit register, map to the appropriate register
18098   // class and return the appropriate register.
18099   if (Res.second == &X86::GR16RegClass) {
18100     if (VT == MVT::i8) {
18101       unsigned DestReg = 0;
18102       switch (Res.first) {
18103       default: break;
18104       case X86::AX: DestReg = X86::AL; break;
18105       case X86::DX: DestReg = X86::DL; break;
18106       case X86::CX: DestReg = X86::CL; break;
18107       case X86::BX: DestReg = X86::BL; break;
18108       }
18109       if (DestReg) {
18110         Res.first = DestReg;
18111         Res.second = &X86::GR8RegClass;
18112       }
18113     } else if (VT == MVT::i32) {
18114       unsigned DestReg = 0;
18115       switch (Res.first) {
18116       default: break;
18117       case X86::AX: DestReg = X86::EAX; break;
18118       case X86::DX: DestReg = X86::EDX; break;
18119       case X86::CX: DestReg = X86::ECX; break;
18120       case X86::BX: DestReg = X86::EBX; break;
18121       case X86::SI: DestReg = X86::ESI; break;
18122       case X86::DI: DestReg = X86::EDI; break;
18123       case X86::BP: DestReg = X86::EBP; break;
18124       case X86::SP: DestReg = X86::ESP; break;
18125       }
18126       if (DestReg) {
18127         Res.first = DestReg;
18128         Res.second = &X86::GR32RegClass;
18129       }
18130     } else if (VT == MVT::i64) {
18131       unsigned DestReg = 0;
18132       switch (Res.first) {
18133       default: break;
18134       case X86::AX: DestReg = X86::RAX; break;
18135       case X86::DX: DestReg = X86::RDX; break;
18136       case X86::CX: DestReg = X86::RCX; break;
18137       case X86::BX: DestReg = X86::RBX; break;
18138       case X86::SI: DestReg = X86::RSI; break;
18139       case X86::DI: DestReg = X86::RDI; break;
18140       case X86::BP: DestReg = X86::RBP; break;
18141       case X86::SP: DestReg = X86::RSP; break;
18142       }
18143       if (DestReg) {
18144         Res.first = DestReg;
18145         Res.second = &X86::GR64RegClass;
18146       }
18147     }
18148   } else if (Res.second == &X86::FR32RegClass ||
18149              Res.second == &X86::FR64RegClass ||
18150              Res.second == &X86::VR128RegClass) {
18151     // Handle references to XMM physical registers that got mapped into the
18152     // wrong class.  This can happen with constraints like {xmm0} where the
18153     // target independent register mapper will just pick the first match it can
18154     // find, ignoring the required type.
18155
18156     if (VT == MVT::f32 || VT == MVT::i32)
18157       Res.second = &X86::FR32RegClass;
18158     else if (VT == MVT::f64 || VT == MVT::i64)
18159       Res.second = &X86::FR64RegClass;
18160     else if (X86::VR128RegClass.hasType(VT))
18161       Res.second = &X86::VR128RegClass;
18162     else if (X86::VR256RegClass.hasType(VT))
18163       Res.second = &X86::VR256RegClass;
18164   }
18165
18166   return Res;
18167 }