When expanding atomic load arith instructions, do not lose target flags. rdar://12453106
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "X86.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference.  Idx is an index in the 128 bits we
64 /// want.  It need not be aligned to a 128-bit bounday.  That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67                                    SelectionDAG &DAG, DebugLoc dl) {
68   EVT VT = Vec.getValueType();
69   assert(VT.is256BitVector() && "Unexpected vector size!");
70   EVT ElVT = VT.getVectorElementType();
71   unsigned Factor = VT.getSizeInBits()/128;
72   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                   VT.getVectorNumElements()/Factor);
74
75   // Extract from UNDEF is UNDEF.
76   if (Vec.getOpcode() == ISD::UNDEF)
77     return DAG.getUNDEF(ResultVT);
78
79   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80   // we can match to VEXTRACTF128.
81   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83   // This is the index of the first element of the 128-bit chunk
84   // we want.
85   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                                * ElemsPerChunk);
87
88   SDValue VecIdx = DAG.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   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
162
163   RegInfo = TM.getRegisterInfo();
164   TD = getDataLayout();
165
166   // Set up the TargetLowering object.
167   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168
169   // X86 is weird, it always uses i8 for shift amounts and setcc results.
170   setBooleanContents(ZeroOrOneBooleanContent);
171   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174   // For 64-bit since we have so many registers use the ILP scheduler, for
175   // 32-bit code use the register pressure specific scheduling.
176   // For Atom, always use ILP scheduling.
177   if (Subtarget->isAtom())
178     setSchedulingPreference(Sched::ILP);
179   else if (Subtarget->is64Bit())
180     setSchedulingPreference(Sched::ILP);
181   else
182     setSchedulingPreference(Sched::RegPressure);
183   setStackPointerRegisterToSaveRestore(X86StackPtr);
184
185   // Bypass i32 with i8 on Atom when compiling with O2
186   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
187     addBypassSlowDiv(32, 8);
188
189   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
190     // Setup Windows compiler runtime calls.
191     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
192     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
193     setLibcallName(RTLIB::SREM_I64, "_allrem");
194     setLibcallName(RTLIB::UREM_I64, "_aullrem");
195     setLibcallName(RTLIB::MUL_I64, "_allmul");
196     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
197     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
198     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
199     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
200     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
201
202     // The _ftol2 runtime function has an unusual calling conv, which
203     // is modeled by a special pseudo-instruction.
204     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
205     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
206     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
207     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
208   }
209
210   if (Subtarget->isTargetDarwin()) {
211     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
212     setUseUnderscoreSetJmp(false);
213     setUseUnderscoreLongJmp(false);
214   } else if (Subtarget->isTargetMingw()) {
215     // MS runtime is weird: it exports _setjmp, but longjmp!
216     setUseUnderscoreSetJmp(true);
217     setUseUnderscoreLongJmp(false);
218   } else {
219     setUseUnderscoreSetJmp(true);
220     setUseUnderscoreLongJmp(true);
221   }
222
223   // Set up the register classes.
224   addRegisterClass(MVT::i8, &X86::GR8RegClass);
225   addRegisterClass(MVT::i16, &X86::GR16RegClass);
226   addRegisterClass(MVT::i32, &X86::GR32RegClass);
227   if (Subtarget->is64Bit())
228     addRegisterClass(MVT::i64, &X86::GR64RegClass);
229
230   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
231
232   // We don't accept any truncstore of integer registers.
233   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
234   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
235   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
236   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
237   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
238   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
239
240   // SETOEQ and SETUNE require checking two conditions.
241   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
242   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
243   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
244   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
245   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
246   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
247
248   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
249   // operation.
250   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
251   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
252   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
253
254   if (Subtarget->is64Bit()) {
255     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
256     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
257   } else if (!TM.Options.UseSoftFloat) {
258     // We have an algorithm for SSE2->double, and we turn this into a
259     // 64-bit FILD followed by conditional FADD for other targets.
260     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
261     // We have an algorithm for SSE2, and we turn this into a 64-bit
262     // FILD for other targets.
263     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
264   }
265
266   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
267   // this operation.
268   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
269   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
270
271   if (!TM.Options.UseSoftFloat) {
272     // SSE has no i16 to fp conversion, only i32
273     if (X86ScalarSSEf32) {
274       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
275       // f32 and f64 cases are Legal, f80 case is not
276       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
277     } else {
278       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
279       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280     }
281   } else {
282     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
283     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
284   }
285
286   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
287   // are Legal, f80 is custom lowered.
288   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
289   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
290
291   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
292   // this operation.
293   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
294   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
295
296   if (X86ScalarSSEf32) {
297     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
298     // f32 and f64 cases are Legal, f80 case is not
299     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
300   } else {
301     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
302     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303   }
304
305   // Handle FP_TO_UINT by promoting the destination to a larger signed
306   // conversion.
307   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
308   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
309   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
310
311   if (Subtarget->is64Bit()) {
312     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
313     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
314   } else if (!TM.Options.UseSoftFloat) {
315     // Since AVX is a superset of SSE3, only check for SSE here.
316     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
317       // Expand FP_TO_UINT into a select.
318       // FIXME: We would like to use a Custom expander here eventually to do
319       // the optimal thing for SSE vs. the default expansion in the legalizer.
320       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
321     else
322       // With SSE3 we can use fisttpll to convert to a signed i64; without
323       // SSE, we're stuck with a fistpll.
324       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
325   }
326
327   if (isTargetFTOL()) {
328     // Use the _ftol2 runtime function, which has a pseudo-instruction
329     // to handle its weird calling convention.
330     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
331   }
332
333   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
334   if (!X86ScalarSSEf64) {
335     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
336     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
337     if (Subtarget->is64Bit()) {
338       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
339       // Without SSE, i64->f64 goes through memory.
340       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
341     }
342   }
343
344   // Scalar integer divide and remainder are lowered to use operations that
345   // produce two results, to match the available instructions. This exposes
346   // the two-result form to trivial CSE, which is able to combine x/y and x%y
347   // into a single instruction.
348   //
349   // Scalar integer multiply-high is also lowered to use two-result
350   // operations, to match the available instructions. However, plain multiply
351   // (low) operations are left as Legal, as there are single-result
352   // instructions for this in x86. Using the two-result multiply instructions
353   // when both high and low results are needed must be arranged by dagcombine.
354   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
355     MVT VT = IntVTs[i];
356     setOperationAction(ISD::MULHS, VT, Expand);
357     setOperationAction(ISD::MULHU, VT, Expand);
358     setOperationAction(ISD::SDIV, VT, Expand);
359     setOperationAction(ISD::UDIV, VT, Expand);
360     setOperationAction(ISD::SREM, VT, Expand);
361     setOperationAction(ISD::UREM, VT, Expand);
362
363     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
364     setOperationAction(ISD::ADDC, VT, Custom);
365     setOperationAction(ISD::ADDE, VT, Custom);
366     setOperationAction(ISD::SUBC, VT, Custom);
367     setOperationAction(ISD::SUBE, VT, Custom);
368   }
369
370   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
371   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
372   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
373   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
374   if (Subtarget->is64Bit())
375     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
376   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
377   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
378   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
379   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
380   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
381   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
382   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
383   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
384
385   // Promote the i8 variants and force them on up to i32 which has a shorter
386   // encoding.
387   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
388   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
389   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
390   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
391   if (Subtarget->hasBMI()) {
392     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
393     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
394     if (Subtarget->is64Bit())
395       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
396   } else {
397     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
398     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
399     if (Subtarget->is64Bit())
400       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
401   }
402
403   if (Subtarget->hasLZCNT()) {
404     // When promoting the i8 variants, force them to i32 for a shorter
405     // encoding.
406     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
407     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
408     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
409     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
410     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
411     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
412     if (Subtarget->is64Bit())
413       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
414   } else {
415     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
416     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
417     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
418     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
419     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
420     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
421     if (Subtarget->is64Bit()) {
422       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
423       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
424     }
425   }
426
427   if (Subtarget->hasPOPCNT()) {
428     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
429   } else {
430     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
431     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
432     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
433     if (Subtarget->is64Bit())
434       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
435   }
436
437   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
438   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
439
440   // These should be promoted to a larger select which is supported.
441   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
442   // X86 wants to expand cmov itself.
443   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
444   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
446   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
447   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
448   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
450   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
452   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
453   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
454   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
455   if (Subtarget->is64Bit()) {
456     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
457     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
458   }
459   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
460
461   // Darwin ABI issue.
462   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
463   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
464   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
465   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
466   if (Subtarget->is64Bit())
467     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
468   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
469   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
470   if (Subtarget->is64Bit()) {
471     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
472     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
473     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
474     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
475     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
476   }
477   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
478   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
479   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
480   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
481   if (Subtarget->is64Bit()) {
482     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
483     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
484     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
485   }
486
487   if (Subtarget->hasSSE1())
488     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
489
490   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
491   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
492
493   // On X86 and X86-64, atomic operations are lowered to locked instructions.
494   // Locked instructions, in turn, have implicit fence semantics (all memory
495   // operations are flushed before issuing the locked instruction, and they
496   // are not buffered), so we can fold away the common pattern of
497   // fence-atomic-fence.
498   setShouldFoldAtomicFences(true);
499
500   // Expand certain atomics
501   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
502     MVT VT = IntVTs[i];
503     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
504     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
505     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
506   }
507
508   if (!Subtarget->is64Bit()) {
509     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
512     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
513     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
514     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
515     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
516     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
517     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
518     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
519     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
520     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
521   }
522
523   if (Subtarget->hasCmpxchg16b()) {
524     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
525   }
526
527   // FIXME - use subtarget debug flags
528   if (!Subtarget->isTargetDarwin() &&
529       !Subtarget->isTargetELF() &&
530       !Subtarget->isTargetCygMing()) {
531     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
532   }
533
534   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
535   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
536   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
537   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
538   if (Subtarget->is64Bit()) {
539     setExceptionPointerRegister(X86::RAX);
540     setExceptionSelectorRegister(X86::RDX);
541   } else {
542     setExceptionPointerRegister(X86::EAX);
543     setExceptionSelectorRegister(X86::EDX);
544   }
545   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
546   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
547
548   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
549   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
550
551   setOperationAction(ISD::TRAP, MVT::Other, Legal);
552
553   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
554   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
555   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
556   if (Subtarget->is64Bit()) {
557     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
558     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
559   } else {
560     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
561     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
562   }
563
564   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
565   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
566
567   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
568     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
569                        MVT::i64 : MVT::i32, Custom);
570   else if (TM.Options.EnableSegmentedStacks)
571     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
572                        MVT::i64 : MVT::i32, Custom);
573   else
574     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
575                        MVT::i64 : MVT::i32, Expand);
576
577   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
578     // f32 and f64 use SSE.
579     // Set up the FP register classes.
580     addRegisterClass(MVT::f32, &X86::FR32RegClass);
581     addRegisterClass(MVT::f64, &X86::FR64RegClass);
582
583     // Use ANDPD to simulate FABS.
584     setOperationAction(ISD::FABS , MVT::f64, Custom);
585     setOperationAction(ISD::FABS , MVT::f32, Custom);
586
587     // Use XORP to simulate FNEG.
588     setOperationAction(ISD::FNEG , MVT::f64, Custom);
589     setOperationAction(ISD::FNEG , MVT::f32, Custom);
590
591     // Use ANDPD and ORPD to simulate FCOPYSIGN.
592     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
593     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
594
595     // Lower this to FGETSIGNx86 plus an AND.
596     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
597     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
598
599     // We don't support sin/cos/fmod
600     setOperationAction(ISD::FSIN , MVT::f64, Expand);
601     setOperationAction(ISD::FCOS , MVT::f64, Expand);
602     setOperationAction(ISD::FSIN , MVT::f32, Expand);
603     setOperationAction(ISD::FCOS , MVT::f32, Expand);
604
605     // Expand FP immediates into loads from the stack, except for the special
606     // cases we handle.
607     addLegalFPImmediate(APFloat(+0.0)); // xorpd
608     addLegalFPImmediate(APFloat(+0.0f)); // xorps
609   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
610     // Use SSE for f32, x87 for f64.
611     // Set up the FP register classes.
612     addRegisterClass(MVT::f32, &X86::FR32RegClass);
613     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
614
615     // Use ANDPS to simulate FABS.
616     setOperationAction(ISD::FABS , MVT::f32, Custom);
617
618     // Use XORP to simulate FNEG.
619     setOperationAction(ISD::FNEG , MVT::f32, Custom);
620
621     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
622
623     // Use ANDPS and ORPS to simulate FCOPYSIGN.
624     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
625     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
626
627     // We don't support sin/cos/fmod
628     setOperationAction(ISD::FSIN , MVT::f32, Expand);
629     setOperationAction(ISD::FCOS , MVT::f32, Expand);
630
631     // Special cases we handle for FP constants.
632     addLegalFPImmediate(APFloat(+0.0f)); // xorps
633     addLegalFPImmediate(APFloat(+0.0)); // FLD0
634     addLegalFPImmediate(APFloat(+1.0)); // FLD1
635     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
636     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
637
638     if (!TM.Options.UnsafeFPMath) {
639       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
640       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
641     }
642   } else if (!TM.Options.UseSoftFloat) {
643     // f32 and f64 in x87.
644     // Set up the FP register classes.
645     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
646     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
647
648     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
649     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
650     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
651     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
652
653     if (!TM.Options.UnsafeFPMath) {
654       setOperationAction(ISD::FSIN           , MVT::f32  , Expand);
655       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
656       setOperationAction(ISD::FCOS           , MVT::f32  , Expand);
657       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
658     }
659     addLegalFPImmediate(APFloat(+0.0)); // FLD0
660     addLegalFPImmediate(APFloat(+1.0)); // FLD1
661     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
662     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
663     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
664     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
665     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
666     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
667   }
668
669   // We don't support FMA.
670   setOperationAction(ISD::FMA, MVT::f64, Expand);
671   setOperationAction(ISD::FMA, MVT::f32, Expand);
672
673   // Long double always uses X87.
674   if (!TM.Options.UseSoftFloat) {
675     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
676     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
677     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
678     {
679       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
680       addLegalFPImmediate(TmpFlt);  // FLD0
681       TmpFlt.changeSign();
682       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
683
684       bool ignored;
685       APFloat TmpFlt2(+1.0);
686       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
687                       &ignored);
688       addLegalFPImmediate(TmpFlt2);  // FLD1
689       TmpFlt2.changeSign();
690       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
691     }
692
693     if (!TM.Options.UnsafeFPMath) {
694       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
695       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
696     }
697
698     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
699     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
700     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
701     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
702     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
703     setOperationAction(ISD::FMA, MVT::f80, Expand);
704   }
705
706   // Always use a library call for pow.
707   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
708   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
709   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
710
711   setOperationAction(ISD::FLOG, MVT::f80, Expand);
712   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
713   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
714   setOperationAction(ISD::FEXP, MVT::f80, Expand);
715   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
716
717   // First set operation action for all vector types to either promote
718   // (for widening) or expand (for scalarization). Then we will selectively
719   // turn on ones that can be effectively codegen'd.
720   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
721            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
722     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
737     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
739     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
740     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
770     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
771     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
772     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
773     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
774     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
775     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
776     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
777     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
778     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
779     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
780     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
781     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
782              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
783       setTruncStoreAction((MVT::SimpleValueType)VT,
784                           (MVT::SimpleValueType)InnerVT, Expand);
785     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
786     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
787     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
788   }
789
790   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
791   // with -msoft-float, disable use of MMX as well.
792   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
793     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
794     // No operations on x86mmx supported, everything uses intrinsics.
795   }
796
797   // MMX-sized vectors (other than x86mmx) are expected to be expanded
798   // into smaller operations.
799   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
800   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
801   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
802   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
803   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
804   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
805   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
806   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
807   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
808   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
809   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
810   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
811   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
812   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
813   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
814   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
815   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
816   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
817   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
818   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
819   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
820   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
821   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
822   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
823   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
824   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
825   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
826   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
827   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
828
829   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
830     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
831
832     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
833     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
834     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
835     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
836     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
837     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
838     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
839     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
840     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
841     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
842     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
843     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
844   }
845
846   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
847     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
848
849     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
850     // registers cannot be used even for integer operations.
851     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
852     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
853     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
854     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
855
856     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
857     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
858     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
859     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
860     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
861     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
862     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
863     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
864     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
865     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
866     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
867     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
868     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
869     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
870     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
871     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
872     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
873
874     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
875     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
876     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
877     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
878
879     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
880     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
881     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
882     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
883     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
884
885     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
886     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
887       MVT VT = (MVT::SimpleValueType)i;
888       // Do not attempt to custom lower non-power-of-2 vectors
889       if (!isPowerOf2_32(VT.getVectorNumElements()))
890         continue;
891       // Do not attempt to custom lower non-128-bit vectors
892       if (!VT.is128BitVector())
893         continue;
894       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
895       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
896       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
897     }
898
899     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
900     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
901     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
902     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
903     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
904     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
905
906     if (Subtarget->is64Bit()) {
907       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
908       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
909     }
910
911     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
912     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
913       MVT VT = (MVT::SimpleValueType)i;
914
915       // Do not attempt to promote non-128-bit vectors
916       if (!VT.is128BitVector())
917         continue;
918
919       setOperationAction(ISD::AND,    VT, Promote);
920       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
921       setOperationAction(ISD::OR,     VT, Promote);
922       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
923       setOperationAction(ISD::XOR,    VT, Promote);
924       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
925       setOperationAction(ISD::LOAD,   VT, Promote);
926       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
927       setOperationAction(ISD::SELECT, VT, Promote);
928       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
929     }
930
931     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
932
933     // Custom lower v2i64 and v2f64 selects.
934     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
935     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
936     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
937     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
938
939     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
940     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
941
942     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
943   }
944
945   if (Subtarget->hasSSE41()) {
946     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
947     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
948     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
949     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
950     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
951     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
952     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
953     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
954     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
955     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
956
957     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
958     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
959
960     // FIXME: Do we need to handle scalar-to-vector here?
961     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
962
963     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
964     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
965     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
966     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
967     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
968
969     // i8 and i16 vectors are custom , because the source register and source
970     // source memory operand types are not the same width.  f32 vectors are
971     // custom since the immediate controlling the insert encodes additional
972     // information.
973     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
974     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
975     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
976     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
977
978     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
979     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
980     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
981     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
982
983     // FIXME: these should be Legal but thats only for the case where
984     // the index is constant.  For now custom expand to deal with that.
985     if (Subtarget->is64Bit()) {
986       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
987       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
988     }
989   }
990
991   if (Subtarget->hasSSE2()) {
992     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
993     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
994
995     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
996     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
997
998     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
999     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1000
1001     if (Subtarget->hasAVX2()) {
1002       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1003       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1004
1005       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1006       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1007
1008       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1009     } else {
1010       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1011       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1012
1013       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1014       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1015
1016       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1017     }
1018   }
1019
1020   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1021     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1022     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1023     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1024     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1025     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1026     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1027
1028     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1029     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1030     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1031
1032     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1033     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1034     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1035     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1036     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1037     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1038     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1039     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1040
1041     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1042     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1043     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1044     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1045     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1046     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1047     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1048     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1049
1050     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1051     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1052     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1053
1054     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1055
1056     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1057     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1058
1059     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1060     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1061
1062     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1063     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1064
1065     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1066     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1067     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1068     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1069
1070     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1071     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1072     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1073
1074     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1075     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1076     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1077     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1078
1079     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1080       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1081       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1082       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1083       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1084       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1085       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1086     }
1087
1088     if (Subtarget->hasAVX2()) {
1089       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1090       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1091       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1092       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1093
1094       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1095       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1096       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1097       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1098
1099       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1100       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1101       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1102       // Don't lower v32i8 because there is no 128-bit byte mul
1103
1104       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1105
1106       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1107       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1108
1109       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1110       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1111
1112       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1113     } else {
1114       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1115       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1116       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1117       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1118
1119       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1120       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1121       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1122       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1123
1124       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1125       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1126       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1127       // Don't lower v32i8 because there is no 128-bit byte mul
1128
1129       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1130       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1131
1132       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1133       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1134
1135       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1136     }
1137
1138     // Custom lower several nodes for 256-bit types.
1139     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1140              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1141       MVT VT = (MVT::SimpleValueType)i;
1142
1143       // Extract subvector is special because the value type
1144       // (result) is 128-bit but the source is 256-bit wide.
1145       if (VT.is128BitVector())
1146         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1147
1148       // Do not attempt to custom lower other non-256-bit vectors
1149       if (!VT.is256BitVector())
1150         continue;
1151
1152       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1153       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1154       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1155       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1156       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1157       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1158       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1159     }
1160
1161     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1162     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1163       MVT VT = (MVT::SimpleValueType)i;
1164
1165       // Do not attempt to promote non-256-bit vectors
1166       if (!VT.is256BitVector())
1167         continue;
1168
1169       setOperationAction(ISD::AND,    VT, Promote);
1170       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1171       setOperationAction(ISD::OR,     VT, Promote);
1172       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1173       setOperationAction(ISD::XOR,    VT, Promote);
1174       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1175       setOperationAction(ISD::LOAD,   VT, Promote);
1176       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1177       setOperationAction(ISD::SELECT, VT, Promote);
1178       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1179     }
1180   }
1181
1182   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1183   // of this type with custom code.
1184   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1185            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1186     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1187                        Custom);
1188   }
1189
1190   // We want to custom lower some of our intrinsics.
1191   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1192   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1193
1194
1195   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1196   // handle type legalization for these operations here.
1197   //
1198   // FIXME: We really should do custom legalization for addition and
1199   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1200   // than generic legalization for 64-bit multiplication-with-overflow, though.
1201   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1202     // Add/Sub/Mul with overflow operations are custom lowered.
1203     MVT VT = IntVTs[i];
1204     setOperationAction(ISD::SADDO, VT, Custom);
1205     setOperationAction(ISD::UADDO, VT, Custom);
1206     setOperationAction(ISD::SSUBO, VT, Custom);
1207     setOperationAction(ISD::USUBO, VT, Custom);
1208     setOperationAction(ISD::SMULO, VT, Custom);
1209     setOperationAction(ISD::UMULO, VT, Custom);
1210   }
1211
1212   // There are no 8-bit 3-address imul/mul instructions
1213   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1214   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1215
1216   if (!Subtarget->is64Bit()) {
1217     // These libcalls are not available in 32-bit.
1218     setLibcallName(RTLIB::SHL_I128, 0);
1219     setLibcallName(RTLIB::SRL_I128, 0);
1220     setLibcallName(RTLIB::SRA_I128, 0);
1221   }
1222
1223   // We have target-specific dag combine patterns for the following nodes:
1224   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1225   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1226   setTargetDAGCombine(ISD::VSELECT);
1227   setTargetDAGCombine(ISD::SELECT);
1228   setTargetDAGCombine(ISD::SHL);
1229   setTargetDAGCombine(ISD::SRA);
1230   setTargetDAGCombine(ISD::SRL);
1231   setTargetDAGCombine(ISD::OR);
1232   setTargetDAGCombine(ISD::AND);
1233   setTargetDAGCombine(ISD::ADD);
1234   setTargetDAGCombine(ISD::FADD);
1235   setTargetDAGCombine(ISD::FSUB);
1236   setTargetDAGCombine(ISD::FMA);
1237   setTargetDAGCombine(ISD::SUB);
1238   setTargetDAGCombine(ISD::LOAD);
1239   setTargetDAGCombine(ISD::STORE);
1240   setTargetDAGCombine(ISD::ZERO_EXTEND);
1241   setTargetDAGCombine(ISD::ANY_EXTEND);
1242   setTargetDAGCombine(ISD::SIGN_EXTEND);
1243   setTargetDAGCombine(ISD::TRUNCATE);
1244   setTargetDAGCombine(ISD::UINT_TO_FP);
1245   setTargetDAGCombine(ISD::SINT_TO_FP);
1246   setTargetDAGCombine(ISD::SETCC);
1247   setTargetDAGCombine(ISD::FP_TO_SINT);
1248   if (Subtarget->is64Bit())
1249     setTargetDAGCombine(ISD::MUL);
1250   setTargetDAGCombine(ISD::XOR);
1251
1252   computeRegisterProperties();
1253
1254   // On Darwin, -Os means optimize for size without hurting performance,
1255   // do not reduce the limit.
1256   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1257   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1258   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1259   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1260   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1261   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1262   setPrefLoopAlignment(4); // 2^4 bytes.
1263   benefitFromCodePlacementOpt = true;
1264
1265   // Predictable cmov don't hurt on atom because it's in-order.
1266   predictableSelectIsExpensive = !Subtarget->isAtom();
1267
1268   setPrefFunctionAlignment(4); // 2^4 bytes.
1269 }
1270
1271
1272 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1273   if (!VT.isVector()) return MVT::i8;
1274   return VT.changeVectorElementTypeToInteger();
1275 }
1276
1277
1278 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1279 /// the desired ByVal argument alignment.
1280 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1281   if (MaxAlign == 16)
1282     return;
1283   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1284     if (VTy->getBitWidth() == 128)
1285       MaxAlign = 16;
1286   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1287     unsigned EltAlign = 0;
1288     getMaxByValAlign(ATy->getElementType(), EltAlign);
1289     if (EltAlign > MaxAlign)
1290       MaxAlign = EltAlign;
1291   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1292     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1293       unsigned EltAlign = 0;
1294       getMaxByValAlign(STy->getElementType(i), EltAlign);
1295       if (EltAlign > MaxAlign)
1296         MaxAlign = EltAlign;
1297       if (MaxAlign == 16)
1298         break;
1299     }
1300   }
1301 }
1302
1303 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1304 /// function arguments in the caller parameter area. For X86, aggregates
1305 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1306 /// are at 4-byte boundaries.
1307 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1308   if (Subtarget->is64Bit()) {
1309     // Max of 8 and alignment of type.
1310     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1311     if (TyAlign > 8)
1312       return TyAlign;
1313     return 8;
1314   }
1315
1316   unsigned Align = 4;
1317   if (Subtarget->hasSSE1())
1318     getMaxByValAlign(Ty, Align);
1319   return Align;
1320 }
1321
1322 /// getOptimalMemOpType - Returns the target specific optimal type for load
1323 /// and store operations as a result of memset, memcpy, and memmove
1324 /// lowering. If DstAlign is zero that means it's safe to destination
1325 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1326 /// means there isn't a need to check it against alignment requirement,
1327 /// probably because the source does not need to be loaded. If
1328 /// 'IsZeroVal' is true, that means it's safe to return a
1329 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1330 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1331 /// constant so it does not need to be loaded.
1332 /// It returns EVT::Other if the type should be determined using generic
1333 /// target-independent logic.
1334 EVT
1335 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1336                                        unsigned DstAlign, unsigned SrcAlign,
1337                                        bool IsZeroVal,
1338                                        bool MemcpyStrSrc,
1339                                        MachineFunction &MF) const {
1340   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1341   // linux.  This is because the stack realignment code can't handle certain
1342   // cases like PR2962.  This should be removed when PR2962 is fixed.
1343   const Function *F = MF.getFunction();
1344   if (IsZeroVal &&
1345       !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1346     if (Size >= 16 &&
1347         (Subtarget->isUnalignedMemAccessFast() ||
1348          ((DstAlign == 0 || DstAlign >= 16) &&
1349           (SrcAlign == 0 || SrcAlign >= 16))) &&
1350         Subtarget->getStackAlignment() >= 16) {
1351       if (Subtarget->getStackAlignment() >= 32) {
1352         if (Subtarget->hasAVX2())
1353           return MVT::v8i32;
1354         if (Subtarget->hasAVX())
1355           return MVT::v8f32;
1356       }
1357       if (Subtarget->hasSSE2())
1358         return MVT::v4i32;
1359       if (Subtarget->hasSSE1())
1360         return MVT::v4f32;
1361     } else if (!MemcpyStrSrc && Size >= 8 &&
1362                !Subtarget->is64Bit() &&
1363                Subtarget->getStackAlignment() >= 8 &&
1364                Subtarget->hasSSE2()) {
1365       // Do not use f64 to lower memcpy if source is string constant. It's
1366       // better to use i32 to avoid the loads.
1367       return MVT::f64;
1368     }
1369   }
1370   if (Subtarget->is64Bit() && Size >= 8)
1371     return MVT::i64;
1372   return MVT::i32;
1373 }
1374
1375 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1376 /// current function.  The returned value is a member of the
1377 /// MachineJumpTableInfo::JTEntryKind enum.
1378 unsigned X86TargetLowering::getJumpTableEncoding() const {
1379   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1380   // symbol.
1381   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1382       Subtarget->isPICStyleGOT())
1383     return MachineJumpTableInfo::EK_Custom32;
1384
1385   // Otherwise, use the normal jump table encoding heuristics.
1386   return TargetLowering::getJumpTableEncoding();
1387 }
1388
1389 const MCExpr *
1390 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1391                                              const MachineBasicBlock *MBB,
1392                                              unsigned uid,MCContext &Ctx) const{
1393   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1394          Subtarget->isPICStyleGOT());
1395   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1396   // entries.
1397   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1398                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1399 }
1400
1401 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1402 /// jumptable.
1403 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1404                                                     SelectionDAG &DAG) const {
1405   if (!Subtarget->is64Bit())
1406     // This doesn't have DebugLoc associated with it, but is not really the
1407     // same as a Register.
1408     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1409   return Table;
1410 }
1411
1412 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1413 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1414 /// MCExpr.
1415 const MCExpr *X86TargetLowering::
1416 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1417                              MCContext &Ctx) const {
1418   // X86-64 uses RIP relative addressing based on the jump table label.
1419   if (Subtarget->isPICStyleRIPRel())
1420     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1421
1422   // Otherwise, the reference is relative to the PIC base.
1423   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1424 }
1425
1426 // FIXME: Why this routine is here? Move to RegInfo!
1427 std::pair<const TargetRegisterClass*, uint8_t>
1428 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1429   const TargetRegisterClass *RRC = 0;
1430   uint8_t Cost = 1;
1431   switch (VT.getSimpleVT().SimpleTy) {
1432   default:
1433     return TargetLowering::findRepresentativeClass(VT);
1434   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1435     RRC = Subtarget->is64Bit() ?
1436       (const TargetRegisterClass*)&X86::GR64RegClass :
1437       (const TargetRegisterClass*)&X86::GR32RegClass;
1438     break;
1439   case MVT::x86mmx:
1440     RRC = &X86::VR64RegClass;
1441     break;
1442   case MVT::f32: case MVT::f64:
1443   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1444   case MVT::v4f32: case MVT::v2f64:
1445   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1446   case MVT::v4f64:
1447     RRC = &X86::VR128RegClass;
1448     break;
1449   }
1450   return std::make_pair(RRC, Cost);
1451 }
1452
1453 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1454                                                unsigned &Offset) const {
1455   if (!Subtarget->isTargetLinux())
1456     return false;
1457
1458   if (Subtarget->is64Bit()) {
1459     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1460     Offset = 0x28;
1461     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1462       AddressSpace = 256;
1463     else
1464       AddressSpace = 257;
1465   } else {
1466     // %gs:0x14 on i386
1467     Offset = 0x14;
1468     AddressSpace = 256;
1469   }
1470   return true;
1471 }
1472
1473
1474 //===----------------------------------------------------------------------===//
1475 //               Return Value Calling Convention Implementation
1476 //===----------------------------------------------------------------------===//
1477
1478 #include "X86GenCallingConv.inc"
1479
1480 bool
1481 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1482                                   MachineFunction &MF, bool isVarArg,
1483                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1484                         LLVMContext &Context) const {
1485   SmallVector<CCValAssign, 16> RVLocs;
1486   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1487                  RVLocs, Context);
1488   return CCInfo.CheckReturn(Outs, RetCC_X86);
1489 }
1490
1491 SDValue
1492 X86TargetLowering::LowerReturn(SDValue Chain,
1493                                CallingConv::ID CallConv, bool isVarArg,
1494                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1495                                const SmallVectorImpl<SDValue> &OutVals,
1496                                DebugLoc dl, SelectionDAG &DAG) const {
1497   MachineFunction &MF = DAG.getMachineFunction();
1498   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1499
1500   SmallVector<CCValAssign, 16> RVLocs;
1501   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1502                  RVLocs, *DAG.getContext());
1503   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1504
1505   // Add the regs to the liveout set for the function.
1506   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1507   for (unsigned i = 0; i != RVLocs.size(); ++i)
1508     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1509       MRI.addLiveOut(RVLocs[i].getLocReg());
1510
1511   SDValue Flag;
1512
1513   SmallVector<SDValue, 6> RetOps;
1514   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1515   // Operand #1 = Bytes To Pop
1516   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1517                    MVT::i16));
1518
1519   // Copy the result values into the output registers.
1520   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1521     CCValAssign &VA = RVLocs[i];
1522     assert(VA.isRegLoc() && "Can only return in registers!");
1523     SDValue ValToCopy = OutVals[i];
1524     EVT ValVT = ValToCopy.getValueType();
1525
1526     // Promote values to the appropriate types
1527     if (VA.getLocInfo() == CCValAssign::SExt)
1528       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1529     else if (VA.getLocInfo() == CCValAssign::ZExt)
1530       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1531     else if (VA.getLocInfo() == CCValAssign::AExt)
1532       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1533     else if (VA.getLocInfo() == CCValAssign::BCvt)
1534       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1535
1536     // If this is x86-64, and we disabled SSE, we can't return FP values,
1537     // or SSE or MMX vectors.
1538     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1539          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1540           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1541       report_fatal_error("SSE register return with SSE disabled");
1542     }
1543     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1544     // llvm-gcc has never done it right and no one has noticed, so this
1545     // should be OK for now.
1546     if (ValVT == MVT::f64 &&
1547         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1548       report_fatal_error("SSE2 register return with SSE2 disabled");
1549
1550     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1551     // the RET instruction and handled by the FP Stackifier.
1552     if (VA.getLocReg() == X86::ST0 ||
1553         VA.getLocReg() == X86::ST1) {
1554       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1555       // change the value to the FP stack register class.
1556       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1557         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1558       RetOps.push_back(ValToCopy);
1559       // Don't emit a copytoreg.
1560       continue;
1561     }
1562
1563     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1564     // which is returned in RAX / RDX.
1565     if (Subtarget->is64Bit()) {
1566       if (ValVT == MVT::x86mmx) {
1567         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1568           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1569           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1570                                   ValToCopy);
1571           // If we don't have SSE2 available, convert to v4f32 so the generated
1572           // register is legal.
1573           if (!Subtarget->hasSSE2())
1574             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1575         }
1576       }
1577     }
1578
1579     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1580     Flag = Chain.getValue(1);
1581   }
1582
1583   // The x86-64 ABI for returning structs by value requires that we copy
1584   // the sret argument into %rax for the return. We saved the argument into
1585   // a virtual register in the entry block, so now we copy the value out
1586   // and into %rax.
1587   if (Subtarget->is64Bit() &&
1588       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1589     MachineFunction &MF = DAG.getMachineFunction();
1590     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1591     unsigned Reg = FuncInfo->getSRetReturnReg();
1592     assert(Reg &&
1593            "SRetReturnReg should have been set in LowerFormalArguments().");
1594     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1595
1596     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1597     Flag = Chain.getValue(1);
1598
1599     // RAX now acts like a return value.
1600     MRI.addLiveOut(X86::RAX);
1601   }
1602
1603   RetOps[0] = Chain;  // Update chain.
1604
1605   // Add the flag if we have it.
1606   if (Flag.getNode())
1607     RetOps.push_back(Flag);
1608
1609   return DAG.getNode(X86ISD::RET_FLAG, dl,
1610                      MVT::Other, &RetOps[0], RetOps.size());
1611 }
1612
1613 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1614   if (N->getNumValues() != 1)
1615     return false;
1616   if (!N->hasNUsesOfValue(1, 0))
1617     return false;
1618
1619   SDValue TCChain = Chain;
1620   SDNode *Copy = *N->use_begin();
1621   if (Copy->getOpcode() == ISD::CopyToReg) {
1622     // If the copy has a glue operand, we conservatively assume it isn't safe to
1623     // perform a tail call.
1624     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1625       return false;
1626     TCChain = Copy->getOperand(0);
1627   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1628     return false;
1629
1630   bool HasRet = false;
1631   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1632        UI != UE; ++UI) {
1633     if (UI->getOpcode() != X86ISD::RET_FLAG)
1634       return false;
1635     HasRet = true;
1636   }
1637
1638   if (!HasRet)
1639     return false;
1640
1641   Chain = TCChain;
1642   return true;
1643 }
1644
1645 EVT
1646 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1647                                             ISD::NodeType ExtendKind) const {
1648   MVT ReturnMVT;
1649   // TODO: Is this also valid on 32-bit?
1650   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1651     ReturnMVT = MVT::i8;
1652   else
1653     ReturnMVT = MVT::i32;
1654
1655   EVT MinVT = getRegisterType(Context, ReturnMVT);
1656   return VT.bitsLT(MinVT) ? MinVT : VT;
1657 }
1658
1659 /// LowerCallResult - Lower the result values of a call into the
1660 /// appropriate copies out of appropriate physical registers.
1661 ///
1662 SDValue
1663 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1664                                    CallingConv::ID CallConv, bool isVarArg,
1665                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1666                                    DebugLoc dl, SelectionDAG &DAG,
1667                                    SmallVectorImpl<SDValue> &InVals) const {
1668
1669   // Assign locations to each value returned by this call.
1670   SmallVector<CCValAssign, 16> RVLocs;
1671   bool Is64Bit = Subtarget->is64Bit();
1672   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1673                  getTargetMachine(), RVLocs, *DAG.getContext());
1674   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1675
1676   // Copy all of the result registers out of their specified physreg.
1677   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1678     CCValAssign &VA = RVLocs[i];
1679     EVT CopyVT = VA.getValVT();
1680
1681     // If this is x86-64, and we disabled SSE, we can't return FP values
1682     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1683         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1684       report_fatal_error("SSE register return with SSE disabled");
1685     }
1686
1687     SDValue Val;
1688
1689     // If this is a call to a function that returns an fp value on the floating
1690     // point stack, we must guarantee the value is popped from the stack, so
1691     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1692     // if the return value is not used. We use the FpPOP_RETVAL instruction
1693     // instead.
1694     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1695       // If we prefer to use the value in xmm registers, copy it out as f80 and
1696       // use a truncate to move it from fp stack reg to xmm reg.
1697       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1698       SDValue Ops[] = { Chain, InFlag };
1699       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1700                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1701       Val = Chain.getValue(0);
1702
1703       // Round the f80 to the right size, which also moves it to the appropriate
1704       // xmm register.
1705       if (CopyVT != VA.getValVT())
1706         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1707                           // This truncation won't change the value.
1708                           DAG.getIntPtrConstant(1));
1709     } else {
1710       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1711                                  CopyVT, InFlag).getValue(1);
1712       Val = Chain.getValue(0);
1713     }
1714     InFlag = Chain.getValue(2);
1715     InVals.push_back(Val);
1716   }
1717
1718   return Chain;
1719 }
1720
1721
1722 //===----------------------------------------------------------------------===//
1723 //                C & StdCall & Fast Calling Convention implementation
1724 //===----------------------------------------------------------------------===//
1725 //  StdCall calling convention seems to be standard for many Windows' API
1726 //  routines and around. It differs from C calling convention just a little:
1727 //  callee should clean up the stack, not caller. Symbols should be also
1728 //  decorated in some fancy way :) It doesn't support any vector arguments.
1729 //  For info on fast calling convention see Fast Calling Convention (tail call)
1730 //  implementation LowerX86_32FastCCCallTo.
1731
1732 /// CallIsStructReturn - Determines whether a call uses struct return
1733 /// semantics.
1734 enum StructReturnType {
1735   NotStructReturn,
1736   RegStructReturn,
1737   StackStructReturn
1738 };
1739 static StructReturnType
1740 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1741   if (Outs.empty())
1742     return NotStructReturn;
1743
1744   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1745   if (!Flags.isSRet())
1746     return NotStructReturn;
1747   if (Flags.isInReg())
1748     return RegStructReturn;
1749   return StackStructReturn;
1750 }
1751
1752 /// ArgsAreStructReturn - Determines whether a function uses struct
1753 /// return semantics.
1754 static StructReturnType
1755 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1756   if (Ins.empty())
1757     return NotStructReturn;
1758
1759   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1760   if (!Flags.isSRet())
1761     return NotStructReturn;
1762   if (Flags.isInReg())
1763     return RegStructReturn;
1764   return StackStructReturn;
1765 }
1766
1767 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1768 /// by "Src" to address "Dst" with size and alignment information specified by
1769 /// the specific parameter attribute. The copy will be passed as a byval
1770 /// function parameter.
1771 static SDValue
1772 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1773                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1774                           DebugLoc dl) {
1775   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1776
1777   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1778                        /*isVolatile*/false, /*AlwaysInline=*/true,
1779                        MachinePointerInfo(), MachinePointerInfo());
1780 }
1781
1782 /// IsTailCallConvention - Return true if the calling convention is one that
1783 /// supports tail call optimization.
1784 static bool IsTailCallConvention(CallingConv::ID CC) {
1785   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1786 }
1787
1788 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1789   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1790     return false;
1791
1792   CallSite CS(CI);
1793   CallingConv::ID CalleeCC = CS.getCallingConv();
1794   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1795     return false;
1796
1797   return true;
1798 }
1799
1800 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1801 /// a tailcall target by changing its ABI.
1802 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1803                                    bool GuaranteedTailCallOpt) {
1804   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1805 }
1806
1807 SDValue
1808 X86TargetLowering::LowerMemArgument(SDValue Chain,
1809                                     CallingConv::ID CallConv,
1810                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1811                                     DebugLoc dl, SelectionDAG &DAG,
1812                                     const CCValAssign &VA,
1813                                     MachineFrameInfo *MFI,
1814                                     unsigned i) const {
1815   // Create the nodes corresponding to a load from this parameter slot.
1816   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1817   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1818                               getTargetMachine().Options.GuaranteedTailCallOpt);
1819   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1820   EVT ValVT;
1821
1822   // If value is passed by pointer we have address passed instead of the value
1823   // itself.
1824   if (VA.getLocInfo() == CCValAssign::Indirect)
1825     ValVT = VA.getLocVT();
1826   else
1827     ValVT = VA.getValVT();
1828
1829   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1830   // changed with more analysis.
1831   // In case of tail call optimization mark all arguments mutable. Since they
1832   // could be overwritten by lowering of arguments in case of a tail call.
1833   if (Flags.isByVal()) {
1834     unsigned Bytes = Flags.getByValSize();
1835     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1836     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1837     return DAG.getFrameIndex(FI, getPointerTy());
1838   } else {
1839     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1840                                     VA.getLocMemOffset(), isImmutable);
1841     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1842     return DAG.getLoad(ValVT, dl, Chain, FIN,
1843                        MachinePointerInfo::getFixedStack(FI),
1844                        false, false, false, 0);
1845   }
1846 }
1847
1848 SDValue
1849 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1850                                         CallingConv::ID CallConv,
1851                                         bool isVarArg,
1852                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1853                                         DebugLoc dl,
1854                                         SelectionDAG &DAG,
1855                                         SmallVectorImpl<SDValue> &InVals)
1856                                           const {
1857   MachineFunction &MF = DAG.getMachineFunction();
1858   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1859
1860   const Function* Fn = MF.getFunction();
1861   if (Fn->hasExternalLinkage() &&
1862       Subtarget->isTargetCygMing() &&
1863       Fn->getName() == "main")
1864     FuncInfo->setForceFramePointer(true);
1865
1866   MachineFrameInfo *MFI = MF.getFrameInfo();
1867   bool Is64Bit = Subtarget->is64Bit();
1868   bool IsWindows = Subtarget->isTargetWindows();
1869   bool IsWin64 = Subtarget->isTargetWin64();
1870
1871   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1872          "Var args not supported with calling convention fastcc or ghc");
1873
1874   // Assign locations to all of the incoming arguments.
1875   SmallVector<CCValAssign, 16> ArgLocs;
1876   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1877                  ArgLocs, *DAG.getContext());
1878
1879   // Allocate shadow area for Win64
1880   if (IsWin64) {
1881     CCInfo.AllocateStack(32, 8);
1882   }
1883
1884   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1885
1886   unsigned LastVal = ~0U;
1887   SDValue ArgValue;
1888   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1889     CCValAssign &VA = ArgLocs[i];
1890     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1891     // places.
1892     assert(VA.getValNo() != LastVal &&
1893            "Don't support value assigned to multiple locs yet");
1894     (void)LastVal;
1895     LastVal = VA.getValNo();
1896
1897     if (VA.isRegLoc()) {
1898       EVT RegVT = VA.getLocVT();
1899       const TargetRegisterClass *RC;
1900       if (RegVT == MVT::i32)
1901         RC = &X86::GR32RegClass;
1902       else if (Is64Bit && RegVT == MVT::i64)
1903         RC = &X86::GR64RegClass;
1904       else if (RegVT == MVT::f32)
1905         RC = &X86::FR32RegClass;
1906       else if (RegVT == MVT::f64)
1907         RC = &X86::FR64RegClass;
1908       else if (RegVT.is256BitVector())
1909         RC = &X86::VR256RegClass;
1910       else if (RegVT.is128BitVector())
1911         RC = &X86::VR128RegClass;
1912       else if (RegVT == MVT::x86mmx)
1913         RC = &X86::VR64RegClass;
1914       else
1915         llvm_unreachable("Unknown argument type!");
1916
1917       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1918       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1919
1920       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1921       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1922       // right size.
1923       if (VA.getLocInfo() == CCValAssign::SExt)
1924         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1925                                DAG.getValueType(VA.getValVT()));
1926       else if (VA.getLocInfo() == CCValAssign::ZExt)
1927         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1928                                DAG.getValueType(VA.getValVT()));
1929       else if (VA.getLocInfo() == CCValAssign::BCvt)
1930         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1931
1932       if (VA.isExtInLoc()) {
1933         // Handle MMX values passed in XMM regs.
1934         if (RegVT.isVector()) {
1935           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1936                                  ArgValue);
1937         } else
1938           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1939       }
1940     } else {
1941       assert(VA.isMemLoc());
1942       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1943     }
1944
1945     // If value is passed via pointer - do a load.
1946     if (VA.getLocInfo() == CCValAssign::Indirect)
1947       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1948                              MachinePointerInfo(), false, false, false, 0);
1949
1950     InVals.push_back(ArgValue);
1951   }
1952
1953   // The x86-64 ABI for returning structs by value requires that we copy
1954   // the sret argument into %rax for the return. Save the argument into
1955   // a virtual register so that we can access it from the return points.
1956   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1957     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1958     unsigned Reg = FuncInfo->getSRetReturnReg();
1959     if (!Reg) {
1960       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1961       FuncInfo->setSRetReturnReg(Reg);
1962     }
1963     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1964     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1965   }
1966
1967   unsigned StackSize = CCInfo.getNextStackOffset();
1968   // Align stack specially for tail calls.
1969   if (FuncIsMadeTailCallSafe(CallConv,
1970                              MF.getTarget().Options.GuaranteedTailCallOpt))
1971     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1972
1973   // If the function takes variable number of arguments, make a frame index for
1974   // the start of the first vararg value... for expansion of llvm.va_start.
1975   if (isVarArg) {
1976     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1977                     CallConv != CallingConv::X86_ThisCall)) {
1978       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1979     }
1980     if (Is64Bit) {
1981       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1982
1983       // FIXME: We should really autogenerate these arrays
1984       static const uint16_t GPR64ArgRegsWin64[] = {
1985         X86::RCX, X86::RDX, X86::R8,  X86::R9
1986       };
1987       static const uint16_t GPR64ArgRegs64Bit[] = {
1988         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1989       };
1990       static const uint16_t XMMArgRegs64Bit[] = {
1991         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1992         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1993       };
1994       const uint16_t *GPR64ArgRegs;
1995       unsigned NumXMMRegs = 0;
1996
1997       if (IsWin64) {
1998         // The XMM registers which might contain var arg parameters are shadowed
1999         // in their paired GPR.  So we only need to save the GPR to their home
2000         // slots.
2001         TotalNumIntRegs = 4;
2002         GPR64ArgRegs = GPR64ArgRegsWin64;
2003       } else {
2004         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2005         GPR64ArgRegs = GPR64ArgRegs64Bit;
2006
2007         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2008                                                 TotalNumXMMRegs);
2009       }
2010       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2011                                                        TotalNumIntRegs);
2012
2013       bool NoImplicitFloatOps = Fn->getFnAttributes().
2014         hasAttribute(Attributes::NoImplicitFloat);
2015       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2016              "SSE register cannot be used when SSE is disabled!");
2017       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2018                NoImplicitFloatOps) &&
2019              "SSE register cannot be used when SSE is disabled!");
2020       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2021           !Subtarget->hasSSE1())
2022         // Kernel mode asks for SSE to be disabled, so don't push them
2023         // on the stack.
2024         TotalNumXMMRegs = 0;
2025
2026       if (IsWin64) {
2027         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2028         // Get to the caller-allocated home save location.  Add 8 to account
2029         // for the return address.
2030         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2031         FuncInfo->setRegSaveFrameIndex(
2032           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2033         // Fixup to set vararg frame on shadow area (4 x i64).
2034         if (NumIntRegs < 4)
2035           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2036       } else {
2037         // For X86-64, if there are vararg parameters that are passed via
2038         // registers, then we must store them to their spots on the stack so
2039         // they may be loaded by deferencing the result of va_next.
2040         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2041         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2042         FuncInfo->setRegSaveFrameIndex(
2043           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2044                                false));
2045       }
2046
2047       // Store the integer parameter registers.
2048       SmallVector<SDValue, 8> MemOps;
2049       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2050                                         getPointerTy());
2051       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2052       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2053         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2054                                   DAG.getIntPtrConstant(Offset));
2055         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2056                                      &X86::GR64RegClass);
2057         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2058         SDValue Store =
2059           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2060                        MachinePointerInfo::getFixedStack(
2061                          FuncInfo->getRegSaveFrameIndex(), Offset),
2062                        false, false, 0);
2063         MemOps.push_back(Store);
2064         Offset += 8;
2065       }
2066
2067       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2068         // Now store the XMM (fp + vector) parameter registers.
2069         SmallVector<SDValue, 11> SaveXMMOps;
2070         SaveXMMOps.push_back(Chain);
2071
2072         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2073         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2074         SaveXMMOps.push_back(ALVal);
2075
2076         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2077                                FuncInfo->getRegSaveFrameIndex()));
2078         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2079                                FuncInfo->getVarArgsFPOffset()));
2080
2081         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2082           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2083                                        &X86::VR128RegClass);
2084           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2085           SaveXMMOps.push_back(Val);
2086         }
2087         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2088                                      MVT::Other,
2089                                      &SaveXMMOps[0], SaveXMMOps.size()));
2090       }
2091
2092       if (!MemOps.empty())
2093         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2094                             &MemOps[0], MemOps.size());
2095     }
2096   }
2097
2098   // Some CCs need callee pop.
2099   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2100                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2101     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2102   } else {
2103     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2104     // If this is an sret function, the return should pop the hidden pointer.
2105     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2106         argsAreStructReturn(Ins) == StackStructReturn)
2107       FuncInfo->setBytesToPopOnReturn(4);
2108   }
2109
2110   if (!Is64Bit) {
2111     // RegSaveFrameIndex is X86-64 only.
2112     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2113     if (CallConv == CallingConv::X86_FastCall ||
2114         CallConv == CallingConv::X86_ThisCall)
2115       // fastcc functions can't have varargs.
2116       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2117   }
2118
2119   FuncInfo->setArgumentStackSize(StackSize);
2120
2121   return Chain;
2122 }
2123
2124 SDValue
2125 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2126                                     SDValue StackPtr, SDValue Arg,
2127                                     DebugLoc dl, SelectionDAG &DAG,
2128                                     const CCValAssign &VA,
2129                                     ISD::ArgFlagsTy Flags) const {
2130   unsigned LocMemOffset = VA.getLocMemOffset();
2131   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2132   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2133   if (Flags.isByVal())
2134     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2135
2136   return DAG.getStore(Chain, dl, Arg, PtrOff,
2137                       MachinePointerInfo::getStack(LocMemOffset),
2138                       false, false, 0);
2139 }
2140
2141 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2142 /// optimization is performed and it is required.
2143 SDValue
2144 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2145                                            SDValue &OutRetAddr, SDValue Chain,
2146                                            bool IsTailCall, bool Is64Bit,
2147                                            int FPDiff, DebugLoc dl) const {
2148   // Adjust the Return address stack slot.
2149   EVT VT = getPointerTy();
2150   OutRetAddr = getReturnAddressFrameIndex(DAG);
2151
2152   // Load the "old" Return address.
2153   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2154                            false, false, false, 0);
2155   return SDValue(OutRetAddr.getNode(), 1);
2156 }
2157
2158 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2159 /// optimization is performed and it is required (FPDiff!=0).
2160 static SDValue
2161 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2162                          SDValue Chain, SDValue RetAddrFrIdx,
2163                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2164   // Store the return address to the appropriate stack slot.
2165   if (!FPDiff) return Chain;
2166   // Calculate the new stack slot for the return address.
2167   int SlotSize = Is64Bit ? 8 : 4;
2168   int NewReturnAddrFI =
2169     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2170   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2171   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2172   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2173                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2174                        false, false, 0);
2175   return Chain;
2176 }
2177
2178 SDValue
2179 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2180                              SmallVectorImpl<SDValue> &InVals) const {
2181   SelectionDAG &DAG                     = CLI.DAG;
2182   DebugLoc &dl                          = CLI.DL;
2183   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2184   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2185   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2186   SDValue Chain                         = CLI.Chain;
2187   SDValue Callee                        = CLI.Callee;
2188   CallingConv::ID CallConv              = CLI.CallConv;
2189   bool &isTailCall                      = CLI.IsTailCall;
2190   bool isVarArg                         = CLI.IsVarArg;
2191
2192   MachineFunction &MF = DAG.getMachineFunction();
2193   bool Is64Bit        = Subtarget->is64Bit();
2194   bool IsWin64        = Subtarget->isTargetWin64();
2195   bool IsWindows      = Subtarget->isTargetWindows();
2196   StructReturnType SR = callIsStructReturn(Outs);
2197   bool IsSibcall      = false;
2198
2199   if (MF.getTarget().Options.DisableTailCalls)
2200     isTailCall = false;
2201
2202   if (isTailCall) {
2203     // Check if it's really possible to do a tail call.
2204     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2205                     isVarArg, SR != NotStructReturn,
2206                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2207                     Outs, OutVals, Ins, DAG);
2208
2209     // Sibcalls are automatically detected tailcalls which do not require
2210     // ABI changes.
2211     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2212       IsSibcall = true;
2213
2214     if (isTailCall)
2215       ++NumTailCalls;
2216   }
2217
2218   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2219          "Var args not supported with calling convention fastcc or ghc");
2220
2221   // Analyze operands of the call, assigning locations to each operand.
2222   SmallVector<CCValAssign, 16> ArgLocs;
2223   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2224                  ArgLocs, *DAG.getContext());
2225
2226   // Allocate shadow area for Win64
2227   if (IsWin64) {
2228     CCInfo.AllocateStack(32, 8);
2229   }
2230
2231   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2232
2233   // Get a count of how many bytes are to be pushed on the stack.
2234   unsigned NumBytes = CCInfo.getNextStackOffset();
2235   if (IsSibcall)
2236     // This is a sibcall. The memory operands are available in caller's
2237     // own caller's stack.
2238     NumBytes = 0;
2239   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2240            IsTailCallConvention(CallConv))
2241     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2242
2243   int FPDiff = 0;
2244   if (isTailCall && !IsSibcall) {
2245     // Lower arguments at fp - stackoffset + fpdiff.
2246     unsigned NumBytesCallerPushed =
2247       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2248     FPDiff = NumBytesCallerPushed - NumBytes;
2249
2250     // Set the delta of movement of the returnaddr stackslot.
2251     // But only set if delta is greater than previous delta.
2252     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2253       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2254   }
2255
2256   if (!IsSibcall)
2257     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2258
2259   SDValue RetAddrFrIdx;
2260   // Load return address for tail calls.
2261   if (isTailCall && FPDiff)
2262     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2263                                     Is64Bit, FPDiff, dl);
2264
2265   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2266   SmallVector<SDValue, 8> MemOpChains;
2267   SDValue StackPtr;
2268
2269   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2270   // of tail call optimization arguments are handle later.
2271   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2272     CCValAssign &VA = ArgLocs[i];
2273     EVT RegVT = VA.getLocVT();
2274     SDValue Arg = OutVals[i];
2275     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2276     bool isByVal = Flags.isByVal();
2277
2278     // Promote the value if needed.
2279     switch (VA.getLocInfo()) {
2280     default: llvm_unreachable("Unknown loc info!");
2281     case CCValAssign::Full: break;
2282     case CCValAssign::SExt:
2283       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2284       break;
2285     case CCValAssign::ZExt:
2286       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2287       break;
2288     case CCValAssign::AExt:
2289       if (RegVT.is128BitVector()) {
2290         // Special case: passing MMX values in XMM registers.
2291         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2292         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2293         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2294       } else
2295         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2296       break;
2297     case CCValAssign::BCvt:
2298       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2299       break;
2300     case CCValAssign::Indirect: {
2301       // Store the argument.
2302       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2303       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2304       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2305                            MachinePointerInfo::getFixedStack(FI),
2306                            false, false, 0);
2307       Arg = SpillSlot;
2308       break;
2309     }
2310     }
2311
2312     if (VA.isRegLoc()) {
2313       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2314       if (isVarArg && IsWin64) {
2315         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2316         // shadow reg if callee is a varargs function.
2317         unsigned ShadowReg = 0;
2318         switch (VA.getLocReg()) {
2319         case X86::XMM0: ShadowReg = X86::RCX; break;
2320         case X86::XMM1: ShadowReg = X86::RDX; break;
2321         case X86::XMM2: ShadowReg = X86::R8; break;
2322         case X86::XMM3: ShadowReg = X86::R9; break;
2323         }
2324         if (ShadowReg)
2325           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2326       }
2327     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2328       assert(VA.isMemLoc());
2329       if (StackPtr.getNode() == 0)
2330         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2331       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2332                                              dl, DAG, VA, Flags));
2333     }
2334   }
2335
2336   if (!MemOpChains.empty())
2337     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2338                         &MemOpChains[0], MemOpChains.size());
2339
2340   if (Subtarget->isPICStyleGOT()) {
2341     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2342     // GOT pointer.
2343     if (!isTailCall) {
2344       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2345                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2346     } else {
2347       // If we are tail calling and generating PIC/GOT style code load the
2348       // address of the callee into ECX. The value in ecx is used as target of
2349       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2350       // for tail calls on PIC/GOT architectures. Normally we would just put the
2351       // address of GOT into ebx and then call target@PLT. But for tail calls
2352       // ebx would be restored (since ebx is callee saved) before jumping to the
2353       // target@PLT.
2354
2355       // Note: The actual moving to ECX is done further down.
2356       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2357       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2358           !G->getGlobal()->hasProtectedVisibility())
2359         Callee = LowerGlobalAddress(Callee, DAG);
2360       else if (isa<ExternalSymbolSDNode>(Callee))
2361         Callee = LowerExternalSymbol(Callee, DAG);
2362     }
2363   }
2364
2365   if (Is64Bit && isVarArg && !IsWin64) {
2366     // From AMD64 ABI document:
2367     // For calls that may call functions that use varargs or stdargs
2368     // (prototype-less calls or calls to functions containing ellipsis (...) in
2369     // the declaration) %al is used as hidden argument to specify the number
2370     // of SSE registers used. The contents of %al do not need to match exactly
2371     // the number of registers, but must be an ubound on the number of SSE
2372     // registers used and is in the range 0 - 8 inclusive.
2373
2374     // Count the number of XMM registers allocated.
2375     static const uint16_t XMMArgRegs[] = {
2376       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2377       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2378     };
2379     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2380     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2381            && "SSE registers cannot be used when SSE is disabled");
2382
2383     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2384                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2385   }
2386
2387   // For tail calls lower the arguments to the 'real' stack slot.
2388   if (isTailCall) {
2389     // Force all the incoming stack arguments to be loaded from the stack
2390     // before any new outgoing arguments are stored to the stack, because the
2391     // outgoing stack slots may alias the incoming argument stack slots, and
2392     // the alias isn't otherwise explicit. This is slightly more conservative
2393     // than necessary, because it means that each store effectively depends
2394     // on every argument instead of just those arguments it would clobber.
2395     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2396
2397     SmallVector<SDValue, 8> MemOpChains2;
2398     SDValue FIN;
2399     int FI = 0;
2400     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2401       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2402         CCValAssign &VA = ArgLocs[i];
2403         if (VA.isRegLoc())
2404           continue;
2405         assert(VA.isMemLoc());
2406         SDValue Arg = OutVals[i];
2407         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2408         // Create frame index.
2409         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2410         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2411         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2412         FIN = DAG.getFrameIndex(FI, getPointerTy());
2413
2414         if (Flags.isByVal()) {
2415           // Copy relative to framepointer.
2416           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2417           if (StackPtr.getNode() == 0)
2418             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2419                                           getPointerTy());
2420           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2421
2422           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2423                                                            ArgChain,
2424                                                            Flags, DAG, dl));
2425         } else {
2426           // Store relative to framepointer.
2427           MemOpChains2.push_back(
2428             DAG.getStore(ArgChain, dl, Arg, FIN,
2429                          MachinePointerInfo::getFixedStack(FI),
2430                          false, false, 0));
2431         }
2432       }
2433     }
2434
2435     if (!MemOpChains2.empty())
2436       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2437                           &MemOpChains2[0], MemOpChains2.size());
2438
2439     // Store the return address to the appropriate stack slot.
2440     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2441                                      FPDiff, dl);
2442   }
2443
2444   // Build a sequence of copy-to-reg nodes chained together with token chain
2445   // and flag operands which copy the outgoing args into registers.
2446   SDValue InFlag;
2447   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2448     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2449                              RegsToPass[i].second, InFlag);
2450     InFlag = Chain.getValue(1);
2451   }
2452
2453   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2454     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2455     // In the 64-bit large code model, we have to make all calls
2456     // through a register, since the call instruction's 32-bit
2457     // pc-relative offset may not be large enough to hold the whole
2458     // address.
2459   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2460     // If the callee is a GlobalAddress node (quite common, every direct call
2461     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2462     // it.
2463
2464     // We should use extra load for direct calls to dllimported functions in
2465     // non-JIT mode.
2466     const GlobalValue *GV = G->getGlobal();
2467     if (!GV->hasDLLImportLinkage()) {
2468       unsigned char OpFlags = 0;
2469       bool ExtraLoad = false;
2470       unsigned WrapperKind = ISD::DELETED_NODE;
2471
2472       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2473       // external symbols most go through the PLT in PIC mode.  If the symbol
2474       // has hidden or protected visibility, or if it is static or local, then
2475       // we don't need to use the PLT - we can directly call it.
2476       if (Subtarget->isTargetELF() &&
2477           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2478           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2479         OpFlags = X86II::MO_PLT;
2480       } else if (Subtarget->isPICStyleStubAny() &&
2481                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2482                  (!Subtarget->getTargetTriple().isMacOSX() ||
2483                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2484         // PC-relative references to external symbols should go through $stub,
2485         // unless we're building with the leopard linker or later, which
2486         // automatically synthesizes these stubs.
2487         OpFlags = X86II::MO_DARWIN_STUB;
2488       } else if (Subtarget->isPICStyleRIPRel() &&
2489                  isa<Function>(GV) &&
2490                  cast<Function>(GV)->getFnAttributes().
2491                    hasAttribute(Attributes::NonLazyBind)) {
2492         // If the function is marked as non-lazy, generate an indirect call
2493         // which loads from the GOT directly. This avoids runtime overhead
2494         // at the cost of eager binding (and one extra byte of encoding).
2495         OpFlags = X86II::MO_GOTPCREL;
2496         WrapperKind = X86ISD::WrapperRIP;
2497         ExtraLoad = true;
2498       }
2499
2500       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2501                                           G->getOffset(), OpFlags);
2502
2503       // Add a wrapper if needed.
2504       if (WrapperKind != ISD::DELETED_NODE)
2505         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2506       // Add extra indirection if needed.
2507       if (ExtraLoad)
2508         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2509                              MachinePointerInfo::getGOT(),
2510                              false, false, false, 0);
2511     }
2512   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2513     unsigned char OpFlags = 0;
2514
2515     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2516     // external symbols should go through the PLT.
2517     if (Subtarget->isTargetELF() &&
2518         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2519       OpFlags = X86II::MO_PLT;
2520     } else if (Subtarget->isPICStyleStubAny() &&
2521                (!Subtarget->getTargetTriple().isMacOSX() ||
2522                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2523       // PC-relative references to external symbols should go through $stub,
2524       // unless we're building with the leopard linker or later, which
2525       // automatically synthesizes these stubs.
2526       OpFlags = X86II::MO_DARWIN_STUB;
2527     }
2528
2529     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2530                                          OpFlags);
2531   }
2532
2533   // Returns a chain & a flag for retval copy to use.
2534   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2535   SmallVector<SDValue, 8> Ops;
2536
2537   if (!IsSibcall && isTailCall) {
2538     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2539                            DAG.getIntPtrConstant(0, true), InFlag);
2540     InFlag = Chain.getValue(1);
2541   }
2542
2543   Ops.push_back(Chain);
2544   Ops.push_back(Callee);
2545
2546   if (isTailCall)
2547     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2548
2549   // Add argument registers to the end of the list so that they are known live
2550   // into the call.
2551   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2552     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2553                                   RegsToPass[i].second.getValueType()));
2554
2555   // Add a register mask operand representing the call-preserved registers.
2556   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2557   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2558   assert(Mask && "Missing call preserved mask for calling convention");
2559   Ops.push_back(DAG.getRegisterMask(Mask));
2560
2561   if (InFlag.getNode())
2562     Ops.push_back(InFlag);
2563
2564   if (isTailCall) {
2565     // We used to do:
2566     //// If this is the first return lowered for this function, add the regs
2567     //// to the liveout set for the function.
2568     // This isn't right, although it's probably harmless on x86; liveouts
2569     // should be computed from returns not tail calls.  Consider a void
2570     // function making a tail call to a function returning int.
2571     return DAG.getNode(X86ISD::TC_RETURN, dl,
2572                        NodeTys, &Ops[0], Ops.size());
2573   }
2574
2575   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2576   InFlag = Chain.getValue(1);
2577
2578   // Create the CALLSEQ_END node.
2579   unsigned NumBytesForCalleeToPush;
2580   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2581                        getTargetMachine().Options.GuaranteedTailCallOpt))
2582     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2583   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2584            SR == StackStructReturn)
2585     // If this is a call to a struct-return function, the callee
2586     // pops the hidden struct pointer, so we have to push it back.
2587     // This is common for Darwin/X86, Linux & Mingw32 targets.
2588     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2589     NumBytesForCalleeToPush = 4;
2590   else
2591     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2592
2593   // Returns a flag for retval copy to use.
2594   if (!IsSibcall) {
2595     Chain = DAG.getCALLSEQ_END(Chain,
2596                                DAG.getIntPtrConstant(NumBytes, true),
2597                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2598                                                      true),
2599                                InFlag);
2600     InFlag = Chain.getValue(1);
2601   }
2602
2603   // Handle result values, copying them out of physregs into vregs that we
2604   // return.
2605   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2606                          Ins, dl, DAG, InVals);
2607 }
2608
2609
2610 //===----------------------------------------------------------------------===//
2611 //                Fast Calling Convention (tail call) implementation
2612 //===----------------------------------------------------------------------===//
2613
2614 //  Like std call, callee cleans arguments, convention except that ECX is
2615 //  reserved for storing the tail called function address. Only 2 registers are
2616 //  free for argument passing (inreg). Tail call optimization is performed
2617 //  provided:
2618 //                * tailcallopt is enabled
2619 //                * caller/callee are fastcc
2620 //  On X86_64 architecture with GOT-style position independent code only local
2621 //  (within module) calls are supported at the moment.
2622 //  To keep the stack aligned according to platform abi the function
2623 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2624 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2625 //  If a tail called function callee has more arguments than the caller the
2626 //  caller needs to make sure that there is room to move the RETADDR to. This is
2627 //  achieved by reserving an area the size of the argument delta right after the
2628 //  original REtADDR, but before the saved framepointer or the spilled registers
2629 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2630 //  stack layout:
2631 //    arg1
2632 //    arg2
2633 //    RETADDR
2634 //    [ new RETADDR
2635 //      move area ]
2636 //    (possible EBP)
2637 //    ESI
2638 //    EDI
2639 //    local1 ..
2640
2641 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2642 /// for a 16 byte align requirement.
2643 unsigned
2644 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2645                                                SelectionDAG& DAG) const {
2646   MachineFunction &MF = DAG.getMachineFunction();
2647   const TargetMachine &TM = MF.getTarget();
2648   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2649   unsigned StackAlignment = TFI.getStackAlignment();
2650   uint64_t AlignMask = StackAlignment - 1;
2651   int64_t Offset = StackSize;
2652   uint64_t SlotSize = TD->getPointerSize();
2653   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2654     // Number smaller than 12 so just add the difference.
2655     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2656   } else {
2657     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2658     Offset = ((~AlignMask) & Offset) + StackAlignment +
2659       (StackAlignment-SlotSize);
2660   }
2661   return Offset;
2662 }
2663
2664 /// MatchingStackOffset - Return true if the given stack call argument is
2665 /// already available in the same position (relatively) of the caller's
2666 /// incoming argument stack.
2667 static
2668 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2669                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2670                          const X86InstrInfo *TII) {
2671   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2672   int FI = INT_MAX;
2673   if (Arg.getOpcode() == ISD::CopyFromReg) {
2674     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2675     if (!TargetRegisterInfo::isVirtualRegister(VR))
2676       return false;
2677     MachineInstr *Def = MRI->getVRegDef(VR);
2678     if (!Def)
2679       return false;
2680     if (!Flags.isByVal()) {
2681       if (!TII->isLoadFromStackSlot(Def, FI))
2682         return false;
2683     } else {
2684       unsigned Opcode = Def->getOpcode();
2685       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2686           Def->getOperand(1).isFI()) {
2687         FI = Def->getOperand(1).getIndex();
2688         Bytes = Flags.getByValSize();
2689       } else
2690         return false;
2691     }
2692   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2693     if (Flags.isByVal())
2694       // ByVal argument is passed in as a pointer but it's now being
2695       // dereferenced. e.g.
2696       // define @foo(%struct.X* %A) {
2697       //   tail call @bar(%struct.X* byval %A)
2698       // }
2699       return false;
2700     SDValue Ptr = Ld->getBasePtr();
2701     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2702     if (!FINode)
2703       return false;
2704     FI = FINode->getIndex();
2705   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2706     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2707     FI = FINode->getIndex();
2708     Bytes = Flags.getByValSize();
2709   } else
2710     return false;
2711
2712   assert(FI != INT_MAX);
2713   if (!MFI->isFixedObjectIndex(FI))
2714     return false;
2715   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2716 }
2717
2718 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2719 /// for tail call optimization. Targets which want to do tail call
2720 /// optimization should implement this function.
2721 bool
2722 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2723                                                      CallingConv::ID CalleeCC,
2724                                                      bool isVarArg,
2725                                                      bool isCalleeStructRet,
2726                                                      bool isCallerStructRet,
2727                                                      Type *RetTy,
2728                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2729                                     const SmallVectorImpl<SDValue> &OutVals,
2730                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2731                                                      SelectionDAG& DAG) const {
2732   if (!IsTailCallConvention(CalleeCC) &&
2733       CalleeCC != CallingConv::C)
2734     return false;
2735
2736   // If -tailcallopt is specified, make fastcc functions tail-callable.
2737   const MachineFunction &MF = DAG.getMachineFunction();
2738   const Function *CallerF = DAG.getMachineFunction().getFunction();
2739
2740   // If the function return type is x86_fp80 and the callee return type is not,
2741   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2742   // perform a tailcall optimization here.
2743   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2744     return false;
2745
2746   CallingConv::ID CallerCC = CallerF->getCallingConv();
2747   bool CCMatch = CallerCC == CalleeCC;
2748
2749   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2750     if (IsTailCallConvention(CalleeCC) && CCMatch)
2751       return true;
2752     return false;
2753   }
2754
2755   // Look for obvious safe cases to perform tail call optimization that do not
2756   // require ABI changes. This is what gcc calls sibcall.
2757
2758   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2759   // emit a special epilogue.
2760   if (RegInfo->needsStackRealignment(MF))
2761     return false;
2762
2763   // Also avoid sibcall optimization if either caller or callee uses struct
2764   // return semantics.
2765   if (isCalleeStructRet || isCallerStructRet)
2766     return false;
2767
2768   // An stdcall caller is expected to clean up its arguments; the callee
2769   // isn't going to do that.
2770   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2771     return false;
2772
2773   // Do not sibcall optimize vararg calls unless all arguments are passed via
2774   // registers.
2775   if (isVarArg && !Outs.empty()) {
2776
2777     // Optimizing for varargs on Win64 is unlikely to be safe without
2778     // additional testing.
2779     if (Subtarget->isTargetWin64())
2780       return false;
2781
2782     SmallVector<CCValAssign, 16> ArgLocs;
2783     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2784                    getTargetMachine(), ArgLocs, *DAG.getContext());
2785
2786     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2787     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2788       if (!ArgLocs[i].isRegLoc())
2789         return false;
2790   }
2791
2792   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2793   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2794   // this into a sibcall.
2795   bool Unused = false;
2796   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2797     if (!Ins[i].Used) {
2798       Unused = true;
2799       break;
2800     }
2801   }
2802   if (Unused) {
2803     SmallVector<CCValAssign, 16> RVLocs;
2804     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2805                    getTargetMachine(), RVLocs, *DAG.getContext());
2806     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2807     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2808       CCValAssign &VA = RVLocs[i];
2809       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2810         return false;
2811     }
2812   }
2813
2814   // If the calling conventions do not match, then we'd better make sure the
2815   // results are returned in the same way as what the caller expects.
2816   if (!CCMatch) {
2817     SmallVector<CCValAssign, 16> RVLocs1;
2818     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2819                     getTargetMachine(), RVLocs1, *DAG.getContext());
2820     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2821
2822     SmallVector<CCValAssign, 16> RVLocs2;
2823     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2824                     getTargetMachine(), RVLocs2, *DAG.getContext());
2825     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2826
2827     if (RVLocs1.size() != RVLocs2.size())
2828       return false;
2829     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2830       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2831         return false;
2832       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2833         return false;
2834       if (RVLocs1[i].isRegLoc()) {
2835         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2836           return false;
2837       } else {
2838         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2839           return false;
2840       }
2841     }
2842   }
2843
2844   // If the callee takes no arguments then go on to check the results of the
2845   // call.
2846   if (!Outs.empty()) {
2847     // Check if stack adjustment is needed. For now, do not do this if any
2848     // argument is passed on the stack.
2849     SmallVector<CCValAssign, 16> ArgLocs;
2850     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2851                    getTargetMachine(), ArgLocs, *DAG.getContext());
2852
2853     // Allocate shadow area for Win64
2854     if (Subtarget->isTargetWin64()) {
2855       CCInfo.AllocateStack(32, 8);
2856     }
2857
2858     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2859     if (CCInfo.getNextStackOffset()) {
2860       MachineFunction &MF = DAG.getMachineFunction();
2861       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2862         return false;
2863
2864       // Check if the arguments are already laid out in the right way as
2865       // the caller's fixed stack objects.
2866       MachineFrameInfo *MFI = MF.getFrameInfo();
2867       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2868       const X86InstrInfo *TII =
2869         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2870       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2871         CCValAssign &VA = ArgLocs[i];
2872         SDValue Arg = OutVals[i];
2873         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2874         if (VA.getLocInfo() == CCValAssign::Indirect)
2875           return false;
2876         if (!VA.isRegLoc()) {
2877           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2878                                    MFI, MRI, TII))
2879             return false;
2880         }
2881       }
2882     }
2883
2884     // If the tailcall address may be in a register, then make sure it's
2885     // possible to register allocate for it. In 32-bit, the call address can
2886     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2887     // callee-saved registers are restored. These happen to be the same
2888     // registers used to pass 'inreg' arguments so watch out for those.
2889     if (!Subtarget->is64Bit() &&
2890         !isa<GlobalAddressSDNode>(Callee) &&
2891         !isa<ExternalSymbolSDNode>(Callee)) {
2892       unsigned NumInRegs = 0;
2893       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2894         CCValAssign &VA = ArgLocs[i];
2895         if (!VA.isRegLoc())
2896           continue;
2897         unsigned Reg = VA.getLocReg();
2898         switch (Reg) {
2899         default: break;
2900         case X86::EAX: case X86::EDX: case X86::ECX:
2901           if (++NumInRegs == 3)
2902             return false;
2903           break;
2904         }
2905       }
2906     }
2907   }
2908
2909   return true;
2910 }
2911
2912 FastISel *
2913 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2914                                   const TargetLibraryInfo *libInfo) const {
2915   return X86::createFastISel(funcInfo, libInfo);
2916 }
2917
2918
2919 //===----------------------------------------------------------------------===//
2920 //                           Other Lowering Hooks
2921 //===----------------------------------------------------------------------===//
2922
2923 static bool MayFoldLoad(SDValue Op) {
2924   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2925 }
2926
2927 static bool MayFoldIntoStore(SDValue Op) {
2928   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2929 }
2930
2931 static bool isTargetShuffle(unsigned Opcode) {
2932   switch(Opcode) {
2933   default: return false;
2934   case X86ISD::PSHUFD:
2935   case X86ISD::PSHUFHW:
2936   case X86ISD::PSHUFLW:
2937   case X86ISD::SHUFP:
2938   case X86ISD::PALIGN:
2939   case X86ISD::MOVLHPS:
2940   case X86ISD::MOVLHPD:
2941   case X86ISD::MOVHLPS:
2942   case X86ISD::MOVLPS:
2943   case X86ISD::MOVLPD:
2944   case X86ISD::MOVSHDUP:
2945   case X86ISD::MOVSLDUP:
2946   case X86ISD::MOVDDUP:
2947   case X86ISD::MOVSS:
2948   case X86ISD::MOVSD:
2949   case X86ISD::UNPCKL:
2950   case X86ISD::UNPCKH:
2951   case X86ISD::VPERMILP:
2952   case X86ISD::VPERM2X128:
2953   case X86ISD::VPERMI:
2954     return true;
2955   }
2956 }
2957
2958 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2959                                     SDValue V1, SelectionDAG &DAG) {
2960   switch(Opc) {
2961   default: llvm_unreachable("Unknown x86 shuffle node");
2962   case X86ISD::MOVSHDUP:
2963   case X86ISD::MOVSLDUP:
2964   case X86ISD::MOVDDUP:
2965     return DAG.getNode(Opc, dl, VT, V1);
2966   }
2967 }
2968
2969 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2970                                     SDValue V1, unsigned TargetMask,
2971                                     SelectionDAG &DAG) {
2972   switch(Opc) {
2973   default: llvm_unreachable("Unknown x86 shuffle node");
2974   case X86ISD::PSHUFD:
2975   case X86ISD::PSHUFHW:
2976   case X86ISD::PSHUFLW:
2977   case X86ISD::VPERMILP:
2978   case X86ISD::VPERMI:
2979     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2980   }
2981 }
2982
2983 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2984                                     SDValue V1, SDValue V2, unsigned TargetMask,
2985                                     SelectionDAG &DAG) {
2986   switch(Opc) {
2987   default: llvm_unreachable("Unknown x86 shuffle node");
2988   case X86ISD::PALIGN:
2989   case X86ISD::SHUFP:
2990   case X86ISD::VPERM2X128:
2991     return DAG.getNode(Opc, dl, VT, V1, V2,
2992                        DAG.getConstant(TargetMask, MVT::i8));
2993   }
2994 }
2995
2996 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2997                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2998   switch(Opc) {
2999   default: llvm_unreachable("Unknown x86 shuffle node");
3000   case X86ISD::MOVLHPS:
3001   case X86ISD::MOVLHPD:
3002   case X86ISD::MOVHLPS:
3003   case X86ISD::MOVLPS:
3004   case X86ISD::MOVLPD:
3005   case X86ISD::MOVSS:
3006   case X86ISD::MOVSD:
3007   case X86ISD::UNPCKL:
3008   case X86ISD::UNPCKH:
3009     return DAG.getNode(Opc, dl, VT, V1, V2);
3010   }
3011 }
3012
3013 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3014   MachineFunction &MF = DAG.getMachineFunction();
3015   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3016   int ReturnAddrIndex = FuncInfo->getRAIndex();
3017
3018   if (ReturnAddrIndex == 0) {
3019     // Set up a frame object for the return address.
3020     uint64_t SlotSize = TD->getPointerSize();
3021     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3022                                                            false);
3023     FuncInfo->setRAIndex(ReturnAddrIndex);
3024   }
3025
3026   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3027 }
3028
3029
3030 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3031                                        bool hasSymbolicDisplacement) {
3032   // Offset should fit into 32 bit immediate field.
3033   if (!isInt<32>(Offset))
3034     return false;
3035
3036   // If we don't have a symbolic displacement - we don't have any extra
3037   // restrictions.
3038   if (!hasSymbolicDisplacement)
3039     return true;
3040
3041   // FIXME: Some tweaks might be needed for medium code model.
3042   if (M != CodeModel::Small && M != CodeModel::Kernel)
3043     return false;
3044
3045   // For small code model we assume that latest object is 16MB before end of 31
3046   // bits boundary. We may also accept pretty large negative constants knowing
3047   // that all objects are in the positive half of address space.
3048   if (M == CodeModel::Small && Offset < 16*1024*1024)
3049     return true;
3050
3051   // For kernel code model we know that all object resist in the negative half
3052   // of 32bits address space. We may not accept negative offsets, since they may
3053   // be just off and we may accept pretty large positive ones.
3054   if (M == CodeModel::Kernel && Offset > 0)
3055     return true;
3056
3057   return false;
3058 }
3059
3060 /// isCalleePop - Determines whether the callee is required to pop its
3061 /// own arguments. Callee pop is necessary to support tail calls.
3062 bool X86::isCalleePop(CallingConv::ID CallingConv,
3063                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3064   if (IsVarArg)
3065     return false;
3066
3067   switch (CallingConv) {
3068   default:
3069     return false;
3070   case CallingConv::X86_StdCall:
3071     return !is64Bit;
3072   case CallingConv::X86_FastCall:
3073     return !is64Bit;
3074   case CallingConv::X86_ThisCall:
3075     return !is64Bit;
3076   case CallingConv::Fast:
3077     return TailCallOpt;
3078   case CallingConv::GHC:
3079     return TailCallOpt;
3080   }
3081 }
3082
3083 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3084 /// specific condition code, returning the condition code and the LHS/RHS of the
3085 /// comparison to make.
3086 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3087                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3088   if (!isFP) {
3089     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3090       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3091         // X > -1   -> X == 0, jump !sign.
3092         RHS = DAG.getConstant(0, RHS.getValueType());
3093         return X86::COND_NS;
3094       }
3095       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3096         // X < 0   -> X == 0, jump on sign.
3097         return X86::COND_S;
3098       }
3099       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3100         // X < 1   -> X <= 0
3101         RHS = DAG.getConstant(0, RHS.getValueType());
3102         return X86::COND_LE;
3103       }
3104     }
3105
3106     switch (SetCCOpcode) {
3107     default: llvm_unreachable("Invalid integer condition!");
3108     case ISD::SETEQ:  return X86::COND_E;
3109     case ISD::SETGT:  return X86::COND_G;
3110     case ISD::SETGE:  return X86::COND_GE;
3111     case ISD::SETLT:  return X86::COND_L;
3112     case ISD::SETLE:  return X86::COND_LE;
3113     case ISD::SETNE:  return X86::COND_NE;
3114     case ISD::SETULT: return X86::COND_B;
3115     case ISD::SETUGT: return X86::COND_A;
3116     case ISD::SETULE: return X86::COND_BE;
3117     case ISD::SETUGE: return X86::COND_AE;
3118     }
3119   }
3120
3121   // First determine if it is required or is profitable to flip the operands.
3122
3123   // If LHS is a foldable load, but RHS is not, flip the condition.
3124   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3125       !ISD::isNON_EXTLoad(RHS.getNode())) {
3126     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3127     std::swap(LHS, RHS);
3128   }
3129
3130   switch (SetCCOpcode) {
3131   default: break;
3132   case ISD::SETOLT:
3133   case ISD::SETOLE:
3134   case ISD::SETUGT:
3135   case ISD::SETUGE:
3136     std::swap(LHS, RHS);
3137     break;
3138   }
3139
3140   // On a floating point condition, the flags are set as follows:
3141   // ZF  PF  CF   op
3142   //  0 | 0 | 0 | X > Y
3143   //  0 | 0 | 1 | X < Y
3144   //  1 | 0 | 0 | X == Y
3145   //  1 | 1 | 1 | unordered
3146   switch (SetCCOpcode) {
3147   default: llvm_unreachable("Condcode should be pre-legalized away");
3148   case ISD::SETUEQ:
3149   case ISD::SETEQ:   return X86::COND_E;
3150   case ISD::SETOLT:              // flipped
3151   case ISD::SETOGT:
3152   case ISD::SETGT:   return X86::COND_A;
3153   case ISD::SETOLE:              // flipped
3154   case ISD::SETOGE:
3155   case ISD::SETGE:   return X86::COND_AE;
3156   case ISD::SETUGT:              // flipped
3157   case ISD::SETULT:
3158   case ISD::SETLT:   return X86::COND_B;
3159   case ISD::SETUGE:              // flipped
3160   case ISD::SETULE:
3161   case ISD::SETLE:   return X86::COND_BE;
3162   case ISD::SETONE:
3163   case ISD::SETNE:   return X86::COND_NE;
3164   case ISD::SETUO:   return X86::COND_P;
3165   case ISD::SETO:    return X86::COND_NP;
3166   case ISD::SETOEQ:
3167   case ISD::SETUNE:  return X86::COND_INVALID;
3168   }
3169 }
3170
3171 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3172 /// code. Current x86 isa includes the following FP cmov instructions:
3173 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3174 static bool hasFPCMov(unsigned X86CC) {
3175   switch (X86CC) {
3176   default:
3177     return false;
3178   case X86::COND_B:
3179   case X86::COND_BE:
3180   case X86::COND_E:
3181   case X86::COND_P:
3182   case X86::COND_A:
3183   case X86::COND_AE:
3184   case X86::COND_NE:
3185   case X86::COND_NP:
3186     return true;
3187   }
3188 }
3189
3190 /// isFPImmLegal - Returns true if the target can instruction select the
3191 /// specified FP immediate natively. If false, the legalizer will
3192 /// materialize the FP immediate as a load from a constant pool.
3193 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3194   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3195     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3196       return true;
3197   }
3198   return false;
3199 }
3200
3201 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3202 /// the specified range (L, H].
3203 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3204   return (Val < 0) || (Val >= Low && Val < Hi);
3205 }
3206
3207 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3208 /// specified value.
3209 static bool isUndefOrEqual(int Val, int CmpVal) {
3210   if (Val < 0 || Val == CmpVal)
3211     return true;
3212   return false;
3213 }
3214
3215 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3216 /// from position Pos and ending in Pos+Size, falls within the specified
3217 /// sequential range (L, L+Pos]. or is undef.
3218 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3219                                        unsigned Pos, unsigned Size, int Low) {
3220   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3221     if (!isUndefOrEqual(Mask[i], Low))
3222       return false;
3223   return true;
3224 }
3225
3226 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3227 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3228 /// the second operand.
3229 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3230   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3231     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3232   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3233     return (Mask[0] < 2 && Mask[1] < 2);
3234   return false;
3235 }
3236
3237 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3238 /// is suitable for input to PSHUFHW.
3239 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3240   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3241     return false;
3242
3243   // Lower quadword copied in order or undef.
3244   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3245     return false;
3246
3247   // Upper quadword shuffled.
3248   for (unsigned i = 4; i != 8; ++i)
3249     if (!isUndefOrInRange(Mask[i], 4, 8))
3250       return false;
3251
3252   if (VT == MVT::v16i16) {
3253     // Lower quadword copied in order or undef.
3254     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3255       return false;
3256
3257     // Upper quadword shuffled.
3258     for (unsigned i = 12; i != 16; ++i)
3259       if (!isUndefOrInRange(Mask[i], 12, 16))
3260         return false;
3261   }
3262
3263   return true;
3264 }
3265
3266 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3267 /// is suitable for input to PSHUFLW.
3268 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3269   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3270     return false;
3271
3272   // Upper quadword copied in order.
3273   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3274     return false;
3275
3276   // Lower quadword shuffled.
3277   for (unsigned i = 0; i != 4; ++i)
3278     if (!isUndefOrInRange(Mask[i], 0, 4))
3279       return false;
3280
3281   if (VT == MVT::v16i16) {
3282     // Upper quadword copied in order.
3283     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3284       return false;
3285
3286     // Lower quadword shuffled.
3287     for (unsigned i = 8; i != 12; ++i)
3288       if (!isUndefOrInRange(Mask[i], 8, 12))
3289         return false;
3290   }
3291
3292   return true;
3293 }
3294
3295 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3296 /// is suitable for input to PALIGNR.
3297 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3298                           const X86Subtarget *Subtarget) {
3299   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3300       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3301     return false;
3302
3303   unsigned NumElts = VT.getVectorNumElements();
3304   unsigned NumLanes = VT.getSizeInBits()/128;
3305   unsigned NumLaneElts = NumElts/NumLanes;
3306
3307   // Do not handle 64-bit element shuffles with palignr.
3308   if (NumLaneElts == 2)
3309     return false;
3310
3311   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3312     unsigned i;
3313     for (i = 0; i != NumLaneElts; ++i) {
3314       if (Mask[i+l] >= 0)
3315         break;
3316     }
3317
3318     // Lane is all undef, go to next lane
3319     if (i == NumLaneElts)
3320       continue;
3321
3322     int Start = Mask[i+l];
3323
3324     // Make sure its in this lane in one of the sources
3325     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3326         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3327       return false;
3328
3329     // If not lane 0, then we must match lane 0
3330     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3331       return false;
3332
3333     // Correct second source to be contiguous with first source
3334     if (Start >= (int)NumElts)
3335       Start -= NumElts - NumLaneElts;
3336
3337     // Make sure we're shifting in the right direction.
3338     if (Start <= (int)(i+l))
3339       return false;
3340
3341     Start -= i;
3342
3343     // Check the rest of the elements to see if they are consecutive.
3344     for (++i; i != NumLaneElts; ++i) {
3345       int Idx = Mask[i+l];
3346
3347       // Make sure its in this lane
3348       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3349           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3350         return false;
3351
3352       // If not lane 0, then we must match lane 0
3353       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3354         return false;
3355
3356       if (Idx >= (int)NumElts)
3357         Idx -= NumElts - NumLaneElts;
3358
3359       if (!isUndefOrEqual(Idx, Start+i))
3360         return false;
3361
3362     }
3363   }
3364
3365   return true;
3366 }
3367
3368 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3369 /// the two vector operands have swapped position.
3370 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3371                                      unsigned NumElems) {
3372   for (unsigned i = 0; i != NumElems; ++i) {
3373     int idx = Mask[i];
3374     if (idx < 0)
3375       continue;
3376     else if (idx < (int)NumElems)
3377       Mask[i] = idx + NumElems;
3378     else
3379       Mask[i] = idx - NumElems;
3380   }
3381 }
3382
3383 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3384 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3385 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3386 /// reverse of what x86 shuffles want.
3387 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3388                         bool Commuted = false) {
3389   if (!HasAVX && VT.getSizeInBits() == 256)
3390     return false;
3391
3392   unsigned NumElems = VT.getVectorNumElements();
3393   unsigned NumLanes = VT.getSizeInBits()/128;
3394   unsigned NumLaneElems = NumElems/NumLanes;
3395
3396   if (NumLaneElems != 2 && NumLaneElems != 4)
3397     return false;
3398
3399   // VSHUFPSY divides the resulting vector into 4 chunks.
3400   // The sources are also splitted into 4 chunks, and each destination
3401   // chunk must come from a different source chunk.
3402   //
3403   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3404   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3405   //
3406   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3407   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3408   //
3409   // VSHUFPDY divides the resulting vector into 4 chunks.
3410   // The sources are also splitted into 4 chunks, and each destination
3411   // chunk must come from a different source chunk.
3412   //
3413   //  SRC1 =>      X3       X2       X1       X0
3414   //  SRC2 =>      Y3       Y2       Y1       Y0
3415   //
3416   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3417   //
3418   unsigned HalfLaneElems = NumLaneElems/2;
3419   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3420     for (unsigned i = 0; i != NumLaneElems; ++i) {
3421       int Idx = Mask[i+l];
3422       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3423       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3424         return false;
3425       // For VSHUFPSY, the mask of the second half must be the same as the
3426       // first but with the appropriate offsets. This works in the same way as
3427       // VPERMILPS works with masks.
3428       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3429         continue;
3430       if (!isUndefOrEqual(Idx, Mask[i]+l))
3431         return false;
3432     }
3433   }
3434
3435   return true;
3436 }
3437
3438 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3439 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3440 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3441   if (!VT.is128BitVector())
3442     return false;
3443
3444   unsigned NumElems = VT.getVectorNumElements();
3445
3446   if (NumElems != 4)
3447     return false;
3448
3449   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3450   return isUndefOrEqual(Mask[0], 6) &&
3451          isUndefOrEqual(Mask[1], 7) &&
3452          isUndefOrEqual(Mask[2], 2) &&
3453          isUndefOrEqual(Mask[3], 3);
3454 }
3455
3456 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3457 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3458 /// <2, 3, 2, 3>
3459 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3460   if (!VT.is128BitVector())
3461     return false;
3462
3463   unsigned NumElems = VT.getVectorNumElements();
3464
3465   if (NumElems != 4)
3466     return false;
3467
3468   return isUndefOrEqual(Mask[0], 2) &&
3469          isUndefOrEqual(Mask[1], 3) &&
3470          isUndefOrEqual(Mask[2], 2) &&
3471          isUndefOrEqual(Mask[3], 3);
3472 }
3473
3474 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3475 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3476 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3477   if (!VT.is128BitVector())
3478     return false;
3479
3480   unsigned NumElems = VT.getVectorNumElements();
3481
3482   if (NumElems != 2 && NumElems != 4)
3483     return false;
3484
3485   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3486     if (!isUndefOrEqual(Mask[i], i + NumElems))
3487       return false;
3488
3489   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3490     if (!isUndefOrEqual(Mask[i], i))
3491       return false;
3492
3493   return true;
3494 }
3495
3496 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3497 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3498 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3499   if (!VT.is128BitVector())
3500     return false;
3501
3502   unsigned NumElems = VT.getVectorNumElements();
3503
3504   if (NumElems != 2 && NumElems != 4)
3505     return false;
3506
3507   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3508     if (!isUndefOrEqual(Mask[i], i))
3509       return false;
3510
3511   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3512     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3513       return false;
3514
3515   return true;
3516 }
3517
3518 //
3519 // Some special combinations that can be optimized.
3520 //
3521 static
3522 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3523                                SelectionDAG &DAG) {
3524   EVT VT = SVOp->getValueType(0);
3525   DebugLoc dl = SVOp->getDebugLoc();
3526
3527   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3528     return SDValue();
3529
3530   ArrayRef<int> Mask = SVOp->getMask();
3531
3532   // These are the special masks that may be optimized.
3533   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3534   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3535   bool MatchEvenMask = true;
3536   bool MatchOddMask  = true;
3537   for (int i=0; i<8; ++i) {
3538     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3539       MatchEvenMask = false;
3540     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3541       MatchOddMask = false;
3542   }
3543
3544   if (!MatchEvenMask && !MatchOddMask)
3545     return SDValue();
3546
3547   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3548
3549   SDValue Op0 = SVOp->getOperand(0);
3550   SDValue Op1 = SVOp->getOperand(1);
3551
3552   if (MatchEvenMask) {
3553     // Shift the second operand right to 32 bits.
3554     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3555     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3556   } else {
3557     // Shift the first operand left to 32 bits.
3558     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3559     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3560   }
3561   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3562   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3563 }
3564
3565 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3566 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3567 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3568                          bool HasAVX2, bool V2IsSplat = false) {
3569   unsigned NumElts = VT.getVectorNumElements();
3570
3571   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3572          "Unsupported vector type for unpckh");
3573
3574   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3575       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3576     return false;
3577
3578   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3579   // independently on 128-bit lanes.
3580   unsigned NumLanes = VT.getSizeInBits()/128;
3581   unsigned NumLaneElts = NumElts/NumLanes;
3582
3583   for (unsigned l = 0; l != NumLanes; ++l) {
3584     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3585          i != (l+1)*NumLaneElts;
3586          i += 2, ++j) {
3587       int BitI  = Mask[i];
3588       int BitI1 = Mask[i+1];
3589       if (!isUndefOrEqual(BitI, j))
3590         return false;
3591       if (V2IsSplat) {
3592         if (!isUndefOrEqual(BitI1, NumElts))
3593           return false;
3594       } else {
3595         if (!isUndefOrEqual(BitI1, j + NumElts))
3596           return false;
3597       }
3598     }
3599   }
3600
3601   return true;
3602 }
3603
3604 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3605 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3606 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3607                          bool HasAVX2, bool V2IsSplat = false) {
3608   unsigned NumElts = VT.getVectorNumElements();
3609
3610   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3611          "Unsupported vector type for unpckh");
3612
3613   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3614       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3615     return false;
3616
3617   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3618   // independently on 128-bit lanes.
3619   unsigned NumLanes = VT.getSizeInBits()/128;
3620   unsigned NumLaneElts = NumElts/NumLanes;
3621
3622   for (unsigned l = 0; l != NumLanes; ++l) {
3623     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3624          i != (l+1)*NumLaneElts; i += 2, ++j) {
3625       int BitI  = Mask[i];
3626       int BitI1 = Mask[i+1];
3627       if (!isUndefOrEqual(BitI, j))
3628         return false;
3629       if (V2IsSplat) {
3630         if (isUndefOrEqual(BitI1, NumElts))
3631           return false;
3632       } else {
3633         if (!isUndefOrEqual(BitI1, j+NumElts))
3634           return false;
3635       }
3636     }
3637   }
3638   return true;
3639 }
3640
3641 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3642 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3643 /// <0, 0, 1, 1>
3644 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3645                                   bool HasAVX2) {
3646   unsigned NumElts = VT.getVectorNumElements();
3647
3648   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3649          "Unsupported vector type for unpckh");
3650
3651   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3652       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3653     return false;
3654
3655   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3656   // FIXME: Need a better way to get rid of this, there's no latency difference
3657   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3658   // the former later. We should also remove the "_undef" special mask.
3659   if (NumElts == 4 && VT.getSizeInBits() == 256)
3660     return false;
3661
3662   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3663   // independently on 128-bit lanes.
3664   unsigned NumLanes = VT.getSizeInBits()/128;
3665   unsigned NumLaneElts = NumElts/NumLanes;
3666
3667   for (unsigned l = 0; l != NumLanes; ++l) {
3668     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3669          i != (l+1)*NumLaneElts;
3670          i += 2, ++j) {
3671       int BitI  = Mask[i];
3672       int BitI1 = Mask[i+1];
3673
3674       if (!isUndefOrEqual(BitI, j))
3675         return false;
3676       if (!isUndefOrEqual(BitI1, j))
3677         return false;
3678     }
3679   }
3680
3681   return true;
3682 }
3683
3684 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3685 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3686 /// <2, 2, 3, 3>
3687 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3688   unsigned NumElts = VT.getVectorNumElements();
3689
3690   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3691          "Unsupported vector type for unpckh");
3692
3693   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3694       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3695     return false;
3696
3697   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3698   // independently on 128-bit lanes.
3699   unsigned NumLanes = VT.getSizeInBits()/128;
3700   unsigned NumLaneElts = NumElts/NumLanes;
3701
3702   for (unsigned l = 0; l != NumLanes; ++l) {
3703     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3704          i != (l+1)*NumLaneElts; i += 2, ++j) {
3705       int BitI  = Mask[i];
3706       int BitI1 = Mask[i+1];
3707       if (!isUndefOrEqual(BitI, j))
3708         return false;
3709       if (!isUndefOrEqual(BitI1, j))
3710         return false;
3711     }
3712   }
3713   return true;
3714 }
3715
3716 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3717 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3718 /// MOVSD, and MOVD, i.e. setting the lowest element.
3719 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3720   if (VT.getVectorElementType().getSizeInBits() < 32)
3721     return false;
3722   if (!VT.is128BitVector())
3723     return false;
3724
3725   unsigned NumElts = VT.getVectorNumElements();
3726
3727   if (!isUndefOrEqual(Mask[0], NumElts))
3728     return false;
3729
3730   for (unsigned i = 1; i != NumElts; ++i)
3731     if (!isUndefOrEqual(Mask[i], i))
3732       return false;
3733
3734   return true;
3735 }
3736
3737 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3738 /// as permutations between 128-bit chunks or halves. As an example: this
3739 /// shuffle bellow:
3740 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3741 /// The first half comes from the second half of V1 and the second half from the
3742 /// the second half of V2.
3743 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3744   if (!HasAVX || !VT.is256BitVector())
3745     return false;
3746
3747   // The shuffle result is divided into half A and half B. In total the two
3748   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3749   // B must come from C, D, E or F.
3750   unsigned HalfSize = VT.getVectorNumElements()/2;
3751   bool MatchA = false, MatchB = false;
3752
3753   // Check if A comes from one of C, D, E, F.
3754   for (unsigned Half = 0; Half != 4; ++Half) {
3755     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3756       MatchA = true;
3757       break;
3758     }
3759   }
3760
3761   // Check if B comes from one of C, D, E, F.
3762   for (unsigned Half = 0; Half != 4; ++Half) {
3763     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3764       MatchB = true;
3765       break;
3766     }
3767   }
3768
3769   return MatchA && MatchB;
3770 }
3771
3772 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3773 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3774 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3775   EVT VT = SVOp->getValueType(0);
3776
3777   unsigned HalfSize = VT.getVectorNumElements()/2;
3778
3779   unsigned FstHalf = 0, SndHalf = 0;
3780   for (unsigned i = 0; i < HalfSize; ++i) {
3781     if (SVOp->getMaskElt(i) > 0) {
3782       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3783       break;
3784     }
3785   }
3786   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3787     if (SVOp->getMaskElt(i) > 0) {
3788       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3789       break;
3790     }
3791   }
3792
3793   return (FstHalf | (SndHalf << 4));
3794 }
3795
3796 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3797 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3798 /// Note that VPERMIL mask matching is different depending whether theunderlying
3799 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3800 /// to the same elements of the low, but to the higher half of the source.
3801 /// In VPERMILPD the two lanes could be shuffled independently of each other
3802 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3803 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3804   if (!HasAVX)
3805     return false;
3806
3807   unsigned NumElts = VT.getVectorNumElements();
3808   // Only match 256-bit with 32/64-bit types
3809   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3810     return false;
3811
3812   unsigned NumLanes = VT.getSizeInBits()/128;
3813   unsigned LaneSize = NumElts/NumLanes;
3814   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3815     for (unsigned i = 0; i != LaneSize; ++i) {
3816       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3817         return false;
3818       if (NumElts != 8 || l == 0)
3819         continue;
3820       // VPERMILPS handling
3821       if (Mask[i] < 0)
3822         continue;
3823       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3824         return false;
3825     }
3826   }
3827
3828   return true;
3829 }
3830
3831 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3832 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3833 /// element of vector 2 and the other elements to come from vector 1 in order.
3834 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3835                                bool V2IsSplat = false, bool V2IsUndef = false) {
3836   if (!VT.is128BitVector())
3837     return false;
3838
3839   unsigned NumOps = VT.getVectorNumElements();
3840   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3841     return false;
3842
3843   if (!isUndefOrEqual(Mask[0], 0))
3844     return false;
3845
3846   for (unsigned i = 1; i != NumOps; ++i)
3847     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3848           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3849           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3850       return false;
3851
3852   return true;
3853 }
3854
3855 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3856 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3857 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3858 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3859                            const X86Subtarget *Subtarget) {
3860   if (!Subtarget->hasSSE3())
3861     return false;
3862
3863   unsigned NumElems = VT.getVectorNumElements();
3864
3865   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3866       (VT.getSizeInBits() == 256 && NumElems != 8))
3867     return false;
3868
3869   // "i+1" is the value the indexed mask element must have
3870   for (unsigned i = 0; i != NumElems; i += 2)
3871     if (!isUndefOrEqual(Mask[i], i+1) ||
3872         !isUndefOrEqual(Mask[i+1], i+1))
3873       return false;
3874
3875   return true;
3876 }
3877
3878 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3879 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3880 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3881 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3882                            const X86Subtarget *Subtarget) {
3883   if (!Subtarget->hasSSE3())
3884     return false;
3885
3886   unsigned NumElems = VT.getVectorNumElements();
3887
3888   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3889       (VT.getSizeInBits() == 256 && NumElems != 8))
3890     return false;
3891
3892   // "i" is the value the indexed mask element must have
3893   for (unsigned i = 0; i != NumElems; i += 2)
3894     if (!isUndefOrEqual(Mask[i], i) ||
3895         !isUndefOrEqual(Mask[i+1], i))
3896       return false;
3897
3898   return true;
3899 }
3900
3901 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3902 /// specifies a shuffle of elements that is suitable for input to 256-bit
3903 /// version of MOVDDUP.
3904 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3905   if (!HasAVX || !VT.is256BitVector())
3906     return false;
3907
3908   unsigned NumElts = VT.getVectorNumElements();
3909   if (NumElts != 4)
3910     return false;
3911
3912   for (unsigned i = 0; i != NumElts/2; ++i)
3913     if (!isUndefOrEqual(Mask[i], 0))
3914       return false;
3915   for (unsigned i = NumElts/2; i != NumElts; ++i)
3916     if (!isUndefOrEqual(Mask[i], NumElts/2))
3917       return false;
3918   return true;
3919 }
3920
3921 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3922 /// specifies a shuffle of elements that is suitable for input to 128-bit
3923 /// version of MOVDDUP.
3924 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3925   if (!VT.is128BitVector())
3926     return false;
3927
3928   unsigned e = VT.getVectorNumElements() / 2;
3929   for (unsigned i = 0; i != e; ++i)
3930     if (!isUndefOrEqual(Mask[i], i))
3931       return false;
3932   for (unsigned i = 0; i != e; ++i)
3933     if (!isUndefOrEqual(Mask[e+i], i))
3934       return false;
3935   return true;
3936 }
3937
3938 /// isVEXTRACTF128Index - Return true if the specified
3939 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3940 /// suitable for input to VEXTRACTF128.
3941 bool X86::isVEXTRACTF128Index(SDNode *N) {
3942   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3943     return false;
3944
3945   // The index should be aligned on a 128-bit boundary.
3946   uint64_t Index =
3947     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3948
3949   unsigned VL = N->getValueType(0).getVectorNumElements();
3950   unsigned VBits = N->getValueType(0).getSizeInBits();
3951   unsigned ElSize = VBits / VL;
3952   bool Result = (Index * ElSize) % 128 == 0;
3953
3954   return Result;
3955 }
3956
3957 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3958 /// operand specifies a subvector insert that is suitable for input to
3959 /// VINSERTF128.
3960 bool X86::isVINSERTF128Index(SDNode *N) {
3961   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3962     return false;
3963
3964   // The index should be aligned on a 128-bit boundary.
3965   uint64_t Index =
3966     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3967
3968   unsigned VL = N->getValueType(0).getVectorNumElements();
3969   unsigned VBits = N->getValueType(0).getSizeInBits();
3970   unsigned ElSize = VBits / VL;
3971   bool Result = (Index * ElSize) % 128 == 0;
3972
3973   return Result;
3974 }
3975
3976 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3977 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3978 /// Handles 128-bit and 256-bit.
3979 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3980   EVT VT = N->getValueType(0);
3981
3982   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3983          "Unsupported vector type for PSHUF/SHUFP");
3984
3985   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3986   // independently on 128-bit lanes.
3987   unsigned NumElts = VT.getVectorNumElements();
3988   unsigned NumLanes = VT.getSizeInBits()/128;
3989   unsigned NumLaneElts = NumElts/NumLanes;
3990
3991   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3992          "Only supports 2 or 4 elements per lane");
3993
3994   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3995   unsigned Mask = 0;
3996   for (unsigned i = 0; i != NumElts; ++i) {
3997     int Elt = N->getMaskElt(i);
3998     if (Elt < 0) continue;
3999     Elt &= NumLaneElts - 1;
4000     unsigned ShAmt = (i << Shift) % 8;
4001     Mask |= Elt << ShAmt;
4002   }
4003
4004   return Mask;
4005 }
4006
4007 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4008 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4009 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4010   EVT VT = N->getValueType(0);
4011
4012   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4013          "Unsupported vector type for PSHUFHW");
4014
4015   unsigned NumElts = VT.getVectorNumElements();
4016
4017   unsigned Mask = 0;
4018   for (unsigned l = 0; l != NumElts; l += 8) {
4019     // 8 nodes per lane, but we only care about the last 4.
4020     for (unsigned i = 0; i < 4; ++i) {
4021       int Elt = N->getMaskElt(l+i+4);
4022       if (Elt < 0) continue;
4023       Elt &= 0x3; // only 2-bits.
4024       Mask |= Elt << (i * 2);
4025     }
4026   }
4027
4028   return Mask;
4029 }
4030
4031 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4032 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4033 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4034   EVT VT = N->getValueType(0);
4035
4036   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4037          "Unsupported vector type for PSHUFHW");
4038
4039   unsigned NumElts = VT.getVectorNumElements();
4040
4041   unsigned Mask = 0;
4042   for (unsigned l = 0; l != NumElts; l += 8) {
4043     // 8 nodes per lane, but we only care about the first 4.
4044     for (unsigned i = 0; i < 4; ++i) {
4045       int Elt = N->getMaskElt(l+i);
4046       if (Elt < 0) continue;
4047       Elt &= 0x3; // only 2-bits
4048       Mask |= Elt << (i * 2);
4049     }
4050   }
4051
4052   return Mask;
4053 }
4054
4055 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4056 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4057 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4058   EVT VT = SVOp->getValueType(0);
4059   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4060
4061   unsigned NumElts = VT.getVectorNumElements();
4062   unsigned NumLanes = VT.getSizeInBits()/128;
4063   unsigned NumLaneElts = NumElts/NumLanes;
4064
4065   int Val = 0;
4066   unsigned i;
4067   for (i = 0; i != NumElts; ++i) {
4068     Val = SVOp->getMaskElt(i);
4069     if (Val >= 0)
4070       break;
4071   }
4072   if (Val >= (int)NumElts)
4073     Val -= NumElts - NumLaneElts;
4074
4075   assert(Val - i > 0 && "PALIGNR imm should be positive");
4076   return (Val - i) * EltSize;
4077 }
4078
4079 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4080 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4081 /// instructions.
4082 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4083   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4084     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4085
4086   uint64_t Index =
4087     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4088
4089   EVT VecVT = N->getOperand(0).getValueType();
4090   EVT ElVT = VecVT.getVectorElementType();
4091
4092   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4093   return Index / NumElemsPerChunk;
4094 }
4095
4096 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4097 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4098 /// instructions.
4099 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4100   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4101     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4102
4103   uint64_t Index =
4104     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4105
4106   EVT VecVT = N->getValueType(0);
4107   EVT ElVT = VecVT.getVectorElementType();
4108
4109   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4110   return Index / NumElemsPerChunk;
4111 }
4112
4113 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4114 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4115 /// Handles 256-bit.
4116 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4117   EVT VT = N->getValueType(0);
4118
4119   unsigned NumElts = VT.getVectorNumElements();
4120
4121   assert((VT.is256BitVector() && NumElts == 4) &&
4122          "Unsupported vector type for VPERMQ/VPERMPD");
4123
4124   unsigned Mask = 0;
4125   for (unsigned i = 0; i != NumElts; ++i) {
4126     int Elt = N->getMaskElt(i);
4127     if (Elt < 0)
4128       continue;
4129     Mask |= Elt << (i*2);
4130   }
4131
4132   return Mask;
4133 }
4134 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4135 /// constant +0.0.
4136 bool X86::isZeroNode(SDValue Elt) {
4137   return ((isa<ConstantSDNode>(Elt) &&
4138            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4139           (isa<ConstantFPSDNode>(Elt) &&
4140            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4141 }
4142
4143 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4144 /// their permute mask.
4145 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4146                                     SelectionDAG &DAG) {
4147   EVT VT = SVOp->getValueType(0);
4148   unsigned NumElems = VT.getVectorNumElements();
4149   SmallVector<int, 8> MaskVec;
4150
4151   for (unsigned i = 0; i != NumElems; ++i) {
4152     int Idx = SVOp->getMaskElt(i);
4153     if (Idx >= 0) {
4154       if (Idx < (int)NumElems)
4155         Idx += NumElems;
4156       else
4157         Idx -= NumElems;
4158     }
4159     MaskVec.push_back(Idx);
4160   }
4161   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4162                               SVOp->getOperand(0), &MaskVec[0]);
4163 }
4164
4165 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4166 /// match movhlps. The lower half elements should come from upper half of
4167 /// V1 (and in order), and the upper half elements should come from the upper
4168 /// half of V2 (and in order).
4169 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4170   if (!VT.is128BitVector())
4171     return false;
4172   if (VT.getVectorNumElements() != 4)
4173     return false;
4174   for (unsigned i = 0, e = 2; i != e; ++i)
4175     if (!isUndefOrEqual(Mask[i], i+2))
4176       return false;
4177   for (unsigned i = 2; i != 4; ++i)
4178     if (!isUndefOrEqual(Mask[i], i+4))
4179       return false;
4180   return true;
4181 }
4182
4183 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4184 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4185 /// required.
4186 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4187   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4188     return false;
4189   N = N->getOperand(0).getNode();
4190   if (!ISD::isNON_EXTLoad(N))
4191     return false;
4192   if (LD)
4193     *LD = cast<LoadSDNode>(N);
4194   return true;
4195 }
4196
4197 // Test whether the given value is a vector value which will be legalized
4198 // into a load.
4199 static bool WillBeConstantPoolLoad(SDNode *N) {
4200   if (N->getOpcode() != ISD::BUILD_VECTOR)
4201     return false;
4202
4203   // Check for any non-constant elements.
4204   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4205     switch (N->getOperand(i).getNode()->getOpcode()) {
4206     case ISD::UNDEF:
4207     case ISD::ConstantFP:
4208     case ISD::Constant:
4209       break;
4210     default:
4211       return false;
4212     }
4213
4214   // Vectors of all-zeros and all-ones are materialized with special
4215   // instructions rather than being loaded.
4216   return !ISD::isBuildVectorAllZeros(N) &&
4217          !ISD::isBuildVectorAllOnes(N);
4218 }
4219
4220 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4221 /// match movlp{s|d}. The lower half elements should come from lower half of
4222 /// V1 (and in order), and the upper half elements should come from the upper
4223 /// half of V2 (and in order). And since V1 will become the source of the
4224 /// MOVLP, it must be either a vector load or a scalar load to vector.
4225 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4226                                ArrayRef<int> Mask, EVT VT) {
4227   if (!VT.is128BitVector())
4228     return false;
4229
4230   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4231     return false;
4232   // Is V2 is a vector load, don't do this transformation. We will try to use
4233   // load folding shufps op.
4234   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4235     return false;
4236
4237   unsigned NumElems = VT.getVectorNumElements();
4238
4239   if (NumElems != 2 && NumElems != 4)
4240     return false;
4241   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4242     if (!isUndefOrEqual(Mask[i], i))
4243       return false;
4244   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4245     if (!isUndefOrEqual(Mask[i], i+NumElems))
4246       return false;
4247   return true;
4248 }
4249
4250 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4251 /// all the same.
4252 static bool isSplatVector(SDNode *N) {
4253   if (N->getOpcode() != ISD::BUILD_VECTOR)
4254     return false;
4255
4256   SDValue SplatValue = N->getOperand(0);
4257   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4258     if (N->getOperand(i) != SplatValue)
4259       return false;
4260   return true;
4261 }
4262
4263 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4264 /// to an zero vector.
4265 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4266 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4267   SDValue V1 = N->getOperand(0);
4268   SDValue V2 = N->getOperand(1);
4269   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4270   for (unsigned i = 0; i != NumElems; ++i) {
4271     int Idx = N->getMaskElt(i);
4272     if (Idx >= (int)NumElems) {
4273       unsigned Opc = V2.getOpcode();
4274       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4275         continue;
4276       if (Opc != ISD::BUILD_VECTOR ||
4277           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4278         return false;
4279     } else if (Idx >= 0) {
4280       unsigned Opc = V1.getOpcode();
4281       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4282         continue;
4283       if (Opc != ISD::BUILD_VECTOR ||
4284           !X86::isZeroNode(V1.getOperand(Idx)))
4285         return false;
4286     }
4287   }
4288   return true;
4289 }
4290
4291 /// getZeroVector - Returns a vector of specified type with all zero elements.
4292 ///
4293 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4294                              SelectionDAG &DAG, DebugLoc dl) {
4295   assert(VT.isVector() && "Expected a vector type");
4296   unsigned Size = VT.getSizeInBits();
4297
4298   // Always build SSE zero vectors as <4 x i32> bitcasted
4299   // to their dest type. This ensures they get CSE'd.
4300   SDValue Vec;
4301   if (Size == 128) {  // SSE
4302     if (Subtarget->hasSSE2()) {  // SSE2
4303       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4304       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4305     } else { // SSE1
4306       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4307       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4308     }
4309   } else if (Size == 256) { // AVX
4310     if (Subtarget->hasAVX2()) { // AVX2
4311       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4312       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4313       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4314     } else {
4315       // 256-bit logic and arithmetic instructions in AVX are all
4316       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4317       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4318       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4319       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4320     }
4321   } else
4322     llvm_unreachable("Unexpected vector type");
4323
4324   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4325 }
4326
4327 /// getOnesVector - Returns a vector of specified type with all bits set.
4328 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4329 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4330 /// Then bitcast to their original type, ensuring they get CSE'd.
4331 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4332                              DebugLoc dl) {
4333   assert(VT.isVector() && "Expected a vector type");
4334   unsigned Size = VT.getSizeInBits();
4335
4336   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4337   SDValue Vec;
4338   if (Size == 256) {
4339     if (HasAVX2) { // AVX2
4340       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4341       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4342     } else { // AVX
4343       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4344       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4345     }
4346   } else if (Size == 128) {
4347     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4348   } else
4349     llvm_unreachable("Unexpected vector type");
4350
4351   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4352 }
4353
4354 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4355 /// that point to V2 points to its first element.
4356 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4357   for (unsigned i = 0; i != NumElems; ++i) {
4358     if (Mask[i] > (int)NumElems) {
4359       Mask[i] = NumElems;
4360     }
4361   }
4362 }
4363
4364 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4365 /// operation of specified width.
4366 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4367                        SDValue V2) {
4368   unsigned NumElems = VT.getVectorNumElements();
4369   SmallVector<int, 8> Mask;
4370   Mask.push_back(NumElems);
4371   for (unsigned i = 1; i != NumElems; ++i)
4372     Mask.push_back(i);
4373   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4374 }
4375
4376 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4377 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4378                           SDValue V2) {
4379   unsigned NumElems = VT.getVectorNumElements();
4380   SmallVector<int, 8> Mask;
4381   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4382     Mask.push_back(i);
4383     Mask.push_back(i + NumElems);
4384   }
4385   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4386 }
4387
4388 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4389 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4390                           SDValue V2) {
4391   unsigned NumElems = VT.getVectorNumElements();
4392   SmallVector<int, 8> Mask;
4393   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4394     Mask.push_back(i + Half);
4395     Mask.push_back(i + NumElems + Half);
4396   }
4397   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4398 }
4399
4400 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4401 // a generic shuffle instruction because the target has no such instructions.
4402 // Generate shuffles which repeat i16 and i8 several times until they can be
4403 // represented by v4f32 and then be manipulated by target suported shuffles.
4404 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4405   EVT VT = V.getValueType();
4406   int NumElems = VT.getVectorNumElements();
4407   DebugLoc dl = V.getDebugLoc();
4408
4409   while (NumElems > 4) {
4410     if (EltNo < NumElems/2) {
4411       V = getUnpackl(DAG, dl, VT, V, V);
4412     } else {
4413       V = getUnpackh(DAG, dl, VT, V, V);
4414       EltNo -= NumElems/2;
4415     }
4416     NumElems >>= 1;
4417   }
4418   return V;
4419 }
4420
4421 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4422 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4423   EVT VT = V.getValueType();
4424   DebugLoc dl = V.getDebugLoc();
4425   unsigned Size = VT.getSizeInBits();
4426
4427   if (Size == 128) {
4428     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4429     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4430     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4431                              &SplatMask[0]);
4432   } else if (Size == 256) {
4433     // To use VPERMILPS to splat scalars, the second half of indicies must
4434     // refer to the higher part, which is a duplication of the lower one,
4435     // because VPERMILPS can only handle in-lane permutations.
4436     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4437                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4438
4439     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4440     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4441                              &SplatMask[0]);
4442   } else
4443     llvm_unreachable("Vector size not supported");
4444
4445   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4446 }
4447
4448 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4449 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4450   EVT SrcVT = SV->getValueType(0);
4451   SDValue V1 = SV->getOperand(0);
4452   DebugLoc dl = SV->getDebugLoc();
4453
4454   int EltNo = SV->getSplatIndex();
4455   int NumElems = SrcVT.getVectorNumElements();
4456   unsigned Size = SrcVT.getSizeInBits();
4457
4458   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4459           "Unknown how to promote splat for type");
4460
4461   // Extract the 128-bit part containing the splat element and update
4462   // the splat element index when it refers to the higher register.
4463   if (Size == 256) {
4464     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4465     if (EltNo >= NumElems/2)
4466       EltNo -= NumElems/2;
4467   }
4468
4469   // All i16 and i8 vector types can't be used directly by a generic shuffle
4470   // instruction because the target has no such instruction. Generate shuffles
4471   // which repeat i16 and i8 several times until they fit in i32, and then can
4472   // be manipulated by target suported shuffles.
4473   EVT EltVT = SrcVT.getVectorElementType();
4474   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4475     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4476
4477   // Recreate the 256-bit vector and place the same 128-bit vector
4478   // into the low and high part. This is necessary because we want
4479   // to use VPERM* to shuffle the vectors
4480   if (Size == 256) {
4481     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4482   }
4483
4484   return getLegalSplat(DAG, V1, EltNo);
4485 }
4486
4487 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4488 /// vector of zero or undef vector.  This produces a shuffle where the low
4489 /// element of V2 is swizzled into the zero/undef vector, landing at element
4490 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4491 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4492                                            bool IsZero,
4493                                            const X86Subtarget *Subtarget,
4494                                            SelectionDAG &DAG) {
4495   EVT VT = V2.getValueType();
4496   SDValue V1 = IsZero
4497     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4498   unsigned NumElems = VT.getVectorNumElements();
4499   SmallVector<int, 16> MaskVec;
4500   for (unsigned i = 0; i != NumElems; ++i)
4501     // If this is the insertion idx, put the low elt of V2 here.
4502     MaskVec.push_back(i == Idx ? NumElems : i);
4503   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4504 }
4505
4506 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4507 /// target specific opcode. Returns true if the Mask could be calculated.
4508 /// Sets IsUnary to true if only uses one source.
4509 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4510                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4511   unsigned NumElems = VT.getVectorNumElements();
4512   SDValue ImmN;
4513
4514   IsUnary = false;
4515   switch(N->getOpcode()) {
4516   case X86ISD::SHUFP:
4517     ImmN = N->getOperand(N->getNumOperands()-1);
4518     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4519     break;
4520   case X86ISD::UNPCKH:
4521     DecodeUNPCKHMask(VT, Mask);
4522     break;
4523   case X86ISD::UNPCKL:
4524     DecodeUNPCKLMask(VT, Mask);
4525     break;
4526   case X86ISD::MOVHLPS:
4527     DecodeMOVHLPSMask(NumElems, Mask);
4528     break;
4529   case X86ISD::MOVLHPS:
4530     DecodeMOVLHPSMask(NumElems, Mask);
4531     break;
4532   case X86ISD::PSHUFD:
4533   case X86ISD::VPERMILP:
4534     ImmN = N->getOperand(N->getNumOperands()-1);
4535     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4536     IsUnary = true;
4537     break;
4538   case X86ISD::PSHUFHW:
4539     ImmN = N->getOperand(N->getNumOperands()-1);
4540     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4541     IsUnary = true;
4542     break;
4543   case X86ISD::PSHUFLW:
4544     ImmN = N->getOperand(N->getNumOperands()-1);
4545     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4546     IsUnary = true;
4547     break;
4548   case X86ISD::VPERMI:
4549     ImmN = N->getOperand(N->getNumOperands()-1);
4550     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4551     IsUnary = true;
4552     break;
4553   case X86ISD::MOVSS:
4554   case X86ISD::MOVSD: {
4555     // The index 0 always comes from the first element of the second source,
4556     // this is why MOVSS and MOVSD are used in the first place. The other
4557     // elements come from the other positions of the first source vector
4558     Mask.push_back(NumElems);
4559     for (unsigned i = 1; i != NumElems; ++i) {
4560       Mask.push_back(i);
4561     }
4562     break;
4563   }
4564   case X86ISD::VPERM2X128:
4565     ImmN = N->getOperand(N->getNumOperands()-1);
4566     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4567     if (Mask.empty()) return false;
4568     break;
4569   case X86ISD::MOVDDUP:
4570   case X86ISD::MOVLHPD:
4571   case X86ISD::MOVLPD:
4572   case X86ISD::MOVLPS:
4573   case X86ISD::MOVSHDUP:
4574   case X86ISD::MOVSLDUP:
4575   case X86ISD::PALIGN:
4576     // Not yet implemented
4577     return false;
4578   default: llvm_unreachable("unknown target shuffle node");
4579   }
4580
4581   return true;
4582 }
4583
4584 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4585 /// element of the result of the vector shuffle.
4586 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4587                                    unsigned Depth) {
4588   if (Depth == 6)
4589     return SDValue();  // Limit search depth.
4590
4591   SDValue V = SDValue(N, 0);
4592   EVT VT = V.getValueType();
4593   unsigned Opcode = V.getOpcode();
4594
4595   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4596   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4597     int Elt = SV->getMaskElt(Index);
4598
4599     if (Elt < 0)
4600       return DAG.getUNDEF(VT.getVectorElementType());
4601
4602     unsigned NumElems = VT.getVectorNumElements();
4603     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4604                                          : SV->getOperand(1);
4605     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4606   }
4607
4608   // Recurse into target specific vector shuffles to find scalars.
4609   if (isTargetShuffle(Opcode)) {
4610     MVT ShufVT = V.getValueType().getSimpleVT();
4611     unsigned NumElems = ShufVT.getVectorNumElements();
4612     SmallVector<int, 16> ShuffleMask;
4613     SDValue ImmN;
4614     bool IsUnary;
4615
4616     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4617       return SDValue();
4618
4619     int Elt = ShuffleMask[Index];
4620     if (Elt < 0)
4621       return DAG.getUNDEF(ShufVT.getVectorElementType());
4622
4623     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4624                                          : N->getOperand(1);
4625     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4626                                Depth+1);
4627   }
4628
4629   // Actual nodes that may contain scalar elements
4630   if (Opcode == ISD::BITCAST) {
4631     V = V.getOperand(0);
4632     EVT SrcVT = V.getValueType();
4633     unsigned NumElems = VT.getVectorNumElements();
4634
4635     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4636       return SDValue();
4637   }
4638
4639   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4640     return (Index == 0) ? V.getOperand(0)
4641                         : DAG.getUNDEF(VT.getVectorElementType());
4642
4643   if (V.getOpcode() == ISD::BUILD_VECTOR)
4644     return V.getOperand(Index);
4645
4646   return SDValue();
4647 }
4648
4649 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4650 /// shuffle operation which come from a consecutively from a zero. The
4651 /// search can start in two different directions, from left or right.
4652 static
4653 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4654                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4655   unsigned i;
4656   for (i = 0; i != NumElems; ++i) {
4657     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4658     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4659     if (!(Elt.getNode() &&
4660          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4661       break;
4662   }
4663
4664   return i;
4665 }
4666
4667 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4668 /// correspond consecutively to elements from one of the vector operands,
4669 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4670 static
4671 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4672                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4673                               unsigned NumElems, unsigned &OpNum) {
4674   bool SeenV1 = false;
4675   bool SeenV2 = false;
4676
4677   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4678     int Idx = SVOp->getMaskElt(i);
4679     // Ignore undef indicies
4680     if (Idx < 0)
4681       continue;
4682
4683     if (Idx < (int)NumElems)
4684       SeenV1 = true;
4685     else
4686       SeenV2 = true;
4687
4688     // Only accept consecutive elements from the same vector
4689     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4690       return false;
4691   }
4692
4693   OpNum = SeenV1 ? 0 : 1;
4694   return true;
4695 }
4696
4697 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4698 /// logical left shift of a vector.
4699 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4700                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4701   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4702   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4703               false /* check zeros from right */, DAG);
4704   unsigned OpSrc;
4705
4706   if (!NumZeros)
4707     return false;
4708
4709   // Considering the elements in the mask that are not consecutive zeros,
4710   // check if they consecutively come from only one of the source vectors.
4711   //
4712   //               V1 = {X, A, B, C}     0
4713   //                         \  \  \    /
4714   //   vector_shuffle V1, V2 <1, 2, 3, X>
4715   //
4716   if (!isShuffleMaskConsecutive(SVOp,
4717             0,                   // Mask Start Index
4718             NumElems-NumZeros,   // Mask End Index(exclusive)
4719             NumZeros,            // Where to start looking in the src vector
4720             NumElems,            // Number of elements in vector
4721             OpSrc))              // Which source operand ?
4722     return false;
4723
4724   isLeft = false;
4725   ShAmt = NumZeros;
4726   ShVal = SVOp->getOperand(OpSrc);
4727   return true;
4728 }
4729
4730 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4731 /// logical left shift of a vector.
4732 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4733                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4734   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4735   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4736               true /* check zeros from left */, DAG);
4737   unsigned OpSrc;
4738
4739   if (!NumZeros)
4740     return false;
4741
4742   // Considering the elements in the mask that are not consecutive zeros,
4743   // check if they consecutively come from only one of the source vectors.
4744   //
4745   //                           0    { A, B, X, X } = V2
4746   //                          / \    /  /
4747   //   vector_shuffle V1, V2 <X, X, 4, 5>
4748   //
4749   if (!isShuffleMaskConsecutive(SVOp,
4750             NumZeros,     // Mask Start Index
4751             NumElems,     // Mask End Index(exclusive)
4752             0,            // Where to start looking in the src vector
4753             NumElems,     // Number of elements in vector
4754             OpSrc))       // Which source operand ?
4755     return false;
4756
4757   isLeft = true;
4758   ShAmt = NumZeros;
4759   ShVal = SVOp->getOperand(OpSrc);
4760   return true;
4761 }
4762
4763 /// isVectorShift - Returns true if the shuffle can be implemented as a
4764 /// logical left or right shift of a vector.
4765 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4766                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4767   // Although the logic below support any bitwidth size, there are no
4768   // shift instructions which handle more than 128-bit vectors.
4769   if (!SVOp->getValueType(0).is128BitVector())
4770     return false;
4771
4772   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4773       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4774     return true;
4775
4776   return false;
4777 }
4778
4779 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4780 ///
4781 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4782                                        unsigned NumNonZero, unsigned NumZero,
4783                                        SelectionDAG &DAG,
4784                                        const X86Subtarget* Subtarget,
4785                                        const TargetLowering &TLI) {
4786   if (NumNonZero > 8)
4787     return SDValue();
4788
4789   DebugLoc dl = Op.getDebugLoc();
4790   SDValue V(0, 0);
4791   bool First = true;
4792   for (unsigned i = 0; i < 16; ++i) {
4793     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4794     if (ThisIsNonZero && First) {
4795       if (NumZero)
4796         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4797       else
4798         V = DAG.getUNDEF(MVT::v8i16);
4799       First = false;
4800     }
4801
4802     if ((i & 1) != 0) {
4803       SDValue ThisElt(0, 0), LastElt(0, 0);
4804       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4805       if (LastIsNonZero) {
4806         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4807                               MVT::i16, Op.getOperand(i-1));
4808       }
4809       if (ThisIsNonZero) {
4810         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4811         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4812                               ThisElt, DAG.getConstant(8, MVT::i8));
4813         if (LastIsNonZero)
4814           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4815       } else
4816         ThisElt = LastElt;
4817
4818       if (ThisElt.getNode())
4819         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4820                         DAG.getIntPtrConstant(i/2));
4821     }
4822   }
4823
4824   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4825 }
4826
4827 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4828 ///
4829 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4830                                      unsigned NumNonZero, unsigned NumZero,
4831                                      SelectionDAG &DAG,
4832                                      const X86Subtarget* Subtarget,
4833                                      const TargetLowering &TLI) {
4834   if (NumNonZero > 4)
4835     return SDValue();
4836
4837   DebugLoc dl = Op.getDebugLoc();
4838   SDValue V(0, 0);
4839   bool First = true;
4840   for (unsigned i = 0; i < 8; ++i) {
4841     bool isNonZero = (NonZeros & (1 << i)) != 0;
4842     if (isNonZero) {
4843       if (First) {
4844         if (NumZero)
4845           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4846         else
4847           V = DAG.getUNDEF(MVT::v8i16);
4848         First = false;
4849       }
4850       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4851                       MVT::v8i16, V, Op.getOperand(i),
4852                       DAG.getIntPtrConstant(i));
4853     }
4854   }
4855
4856   return V;
4857 }
4858
4859 /// getVShift - Return a vector logical shift node.
4860 ///
4861 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4862                          unsigned NumBits, SelectionDAG &DAG,
4863                          const TargetLowering &TLI, DebugLoc dl) {
4864   assert(VT.is128BitVector() && "Unknown type for VShift");
4865   EVT ShVT = MVT::v2i64;
4866   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4867   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4868   return DAG.getNode(ISD::BITCAST, dl, VT,
4869                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4870                              DAG.getConstant(NumBits,
4871                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4872 }
4873
4874 SDValue
4875 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4876                                           SelectionDAG &DAG) const {
4877
4878   // Check if the scalar load can be widened into a vector load. And if
4879   // the address is "base + cst" see if the cst can be "absorbed" into
4880   // the shuffle mask.
4881   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4882     SDValue Ptr = LD->getBasePtr();
4883     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4884       return SDValue();
4885     EVT PVT = LD->getValueType(0);
4886     if (PVT != MVT::i32 && PVT != MVT::f32)
4887       return SDValue();
4888
4889     int FI = -1;
4890     int64_t Offset = 0;
4891     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4892       FI = FINode->getIndex();
4893       Offset = 0;
4894     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4895                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4896       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4897       Offset = Ptr.getConstantOperandVal(1);
4898       Ptr = Ptr.getOperand(0);
4899     } else {
4900       return SDValue();
4901     }
4902
4903     // FIXME: 256-bit vector instructions don't require a strict alignment,
4904     // improve this code to support it better.
4905     unsigned RequiredAlign = VT.getSizeInBits()/8;
4906     SDValue Chain = LD->getChain();
4907     // Make sure the stack object alignment is at least 16 or 32.
4908     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4909     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4910       if (MFI->isFixedObjectIndex(FI)) {
4911         // Can't change the alignment. FIXME: It's possible to compute
4912         // the exact stack offset and reference FI + adjust offset instead.
4913         // If someone *really* cares about this. That's the way to implement it.
4914         return SDValue();
4915       } else {
4916         MFI->setObjectAlignment(FI, RequiredAlign);
4917       }
4918     }
4919
4920     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4921     // Ptr + (Offset & ~15).
4922     if (Offset < 0)
4923       return SDValue();
4924     if ((Offset % RequiredAlign) & 3)
4925       return SDValue();
4926     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4927     if (StartOffset)
4928       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4929                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4930
4931     int EltNo = (Offset - StartOffset) >> 2;
4932     unsigned NumElems = VT.getVectorNumElements();
4933
4934     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4935     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4936                              LD->getPointerInfo().getWithOffset(StartOffset),
4937                              false, false, false, 0);
4938
4939     SmallVector<int, 8> Mask;
4940     for (unsigned i = 0; i != NumElems; ++i)
4941       Mask.push_back(EltNo);
4942
4943     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4944   }
4945
4946   return SDValue();
4947 }
4948
4949 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4950 /// vector of type 'VT', see if the elements can be replaced by a single large
4951 /// load which has the same value as a build_vector whose operands are 'elts'.
4952 ///
4953 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4954 ///
4955 /// FIXME: we'd also like to handle the case where the last elements are zero
4956 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4957 /// There's even a handy isZeroNode for that purpose.
4958 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4959                                         DebugLoc &DL, SelectionDAG &DAG) {
4960   EVT EltVT = VT.getVectorElementType();
4961   unsigned NumElems = Elts.size();
4962
4963   LoadSDNode *LDBase = NULL;
4964   unsigned LastLoadedElt = -1U;
4965
4966   // For each element in the initializer, see if we've found a load or an undef.
4967   // If we don't find an initial load element, or later load elements are
4968   // non-consecutive, bail out.
4969   for (unsigned i = 0; i < NumElems; ++i) {
4970     SDValue Elt = Elts[i];
4971
4972     if (!Elt.getNode() ||
4973         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4974       return SDValue();
4975     if (!LDBase) {
4976       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4977         return SDValue();
4978       LDBase = cast<LoadSDNode>(Elt.getNode());
4979       LastLoadedElt = i;
4980       continue;
4981     }
4982     if (Elt.getOpcode() == ISD::UNDEF)
4983       continue;
4984
4985     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4986     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4987       return SDValue();
4988     LastLoadedElt = i;
4989   }
4990
4991   // If we have found an entire vector of loads and undefs, then return a large
4992   // load of the entire vector width starting at the base pointer.  If we found
4993   // consecutive loads for the low half, generate a vzext_load node.
4994   if (LastLoadedElt == NumElems - 1) {
4995     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4996       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4997                          LDBase->getPointerInfo(),
4998                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4999                          LDBase->isInvariant(), 0);
5000     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5001                        LDBase->getPointerInfo(),
5002                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5003                        LDBase->isInvariant(), LDBase->getAlignment());
5004   }
5005   if (NumElems == 4 && LastLoadedElt == 1 &&
5006       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5007     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5008     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5009     SDValue ResNode =
5010         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5011                                 LDBase->getPointerInfo(),
5012                                 LDBase->getAlignment(),
5013                                 false/*isVolatile*/, true/*ReadMem*/,
5014                                 false/*WriteMem*/);
5015
5016     // Make sure the newly-created LOAD is in the same position as LDBase in
5017     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5018     // update uses of LDBase's output chain to use the TokenFactor.
5019     if (LDBase->hasAnyUseOfValue(1)) {
5020       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5021                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5022       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5023       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5024                              SDValue(ResNode.getNode(), 1));
5025     }
5026
5027     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5028   }
5029   return SDValue();
5030 }
5031
5032 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5033 /// to generate a splat value for the following cases:
5034 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5035 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5036 /// a scalar load, or a constant.
5037 /// The VBROADCAST node is returned when a pattern is found,
5038 /// or SDValue() otherwise.
5039 SDValue
5040 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5041   if (!Subtarget->hasAVX())
5042     return SDValue();
5043
5044   EVT VT = Op.getValueType();
5045   DebugLoc dl = Op.getDebugLoc();
5046
5047   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5048          "Unsupported vector type for broadcast.");
5049
5050   SDValue Ld;
5051   bool ConstSplatVal;
5052
5053   switch (Op.getOpcode()) {
5054     default:
5055       // Unknown pattern found.
5056       return SDValue();
5057
5058     case ISD::BUILD_VECTOR: {
5059       // The BUILD_VECTOR node must be a splat.
5060       if (!isSplatVector(Op.getNode()))
5061         return SDValue();
5062
5063       Ld = Op.getOperand(0);
5064       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5065                      Ld.getOpcode() == ISD::ConstantFP);
5066
5067       // The suspected load node has several users. Make sure that all
5068       // of its users are from the BUILD_VECTOR node.
5069       // Constants may have multiple users.
5070       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5071         return SDValue();
5072       break;
5073     }
5074
5075     case ISD::VECTOR_SHUFFLE: {
5076       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5077
5078       // Shuffles must have a splat mask where the first element is
5079       // broadcasted.
5080       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5081         return SDValue();
5082
5083       SDValue Sc = Op.getOperand(0);
5084       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5085           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5086
5087         if (!Subtarget->hasAVX2())
5088           return SDValue();
5089
5090         // Use the register form of the broadcast instruction available on AVX2.
5091         if (VT.is256BitVector())
5092           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5093         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5094       }
5095
5096       Ld = Sc.getOperand(0);
5097       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5098                        Ld.getOpcode() == ISD::ConstantFP);
5099
5100       // The scalar_to_vector node and the suspected
5101       // load node must have exactly one user.
5102       // Constants may have multiple users.
5103       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5104         return SDValue();
5105       break;
5106     }
5107   }
5108
5109   bool Is256 = VT.is256BitVector();
5110
5111   // Handle the broadcasting a single constant scalar from the constant pool
5112   // into a vector. On Sandybridge it is still better to load a constant vector
5113   // from the constant pool and not to broadcast it from a scalar.
5114   if (ConstSplatVal && Subtarget->hasAVX2()) {
5115     EVT CVT = Ld.getValueType();
5116     assert(!CVT.isVector() && "Must not broadcast a vector type");
5117     unsigned ScalarSize = CVT.getSizeInBits();
5118
5119     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5120       const Constant *C = 0;
5121       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5122         C = CI->getConstantIntValue();
5123       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5124         C = CF->getConstantFPValue();
5125
5126       assert(C && "Invalid constant type");
5127
5128       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5129       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5130       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5131                        MachinePointerInfo::getConstantPool(),
5132                        false, false, false, Alignment);
5133
5134       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5135     }
5136   }
5137
5138   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5139   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5140
5141   // Handle AVX2 in-register broadcasts.
5142   if (!IsLoad && Subtarget->hasAVX2() &&
5143       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5144     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5145
5146   // The scalar source must be a normal load.
5147   if (!IsLoad)
5148     return SDValue();
5149
5150   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5151     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5152
5153   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5154   // double since there is no vbroadcastsd xmm
5155   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5156     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5157       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5158   }
5159
5160   // Unsupported broadcast.
5161   return SDValue();
5162 }
5163
5164 // LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5165 // and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5166 // constraint of matching input/output vector elements.
5167 SDValue
5168 X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5169   DebugLoc DL = Op.getDebugLoc();
5170   SDNode *N = Op.getNode();
5171   EVT VT = Op.getValueType();
5172   unsigned NumElts = Op.getNumOperands();
5173
5174   // Check supported types and sub-targets.
5175   //
5176   // Only v2f32 -> v2f64 needs special handling.
5177   if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5178     return SDValue();
5179
5180   SDValue VecIn;
5181   EVT VecInVT;
5182   SmallVector<int, 8> Mask;
5183   EVT SrcVT = MVT::Other;
5184
5185   // Check the patterns could be translated into X86vfpext.
5186   for (unsigned i = 0; i < NumElts; ++i) {
5187     SDValue In = N->getOperand(i);
5188     unsigned Opcode = In.getOpcode();
5189
5190     // Skip if the element is undefined.
5191     if (Opcode == ISD::UNDEF) {
5192       Mask.push_back(-1);
5193       continue;
5194     }
5195
5196     // Quit if one of the elements is not defined from 'fpext'.
5197     if (Opcode != ISD::FP_EXTEND)
5198       return SDValue();
5199
5200     // Check how the source of 'fpext' is defined.
5201     SDValue L2In = In.getOperand(0);
5202     EVT L2InVT = L2In.getValueType();
5203
5204     // Check the original type
5205     if (SrcVT == MVT::Other)
5206       SrcVT = L2InVT;
5207     else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5208       return SDValue();
5209
5210     // Check whether the value being 'fpext'ed is extracted from the same
5211     // source.
5212     Opcode = L2In.getOpcode();
5213
5214     // Quit if it's not extracted with a constant index.
5215     if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5216         !isa<ConstantSDNode>(L2In.getOperand(1)))
5217       return SDValue();
5218
5219     SDValue ExtractedFromVec = L2In.getOperand(0);
5220
5221     if (VecIn.getNode() == 0) {
5222       VecIn = ExtractedFromVec;
5223       VecInVT = ExtractedFromVec.getValueType();
5224     } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5225       return SDValue();
5226
5227     Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5228   }
5229
5230   // Quit if all operands of BUILD_VECTOR are undefined.
5231   if (!VecIn.getNode())
5232     return SDValue();
5233
5234   // Fill the remaining mask as undef.
5235   for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5236     Mask.push_back(-1);
5237
5238   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5239                      DAG.getVectorShuffle(VecInVT, DL,
5240                                           VecIn, DAG.getUNDEF(VecInVT),
5241                                           &Mask[0]));
5242 }
5243
5244 SDValue
5245 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5246   DebugLoc dl = Op.getDebugLoc();
5247
5248   EVT VT = Op.getValueType();
5249   EVT ExtVT = VT.getVectorElementType();
5250   unsigned NumElems = Op.getNumOperands();
5251
5252   // Vectors containing all zeros can be matched by pxor and xorps later
5253   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5254     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5255     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5256     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5257       return Op;
5258
5259     return getZeroVector(VT, Subtarget, DAG, dl);
5260   }
5261
5262   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5263   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5264   // vpcmpeqd on 256-bit vectors.
5265   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5266     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5267       return Op;
5268
5269     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5270   }
5271
5272   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5273   if (Broadcast.getNode())
5274     return Broadcast;
5275
5276   SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5277   if (FpExt.getNode())
5278     return FpExt;
5279
5280   unsigned EVTBits = ExtVT.getSizeInBits();
5281
5282   unsigned NumZero  = 0;
5283   unsigned NumNonZero = 0;
5284   unsigned NonZeros = 0;
5285   bool IsAllConstants = true;
5286   SmallSet<SDValue, 8> Values;
5287   for (unsigned i = 0; i < NumElems; ++i) {
5288     SDValue Elt = Op.getOperand(i);
5289     if (Elt.getOpcode() == ISD::UNDEF)
5290       continue;
5291     Values.insert(Elt);
5292     if (Elt.getOpcode() != ISD::Constant &&
5293         Elt.getOpcode() != ISD::ConstantFP)
5294       IsAllConstants = false;
5295     if (X86::isZeroNode(Elt))
5296       NumZero++;
5297     else {
5298       NonZeros |= (1 << i);
5299       NumNonZero++;
5300     }
5301   }
5302
5303   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5304   if (NumNonZero == 0)
5305     return DAG.getUNDEF(VT);
5306
5307   // Special case for single non-zero, non-undef, element.
5308   if (NumNonZero == 1) {
5309     unsigned Idx = CountTrailingZeros_32(NonZeros);
5310     SDValue Item = Op.getOperand(Idx);
5311
5312     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5313     // the value are obviously zero, truncate the value to i32 and do the
5314     // insertion that way.  Only do this if the value is non-constant or if the
5315     // value is a constant being inserted into element 0.  It is cheaper to do
5316     // a constant pool load than it is to do a movd + shuffle.
5317     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5318         (!IsAllConstants || Idx == 0)) {
5319       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5320         // Handle SSE only.
5321         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5322         EVT VecVT = MVT::v4i32;
5323         unsigned VecElts = 4;
5324
5325         // Truncate the value (which may itself be a constant) to i32, and
5326         // convert it to a vector with movd (S2V+shuffle to zero extend).
5327         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5328         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5329         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5330
5331         // Now we have our 32-bit value zero extended in the low element of
5332         // a vector.  If Idx != 0, swizzle it into place.
5333         if (Idx != 0) {
5334           SmallVector<int, 4> Mask;
5335           Mask.push_back(Idx);
5336           for (unsigned i = 1; i != VecElts; ++i)
5337             Mask.push_back(i);
5338           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5339                                       &Mask[0]);
5340         }
5341         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5342       }
5343     }
5344
5345     // If we have a constant or non-constant insertion into the low element of
5346     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5347     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5348     // depending on what the source datatype is.
5349     if (Idx == 0) {
5350       if (NumZero == 0)
5351         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5352
5353       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5354           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5355         if (VT.is256BitVector()) {
5356           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5357           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5358                              Item, DAG.getIntPtrConstant(0));
5359         }
5360         assert(VT.is128BitVector() && "Expected an SSE value type!");
5361         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5362         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5363         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5364       }
5365
5366       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5367         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5368         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5369         if (VT.is256BitVector()) {
5370           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5371           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5372         } else {
5373           assert(VT.is128BitVector() && "Expected an SSE value type!");
5374           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5375         }
5376         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5377       }
5378     }
5379
5380     // Is it a vector logical left shift?
5381     if (NumElems == 2 && Idx == 1 &&
5382         X86::isZeroNode(Op.getOperand(0)) &&
5383         !X86::isZeroNode(Op.getOperand(1))) {
5384       unsigned NumBits = VT.getSizeInBits();
5385       return getVShift(true, VT,
5386                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5387                                    VT, Op.getOperand(1)),
5388                        NumBits/2, DAG, *this, dl);
5389     }
5390
5391     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5392       return SDValue();
5393
5394     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5395     // is a non-constant being inserted into an element other than the low one,
5396     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5397     // movd/movss) to move this into the low element, then shuffle it into
5398     // place.
5399     if (EVTBits == 32) {
5400       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5401
5402       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5403       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5404       SmallVector<int, 8> MaskVec;
5405       for (unsigned i = 0; i != NumElems; ++i)
5406         MaskVec.push_back(i == Idx ? 0 : 1);
5407       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5408     }
5409   }
5410
5411   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5412   if (Values.size() == 1) {
5413     if (EVTBits == 32) {
5414       // Instead of a shuffle like this:
5415       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5416       // Check if it's possible to issue this instead.
5417       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5418       unsigned Idx = CountTrailingZeros_32(NonZeros);
5419       SDValue Item = Op.getOperand(Idx);
5420       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5421         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5422     }
5423     return SDValue();
5424   }
5425
5426   // A vector full of immediates; various special cases are already
5427   // handled, so this is best done with a single constant-pool load.
5428   if (IsAllConstants)
5429     return SDValue();
5430
5431   // For AVX-length vectors, build the individual 128-bit pieces and use
5432   // shuffles to put them in place.
5433   if (VT.is256BitVector()) {
5434     SmallVector<SDValue, 32> V;
5435     for (unsigned i = 0; i != NumElems; ++i)
5436       V.push_back(Op.getOperand(i));
5437
5438     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5439
5440     // Build both the lower and upper subvector.
5441     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5442     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5443                                 NumElems/2);
5444
5445     // Recreate the wider vector with the lower and upper part.
5446     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5447   }
5448
5449   // Let legalizer expand 2-wide build_vectors.
5450   if (EVTBits == 64) {
5451     if (NumNonZero == 1) {
5452       // One half is zero or undef.
5453       unsigned Idx = CountTrailingZeros_32(NonZeros);
5454       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5455                                  Op.getOperand(Idx));
5456       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5457     }
5458     return SDValue();
5459   }
5460
5461   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5462   if (EVTBits == 8 && NumElems == 16) {
5463     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5464                                         Subtarget, *this);
5465     if (V.getNode()) return V;
5466   }
5467
5468   if (EVTBits == 16 && NumElems == 8) {
5469     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5470                                       Subtarget, *this);
5471     if (V.getNode()) return V;
5472   }
5473
5474   // If element VT is == 32 bits, turn it into a number of shuffles.
5475   SmallVector<SDValue, 8> V(NumElems);
5476   if (NumElems == 4 && NumZero > 0) {
5477     for (unsigned i = 0; i < 4; ++i) {
5478       bool isZero = !(NonZeros & (1 << i));
5479       if (isZero)
5480         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5481       else
5482         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5483     }
5484
5485     for (unsigned i = 0; i < 2; ++i) {
5486       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5487         default: break;
5488         case 0:
5489           V[i] = V[i*2];  // Must be a zero vector.
5490           break;
5491         case 1:
5492           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5493           break;
5494         case 2:
5495           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5496           break;
5497         case 3:
5498           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5499           break;
5500       }
5501     }
5502
5503     bool Reverse1 = (NonZeros & 0x3) == 2;
5504     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5505     int MaskVec[] = {
5506       Reverse1 ? 1 : 0,
5507       Reverse1 ? 0 : 1,
5508       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5509       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5510     };
5511     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5512   }
5513
5514   if (Values.size() > 1 && VT.is128BitVector()) {
5515     // Check for a build vector of consecutive loads.
5516     for (unsigned i = 0; i < NumElems; ++i)
5517       V[i] = Op.getOperand(i);
5518
5519     // Check for elements which are consecutive loads.
5520     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5521     if (LD.getNode())
5522       return LD;
5523
5524     // For SSE 4.1, use insertps to put the high elements into the low element.
5525     if (getSubtarget()->hasSSE41()) {
5526       SDValue Result;
5527       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5528         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5529       else
5530         Result = DAG.getUNDEF(VT);
5531
5532       for (unsigned i = 1; i < NumElems; ++i) {
5533         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5534         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5535                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5536       }
5537       return Result;
5538     }
5539
5540     // Otherwise, expand into a number of unpckl*, start by extending each of
5541     // our (non-undef) elements to the full vector width with the element in the
5542     // bottom slot of the vector (which generates no code for SSE).
5543     for (unsigned i = 0; i < NumElems; ++i) {
5544       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5545         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5546       else
5547         V[i] = DAG.getUNDEF(VT);
5548     }
5549
5550     // Next, we iteratively mix elements, e.g. for v4f32:
5551     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5552     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5553     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5554     unsigned EltStride = NumElems >> 1;
5555     while (EltStride != 0) {
5556       for (unsigned i = 0; i < EltStride; ++i) {
5557         // If V[i+EltStride] is undef and this is the first round of mixing,
5558         // then it is safe to just drop this shuffle: V[i] is already in the
5559         // right place, the one element (since it's the first round) being
5560         // inserted as undef can be dropped.  This isn't safe for successive
5561         // rounds because they will permute elements within both vectors.
5562         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5563             EltStride == NumElems/2)
5564           continue;
5565
5566         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5567       }
5568       EltStride >>= 1;
5569     }
5570     return V[0];
5571   }
5572   return SDValue();
5573 }
5574
5575 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5576 // to create 256-bit vectors from two other 128-bit ones.
5577 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5578   DebugLoc dl = Op.getDebugLoc();
5579   EVT ResVT = Op.getValueType();
5580
5581   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5582
5583   SDValue V1 = Op.getOperand(0);
5584   SDValue V2 = Op.getOperand(1);
5585   unsigned NumElems = ResVT.getVectorNumElements();
5586
5587   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5588 }
5589
5590 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5591   assert(Op.getNumOperands() == 2);
5592
5593   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5594   // from two other 128-bit ones.
5595   return LowerAVXCONCAT_VECTORS(Op, DAG);
5596 }
5597
5598 // Try to lower a shuffle node into a simple blend instruction.
5599 static SDValue
5600 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5601                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5602   SDValue V1 = SVOp->getOperand(0);
5603   SDValue V2 = SVOp->getOperand(1);
5604   DebugLoc dl = SVOp->getDebugLoc();
5605   MVT VT = SVOp->getValueType(0).getSimpleVT();
5606   unsigned NumElems = VT.getVectorNumElements();
5607
5608   if (!Subtarget->hasSSE41())
5609     return SDValue();
5610
5611   unsigned ISDNo = 0;
5612   MVT OpTy;
5613
5614   switch (VT.SimpleTy) {
5615   default: return SDValue();
5616   case MVT::v8i16:
5617     ISDNo = X86ISD::BLENDPW;
5618     OpTy = MVT::v8i16;
5619     break;
5620   case MVT::v4i32:
5621   case MVT::v4f32:
5622     ISDNo = X86ISD::BLENDPS;
5623     OpTy = MVT::v4f32;
5624     break;
5625   case MVT::v2i64:
5626   case MVT::v2f64:
5627     ISDNo = X86ISD::BLENDPD;
5628     OpTy = MVT::v2f64;
5629     break;
5630   case MVT::v8i32:
5631   case MVT::v8f32:
5632     if (!Subtarget->hasAVX())
5633       return SDValue();
5634     ISDNo = X86ISD::BLENDPS;
5635     OpTy = MVT::v8f32;
5636     break;
5637   case MVT::v4i64:
5638   case MVT::v4f64:
5639     if (!Subtarget->hasAVX())
5640       return SDValue();
5641     ISDNo = X86ISD::BLENDPD;
5642     OpTy = MVT::v4f64;
5643     break;
5644   }
5645   assert(ISDNo && "Invalid Op Number");
5646
5647   unsigned MaskVals = 0;
5648
5649   for (unsigned i = 0; i != NumElems; ++i) {
5650     int EltIdx = SVOp->getMaskElt(i);
5651     if (EltIdx == (int)i || EltIdx < 0)
5652       MaskVals |= (1<<i);
5653     else if (EltIdx == (int)(i + NumElems))
5654       continue; // Bit is set to zero;
5655     else
5656       return SDValue();
5657   }
5658
5659   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5660   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5661   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5662                              DAG.getConstant(MaskVals, MVT::i32));
5663   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5664 }
5665
5666 // v8i16 shuffles - Prefer shuffles in the following order:
5667 // 1. [all]   pshuflw, pshufhw, optional move
5668 // 2. [ssse3] 1 x pshufb
5669 // 3. [ssse3] 2 x pshufb + 1 x por
5670 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5671 static SDValue
5672 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5673                          SelectionDAG &DAG) {
5674   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5675   SDValue V1 = SVOp->getOperand(0);
5676   SDValue V2 = SVOp->getOperand(1);
5677   DebugLoc dl = SVOp->getDebugLoc();
5678   SmallVector<int, 8> MaskVals;
5679
5680   // Determine if more than 1 of the words in each of the low and high quadwords
5681   // of the result come from the same quadword of one of the two inputs.  Undef
5682   // mask values count as coming from any quadword, for better codegen.
5683   unsigned LoQuad[] = { 0, 0, 0, 0 };
5684   unsigned HiQuad[] = { 0, 0, 0, 0 };
5685   std::bitset<4> InputQuads;
5686   for (unsigned i = 0; i < 8; ++i) {
5687     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5688     int EltIdx = SVOp->getMaskElt(i);
5689     MaskVals.push_back(EltIdx);
5690     if (EltIdx < 0) {
5691       ++Quad[0];
5692       ++Quad[1];
5693       ++Quad[2];
5694       ++Quad[3];
5695       continue;
5696     }
5697     ++Quad[EltIdx / 4];
5698     InputQuads.set(EltIdx / 4);
5699   }
5700
5701   int BestLoQuad = -1;
5702   unsigned MaxQuad = 1;
5703   for (unsigned i = 0; i < 4; ++i) {
5704     if (LoQuad[i] > MaxQuad) {
5705       BestLoQuad = i;
5706       MaxQuad = LoQuad[i];
5707     }
5708   }
5709
5710   int BestHiQuad = -1;
5711   MaxQuad = 1;
5712   for (unsigned i = 0; i < 4; ++i) {
5713     if (HiQuad[i] > MaxQuad) {
5714       BestHiQuad = i;
5715       MaxQuad = HiQuad[i];
5716     }
5717   }
5718
5719   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5720   // of the two input vectors, shuffle them into one input vector so only a
5721   // single pshufb instruction is necessary. If There are more than 2 input
5722   // quads, disable the next transformation since it does not help SSSE3.
5723   bool V1Used = InputQuads[0] || InputQuads[1];
5724   bool V2Used = InputQuads[2] || InputQuads[3];
5725   if (Subtarget->hasSSSE3()) {
5726     if (InputQuads.count() == 2 && V1Used && V2Used) {
5727       BestLoQuad = InputQuads[0] ? 0 : 1;
5728       BestHiQuad = InputQuads[2] ? 2 : 3;
5729     }
5730     if (InputQuads.count() > 2) {
5731       BestLoQuad = -1;
5732       BestHiQuad = -1;
5733     }
5734   }
5735
5736   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5737   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5738   // words from all 4 input quadwords.
5739   SDValue NewV;
5740   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5741     int MaskV[] = {
5742       BestLoQuad < 0 ? 0 : BestLoQuad,
5743       BestHiQuad < 0 ? 1 : BestHiQuad
5744     };
5745     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5746                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5747                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5748     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5749
5750     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5751     // source words for the shuffle, to aid later transformations.
5752     bool AllWordsInNewV = true;
5753     bool InOrder[2] = { true, true };
5754     for (unsigned i = 0; i != 8; ++i) {
5755       int idx = MaskVals[i];
5756       if (idx != (int)i)
5757         InOrder[i/4] = false;
5758       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5759         continue;
5760       AllWordsInNewV = false;
5761       break;
5762     }
5763
5764     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5765     if (AllWordsInNewV) {
5766       for (int i = 0; i != 8; ++i) {
5767         int idx = MaskVals[i];
5768         if (idx < 0)
5769           continue;
5770         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5771         if ((idx != i) && idx < 4)
5772           pshufhw = false;
5773         if ((idx != i) && idx > 3)
5774           pshuflw = false;
5775       }
5776       V1 = NewV;
5777       V2Used = false;
5778       BestLoQuad = 0;
5779       BestHiQuad = 1;
5780     }
5781
5782     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5783     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5784     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5785       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5786       unsigned TargetMask = 0;
5787       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5788                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5789       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5790       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5791                              getShufflePSHUFLWImmediate(SVOp);
5792       V1 = NewV.getOperand(0);
5793       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5794     }
5795   }
5796
5797   // If we have SSSE3, and all words of the result are from 1 input vector,
5798   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5799   // is present, fall back to case 4.
5800   if (Subtarget->hasSSSE3()) {
5801     SmallVector<SDValue,16> pshufbMask;
5802
5803     // If we have elements from both input vectors, set the high bit of the
5804     // shuffle mask element to zero out elements that come from V2 in the V1
5805     // mask, and elements that come from V1 in the V2 mask, so that the two
5806     // results can be OR'd together.
5807     bool TwoInputs = V1Used && V2Used;
5808     for (unsigned i = 0; i != 8; ++i) {
5809       int EltIdx = MaskVals[i] * 2;
5810       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5811       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5812       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5813       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5814     }
5815     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5816     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5817                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5818                                  MVT::v16i8, &pshufbMask[0], 16));
5819     if (!TwoInputs)
5820       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5821
5822     // Calculate the shuffle mask for the second input, shuffle it, and
5823     // OR it with the first shuffled input.
5824     pshufbMask.clear();
5825     for (unsigned i = 0; i != 8; ++i) {
5826       int EltIdx = MaskVals[i] * 2;
5827       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5828       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5829       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5830       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5831     }
5832     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5833     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5834                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5835                                  MVT::v16i8, &pshufbMask[0], 16));
5836     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5837     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5838   }
5839
5840   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5841   // and update MaskVals with new element order.
5842   std::bitset<8> InOrder;
5843   if (BestLoQuad >= 0) {
5844     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5845     for (int i = 0; i != 4; ++i) {
5846       int idx = MaskVals[i];
5847       if (idx < 0) {
5848         InOrder.set(i);
5849       } else if ((idx / 4) == BestLoQuad) {
5850         MaskV[i] = idx & 3;
5851         InOrder.set(i);
5852       }
5853     }
5854     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5855                                 &MaskV[0]);
5856
5857     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5858       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5859       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5860                                   NewV.getOperand(0),
5861                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5862     }
5863   }
5864
5865   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5866   // and update MaskVals with the new element order.
5867   if (BestHiQuad >= 0) {
5868     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5869     for (unsigned i = 4; i != 8; ++i) {
5870       int idx = MaskVals[i];
5871       if (idx < 0) {
5872         InOrder.set(i);
5873       } else if ((idx / 4) == BestHiQuad) {
5874         MaskV[i] = (idx & 3) + 4;
5875         InOrder.set(i);
5876       }
5877     }
5878     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5879                                 &MaskV[0]);
5880
5881     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5882       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5883       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5884                                   NewV.getOperand(0),
5885                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5886     }
5887   }
5888
5889   // In case BestHi & BestLo were both -1, which means each quadword has a word
5890   // from each of the four input quadwords, calculate the InOrder bitvector now
5891   // before falling through to the insert/extract cleanup.
5892   if (BestLoQuad == -1 && BestHiQuad == -1) {
5893     NewV = V1;
5894     for (int i = 0; i != 8; ++i)
5895       if (MaskVals[i] < 0 || MaskVals[i] == i)
5896         InOrder.set(i);
5897   }
5898
5899   // The other elements are put in the right place using pextrw and pinsrw.
5900   for (unsigned i = 0; i != 8; ++i) {
5901     if (InOrder[i])
5902       continue;
5903     int EltIdx = MaskVals[i];
5904     if (EltIdx < 0)
5905       continue;
5906     SDValue ExtOp = (EltIdx < 8) ?
5907       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5908                   DAG.getIntPtrConstant(EltIdx)) :
5909       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5910                   DAG.getIntPtrConstant(EltIdx - 8));
5911     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5912                        DAG.getIntPtrConstant(i));
5913   }
5914   return NewV;
5915 }
5916
5917 // v16i8 shuffles - Prefer shuffles in the following order:
5918 // 1. [ssse3] 1 x pshufb
5919 // 2. [ssse3] 2 x pshufb + 1 x por
5920 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5921 static
5922 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5923                                  SelectionDAG &DAG,
5924                                  const X86TargetLowering &TLI) {
5925   SDValue V1 = SVOp->getOperand(0);
5926   SDValue V2 = SVOp->getOperand(1);
5927   DebugLoc dl = SVOp->getDebugLoc();
5928   ArrayRef<int> MaskVals = SVOp->getMask();
5929
5930   // If we have SSSE3, case 1 is generated when all result bytes come from
5931   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5932   // present, fall back to case 3.
5933
5934   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5935   if (TLI.getSubtarget()->hasSSSE3()) {
5936     SmallVector<SDValue,16> pshufbMask;
5937
5938     // If all result elements are from one input vector, then only translate
5939     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5940     //
5941     // Otherwise, we have elements from both input vectors, and must zero out
5942     // elements that come from V2 in the first mask, and V1 in the second mask
5943     // so that we can OR them together.
5944     for (unsigned i = 0; i != 16; ++i) {
5945       int EltIdx = MaskVals[i];
5946       if (EltIdx < 0 || EltIdx >= 16)
5947         EltIdx = 0x80;
5948       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5949     }
5950     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5951                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5952                                  MVT::v16i8, &pshufbMask[0], 16));
5953
5954     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5955     // the 2nd operand if it's undefined or zero.
5956     if (V2.getOpcode() == ISD::UNDEF ||
5957         ISD::isBuildVectorAllZeros(V2.getNode()))
5958       return V1;
5959
5960     // Calculate the shuffle mask for the second input, shuffle it, and
5961     // OR it with the first shuffled input.
5962     pshufbMask.clear();
5963     for (unsigned i = 0; i != 16; ++i) {
5964       int EltIdx = MaskVals[i];
5965       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5966       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5967     }
5968     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5969                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5970                                  MVT::v16i8, &pshufbMask[0], 16));
5971     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5972   }
5973
5974   // No SSSE3 - Calculate in place words and then fix all out of place words
5975   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5976   // the 16 different words that comprise the two doublequadword input vectors.
5977   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5978   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5979   SDValue NewV = V1;
5980   for (int i = 0; i != 8; ++i) {
5981     int Elt0 = MaskVals[i*2];
5982     int Elt1 = MaskVals[i*2+1];
5983
5984     // This word of the result is all undef, skip it.
5985     if (Elt0 < 0 && Elt1 < 0)
5986       continue;
5987
5988     // This word of the result is already in the correct place, skip it.
5989     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5990       continue;
5991
5992     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5993     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5994     SDValue InsElt;
5995
5996     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5997     // using a single extract together, load it and store it.
5998     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5999       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6000                            DAG.getIntPtrConstant(Elt1 / 2));
6001       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6002                         DAG.getIntPtrConstant(i));
6003       continue;
6004     }
6005
6006     // If Elt1 is defined, extract it from the appropriate source.  If the
6007     // source byte is not also odd, shift the extracted word left 8 bits
6008     // otherwise clear the bottom 8 bits if we need to do an or.
6009     if (Elt1 >= 0) {
6010       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6011                            DAG.getIntPtrConstant(Elt1 / 2));
6012       if ((Elt1 & 1) == 0)
6013         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6014                              DAG.getConstant(8,
6015                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6016       else if (Elt0 >= 0)
6017         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6018                              DAG.getConstant(0xFF00, MVT::i16));
6019     }
6020     // If Elt0 is defined, extract it from the appropriate source.  If the
6021     // source byte is not also even, shift the extracted word right 8 bits. If
6022     // Elt1 was also defined, OR the extracted values together before
6023     // inserting them in the result.
6024     if (Elt0 >= 0) {
6025       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6026                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6027       if ((Elt0 & 1) != 0)
6028         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6029                               DAG.getConstant(8,
6030                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6031       else if (Elt1 >= 0)
6032         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6033                              DAG.getConstant(0x00FF, MVT::i16));
6034       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6035                          : InsElt0;
6036     }
6037     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6038                        DAG.getIntPtrConstant(i));
6039   }
6040   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6041 }
6042
6043 // v32i8 shuffles - Translate to VPSHUFB if possible.
6044 static
6045 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6046                                  const X86Subtarget *Subtarget,
6047                                  SelectionDAG &DAG) {
6048   EVT VT = SVOp->getValueType(0);
6049   SDValue V1 = SVOp->getOperand(0);
6050   SDValue V2 = SVOp->getOperand(1);
6051   DebugLoc dl = SVOp->getDebugLoc();
6052   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6053
6054   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6055   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6056   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6057
6058   // VPSHUFB may be generated if
6059   // (1) one of input vector is undefined or zeroinitializer.
6060   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6061   // And (2) the mask indexes don't cross the 128-bit lane.
6062   if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6063       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6064     return SDValue();
6065
6066   if (V1IsAllZero && !V2IsAllZero) {
6067     CommuteVectorShuffleMask(MaskVals, 32);
6068     V1 = V2;
6069   }
6070   SmallVector<SDValue, 32> pshufbMask;
6071   for (unsigned i = 0; i != 32; i++) {
6072     int EltIdx = MaskVals[i];
6073     if (EltIdx < 0 || EltIdx >= 32)
6074       EltIdx = 0x80;
6075     else {
6076       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6077         // Cross lane is not allowed.
6078         return SDValue();
6079       EltIdx &= 0xf;
6080     }
6081     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6082   }
6083   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6084                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6085                                   MVT::v32i8, &pshufbMask[0], 32));
6086 }
6087
6088 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6089 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6090 /// done when every pair / quad of shuffle mask elements point to elements in
6091 /// the right sequence. e.g.
6092 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6093 static
6094 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6095                                  SelectionDAG &DAG, DebugLoc dl) {
6096   MVT VT = SVOp->getValueType(0).getSimpleVT();
6097   unsigned NumElems = VT.getVectorNumElements();
6098   MVT NewVT;
6099   unsigned Scale;
6100   switch (VT.SimpleTy) {
6101   default: llvm_unreachable("Unexpected!");
6102   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6103   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6104   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6105   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6106   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6107   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6108   }
6109
6110   SmallVector<int, 8> MaskVec;
6111   for (unsigned i = 0; i != NumElems; i += Scale) {
6112     int StartIdx = -1;
6113     for (unsigned j = 0; j != Scale; ++j) {
6114       int EltIdx = SVOp->getMaskElt(i+j);
6115       if (EltIdx < 0)
6116         continue;
6117       if (StartIdx < 0)
6118         StartIdx = (EltIdx / Scale);
6119       if (EltIdx != (int)(StartIdx*Scale + j))
6120         return SDValue();
6121     }
6122     MaskVec.push_back(StartIdx);
6123   }
6124
6125   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6126   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6127   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6128 }
6129
6130 /// getVZextMovL - Return a zero-extending vector move low node.
6131 ///
6132 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6133                             SDValue SrcOp, SelectionDAG &DAG,
6134                             const X86Subtarget *Subtarget, DebugLoc dl) {
6135   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6136     LoadSDNode *LD = NULL;
6137     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6138       LD = dyn_cast<LoadSDNode>(SrcOp);
6139     if (!LD) {
6140       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6141       // instead.
6142       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6143       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6144           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6145           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6146           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6147         // PR2108
6148         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6149         return DAG.getNode(ISD::BITCAST, dl, VT,
6150                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6151                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6152                                                    OpVT,
6153                                                    SrcOp.getOperand(0)
6154                                                           .getOperand(0))));
6155       }
6156     }
6157   }
6158
6159   return DAG.getNode(ISD::BITCAST, dl, VT,
6160                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6161                                  DAG.getNode(ISD::BITCAST, dl,
6162                                              OpVT, SrcOp)));
6163 }
6164
6165 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6166 /// which could not be matched by any known target speficic shuffle
6167 static SDValue
6168 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6169
6170   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6171   if (NewOp.getNode())
6172     return NewOp;
6173
6174   EVT VT = SVOp->getValueType(0);
6175
6176   unsigned NumElems = VT.getVectorNumElements();
6177   unsigned NumLaneElems = NumElems / 2;
6178
6179   DebugLoc dl = SVOp->getDebugLoc();
6180   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6181   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6182   SDValue Output[2];
6183
6184   SmallVector<int, 16> Mask;
6185   for (unsigned l = 0; l < 2; ++l) {
6186     // Build a shuffle mask for the output, discovering on the fly which
6187     // input vectors to use as shuffle operands (recorded in InputUsed).
6188     // If building a suitable shuffle vector proves too hard, then bail
6189     // out with UseBuildVector set.
6190     bool UseBuildVector = false;
6191     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6192     unsigned LaneStart = l * NumLaneElems;
6193     for (unsigned i = 0; i != NumLaneElems; ++i) {
6194       // The mask element.  This indexes into the input.
6195       int Idx = SVOp->getMaskElt(i+LaneStart);
6196       if (Idx < 0) {
6197         // the mask element does not index into any input vector.
6198         Mask.push_back(-1);
6199         continue;
6200       }
6201
6202       // The input vector this mask element indexes into.
6203       int Input = Idx / NumLaneElems;
6204
6205       // Turn the index into an offset from the start of the input vector.
6206       Idx -= Input * NumLaneElems;
6207
6208       // Find or create a shuffle vector operand to hold this input.
6209       unsigned OpNo;
6210       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6211         if (InputUsed[OpNo] == Input)
6212           // This input vector is already an operand.
6213           break;
6214         if (InputUsed[OpNo] < 0) {
6215           // Create a new operand for this input vector.
6216           InputUsed[OpNo] = Input;
6217           break;
6218         }
6219       }
6220
6221       if (OpNo >= array_lengthof(InputUsed)) {
6222         // More than two input vectors used!  Give up on trying to create a
6223         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6224         UseBuildVector = true;
6225         break;
6226       }
6227
6228       // Add the mask index for the new shuffle vector.
6229       Mask.push_back(Idx + OpNo * NumLaneElems);
6230     }
6231
6232     if (UseBuildVector) {
6233       SmallVector<SDValue, 16> SVOps;
6234       for (unsigned i = 0; i != NumLaneElems; ++i) {
6235         // The mask element.  This indexes into the input.
6236         int Idx = SVOp->getMaskElt(i+LaneStart);
6237         if (Idx < 0) {
6238           SVOps.push_back(DAG.getUNDEF(EltVT));
6239           continue;
6240         }
6241
6242         // The input vector this mask element indexes into.
6243         int Input = Idx / NumElems;
6244
6245         // Turn the index into an offset from the start of the input vector.
6246         Idx -= Input * NumElems;
6247
6248         // Extract the vector element by hand.
6249         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6250                                     SVOp->getOperand(Input),
6251                                     DAG.getIntPtrConstant(Idx)));
6252       }
6253
6254       // Construct the output using a BUILD_VECTOR.
6255       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6256                               SVOps.size());
6257     } else if (InputUsed[0] < 0) {
6258       // No input vectors were used! The result is undefined.
6259       Output[l] = DAG.getUNDEF(NVT);
6260     } else {
6261       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6262                                         (InputUsed[0] % 2) * NumLaneElems,
6263                                         DAG, dl);
6264       // If only one input was used, use an undefined vector for the other.
6265       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6266         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6267                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6268       // At least one input vector was used. Create a new shuffle vector.
6269       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6270     }
6271
6272     Mask.clear();
6273   }
6274
6275   // Concatenate the result back
6276   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6277 }
6278
6279 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6280 /// 4 elements, and match them with several different shuffle types.
6281 static SDValue
6282 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6283   SDValue V1 = SVOp->getOperand(0);
6284   SDValue V2 = SVOp->getOperand(1);
6285   DebugLoc dl = SVOp->getDebugLoc();
6286   EVT VT = SVOp->getValueType(0);
6287
6288   assert(VT.is128BitVector() && "Unsupported vector size");
6289
6290   std::pair<int, int> Locs[4];
6291   int Mask1[] = { -1, -1, -1, -1 };
6292   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6293
6294   unsigned NumHi = 0;
6295   unsigned NumLo = 0;
6296   for (unsigned i = 0; i != 4; ++i) {
6297     int Idx = PermMask[i];
6298     if (Idx < 0) {
6299       Locs[i] = std::make_pair(-1, -1);
6300     } else {
6301       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6302       if (Idx < 4) {
6303         Locs[i] = std::make_pair(0, NumLo);
6304         Mask1[NumLo] = Idx;
6305         NumLo++;
6306       } else {
6307         Locs[i] = std::make_pair(1, NumHi);
6308         if (2+NumHi < 4)
6309           Mask1[2+NumHi] = Idx;
6310         NumHi++;
6311       }
6312     }
6313   }
6314
6315   if (NumLo <= 2 && NumHi <= 2) {
6316     // If no more than two elements come from either vector. This can be
6317     // implemented with two shuffles. First shuffle gather the elements.
6318     // The second shuffle, which takes the first shuffle as both of its
6319     // vector operands, put the elements into the right order.
6320     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6321
6322     int Mask2[] = { -1, -1, -1, -1 };
6323
6324     for (unsigned i = 0; i != 4; ++i)
6325       if (Locs[i].first != -1) {
6326         unsigned Idx = (i < 2) ? 0 : 4;
6327         Idx += Locs[i].first * 2 + Locs[i].second;
6328         Mask2[i] = Idx;
6329       }
6330
6331     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6332   }
6333
6334   if (NumLo == 3 || NumHi == 3) {
6335     // Otherwise, we must have three elements from one vector, call it X, and
6336     // one element from the other, call it Y.  First, use a shufps to build an
6337     // intermediate vector with the one element from Y and the element from X
6338     // that will be in the same half in the final destination (the indexes don't
6339     // matter). Then, use a shufps to build the final vector, taking the half
6340     // containing the element from Y from the intermediate, and the other half
6341     // from X.
6342     if (NumHi == 3) {
6343       // Normalize it so the 3 elements come from V1.
6344       CommuteVectorShuffleMask(PermMask, 4);
6345       std::swap(V1, V2);
6346     }
6347
6348     // Find the element from V2.
6349     unsigned HiIndex;
6350     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6351       int Val = PermMask[HiIndex];
6352       if (Val < 0)
6353         continue;
6354       if (Val >= 4)
6355         break;
6356     }
6357
6358     Mask1[0] = PermMask[HiIndex];
6359     Mask1[1] = -1;
6360     Mask1[2] = PermMask[HiIndex^1];
6361     Mask1[3] = -1;
6362     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6363
6364     if (HiIndex >= 2) {
6365       Mask1[0] = PermMask[0];
6366       Mask1[1] = PermMask[1];
6367       Mask1[2] = HiIndex & 1 ? 6 : 4;
6368       Mask1[3] = HiIndex & 1 ? 4 : 6;
6369       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6370     }
6371
6372     Mask1[0] = HiIndex & 1 ? 2 : 0;
6373     Mask1[1] = HiIndex & 1 ? 0 : 2;
6374     Mask1[2] = PermMask[2];
6375     Mask1[3] = PermMask[3];
6376     if (Mask1[2] >= 0)
6377       Mask1[2] += 4;
6378     if (Mask1[3] >= 0)
6379       Mask1[3] += 4;
6380     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6381   }
6382
6383   // Break it into (shuffle shuffle_hi, shuffle_lo).
6384   int LoMask[] = { -1, -1, -1, -1 };
6385   int HiMask[] = { -1, -1, -1, -1 };
6386
6387   int *MaskPtr = LoMask;
6388   unsigned MaskIdx = 0;
6389   unsigned LoIdx = 0;
6390   unsigned HiIdx = 2;
6391   for (unsigned i = 0; i != 4; ++i) {
6392     if (i == 2) {
6393       MaskPtr = HiMask;
6394       MaskIdx = 1;
6395       LoIdx = 0;
6396       HiIdx = 2;
6397     }
6398     int Idx = PermMask[i];
6399     if (Idx < 0) {
6400       Locs[i] = std::make_pair(-1, -1);
6401     } else if (Idx < 4) {
6402       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6403       MaskPtr[LoIdx] = Idx;
6404       LoIdx++;
6405     } else {
6406       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6407       MaskPtr[HiIdx] = Idx;
6408       HiIdx++;
6409     }
6410   }
6411
6412   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6413   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6414   int MaskOps[] = { -1, -1, -1, -1 };
6415   for (unsigned i = 0; i != 4; ++i)
6416     if (Locs[i].first != -1)
6417       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6418   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6419 }
6420
6421 static bool MayFoldVectorLoad(SDValue V) {
6422   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6423     V = V.getOperand(0);
6424   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6425     V = V.getOperand(0);
6426   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6427       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6428     // BUILD_VECTOR (load), undef
6429     V = V.getOperand(0);
6430   if (MayFoldLoad(V))
6431     return true;
6432   return false;
6433 }
6434
6435 // FIXME: the version above should always be used. Since there's
6436 // a bug where several vector shuffles can't be folded because the
6437 // DAG is not updated during lowering and a node claims to have two
6438 // uses while it only has one, use this version, and let isel match
6439 // another instruction if the load really happens to have more than
6440 // one use. Remove this version after this bug get fixed.
6441 // rdar://8434668, PR8156
6442 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6443   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6444     V = V.getOperand(0);
6445   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6446     V = V.getOperand(0);
6447   if (ISD::isNormalLoad(V.getNode()))
6448     return true;
6449   return false;
6450 }
6451
6452 static
6453 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6454   EVT VT = Op.getValueType();
6455
6456   // Canonizalize to v2f64.
6457   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6458   return DAG.getNode(ISD::BITCAST, dl, VT,
6459                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6460                                           V1, DAG));
6461 }
6462
6463 static
6464 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6465                         bool HasSSE2) {
6466   SDValue V1 = Op.getOperand(0);
6467   SDValue V2 = Op.getOperand(1);
6468   EVT VT = Op.getValueType();
6469
6470   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6471
6472   if (HasSSE2 && VT == MVT::v2f64)
6473     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6474
6475   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6476   return DAG.getNode(ISD::BITCAST, dl, VT,
6477                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6478                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6479                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6480 }
6481
6482 static
6483 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6484   SDValue V1 = Op.getOperand(0);
6485   SDValue V2 = Op.getOperand(1);
6486   EVT VT = Op.getValueType();
6487
6488   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6489          "unsupported shuffle type");
6490
6491   if (V2.getOpcode() == ISD::UNDEF)
6492     V2 = V1;
6493
6494   // v4i32 or v4f32
6495   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6496 }
6497
6498 static
6499 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6500   SDValue V1 = Op.getOperand(0);
6501   SDValue V2 = Op.getOperand(1);
6502   EVT VT = Op.getValueType();
6503   unsigned NumElems = VT.getVectorNumElements();
6504
6505   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6506   // operand of these instructions is only memory, so check if there's a
6507   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6508   // same masks.
6509   bool CanFoldLoad = false;
6510
6511   // Trivial case, when V2 comes from a load.
6512   if (MayFoldVectorLoad(V2))
6513     CanFoldLoad = true;
6514
6515   // When V1 is a load, it can be folded later into a store in isel, example:
6516   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6517   //    turns into:
6518   //  (MOVLPSmr addr:$src1, VR128:$src2)
6519   // So, recognize this potential and also use MOVLPS or MOVLPD
6520   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6521     CanFoldLoad = true;
6522
6523   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6524   if (CanFoldLoad) {
6525     if (HasSSE2 && NumElems == 2)
6526       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6527
6528     if (NumElems == 4)
6529       // If we don't care about the second element, proceed to use movss.
6530       if (SVOp->getMaskElt(1) != -1)
6531         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6532   }
6533
6534   // movl and movlp will both match v2i64, but v2i64 is never matched by
6535   // movl earlier because we make it strict to avoid messing with the movlp load
6536   // folding logic (see the code above getMOVLP call). Match it here then,
6537   // this is horrible, but will stay like this until we move all shuffle
6538   // matching to x86 specific nodes. Note that for the 1st condition all
6539   // types are matched with movsd.
6540   if (HasSSE2) {
6541     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6542     // as to remove this logic from here, as much as possible
6543     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6544       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6545     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6546   }
6547
6548   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6549
6550   // Invert the operand order and use SHUFPS to match it.
6551   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6552                               getShuffleSHUFImmediate(SVOp), DAG);
6553 }
6554
6555 SDValue
6556 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6557   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6558   EVT VT = Op.getValueType();
6559   DebugLoc dl = Op.getDebugLoc();
6560   SDValue V1 = Op.getOperand(0);
6561   SDValue V2 = Op.getOperand(1);
6562
6563   if (isZeroShuffle(SVOp))
6564     return getZeroVector(VT, Subtarget, DAG, dl);
6565
6566   // Handle splat operations
6567   if (SVOp->isSplat()) {
6568     unsigned NumElem = VT.getVectorNumElements();
6569     int Size = VT.getSizeInBits();
6570
6571     // Use vbroadcast whenever the splat comes from a foldable load
6572     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6573     if (Broadcast.getNode())
6574       return Broadcast;
6575
6576     // Handle splats by matching through known shuffle masks
6577     if ((Size == 128 && NumElem <= 4) ||
6578         (Size == 256 && NumElem < 8))
6579       return SDValue();
6580
6581     // All remaning splats are promoted to target supported vector shuffles.
6582     return PromoteSplat(SVOp, DAG);
6583   }
6584
6585   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6586   // do it!
6587   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6588       VT == MVT::v16i16 || VT == MVT::v32i8) {
6589     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6590     if (NewOp.getNode())
6591       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6592   } else if ((VT == MVT::v4i32 ||
6593              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6594     // FIXME: Figure out a cleaner way to do this.
6595     // Try to make use of movq to zero out the top part.
6596     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6597       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6598       if (NewOp.getNode()) {
6599         EVT NewVT = NewOp.getValueType();
6600         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6601                                NewVT, true, false))
6602           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6603                               DAG, Subtarget, dl);
6604       }
6605     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6606       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6607       if (NewOp.getNode()) {
6608         EVT NewVT = NewOp.getValueType();
6609         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6610           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6611                               DAG, Subtarget, dl);
6612       }
6613     }
6614   }
6615   return SDValue();
6616 }
6617
6618 SDValue
6619 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6620   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6621   SDValue V1 = Op.getOperand(0);
6622   SDValue V2 = Op.getOperand(1);
6623   EVT VT = Op.getValueType();
6624   DebugLoc dl = Op.getDebugLoc();
6625   unsigned NumElems = VT.getVectorNumElements();
6626   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6627   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6628   bool V1IsSplat = false;
6629   bool V2IsSplat = false;
6630   bool HasSSE2 = Subtarget->hasSSE2();
6631   bool HasAVX    = Subtarget->hasAVX();
6632   bool HasAVX2   = Subtarget->hasAVX2();
6633   MachineFunction &MF = DAG.getMachineFunction();
6634   bool OptForSize = MF.getFunction()->getFnAttributes().
6635     hasAttribute(Attributes::OptimizeForSize);
6636
6637   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6638
6639   if (V1IsUndef && V2IsUndef)
6640     return DAG.getUNDEF(VT);
6641
6642   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6643
6644   // Vector shuffle lowering takes 3 steps:
6645   //
6646   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6647   //    narrowing and commutation of operands should be handled.
6648   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6649   //    shuffle nodes.
6650   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6651   //    so the shuffle can be broken into other shuffles and the legalizer can
6652   //    try the lowering again.
6653   //
6654   // The general idea is that no vector_shuffle operation should be left to
6655   // be matched during isel, all of them must be converted to a target specific
6656   // node here.
6657
6658   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6659   // narrowing and commutation of operands should be handled. The actual code
6660   // doesn't include all of those, work in progress...
6661   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6662   if (NewOp.getNode())
6663     return NewOp;
6664
6665   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6666
6667   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6668   // unpckh_undef). Only use pshufd if speed is more important than size.
6669   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6670     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6671   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6672     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6673
6674   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6675       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6676     return getMOVDDup(Op, dl, V1, DAG);
6677
6678   if (isMOVHLPS_v_undef_Mask(M, VT))
6679     return getMOVHighToLow(Op, dl, DAG);
6680
6681   // Use to match splats
6682   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6683       (VT == MVT::v2f64 || VT == MVT::v2i64))
6684     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6685
6686   if (isPSHUFDMask(M, VT)) {
6687     // The actual implementation will match the mask in the if above and then
6688     // during isel it can match several different instructions, not only pshufd
6689     // as its name says, sad but true, emulate the behavior for now...
6690     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6691       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6692
6693     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6694
6695     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6696       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6697
6698     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6699       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6700
6701     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6702                                 TargetMask, DAG);
6703   }
6704
6705   // Check if this can be converted into a logical shift.
6706   bool isLeft = false;
6707   unsigned ShAmt = 0;
6708   SDValue ShVal;
6709   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6710   if (isShift && ShVal.hasOneUse()) {
6711     // If the shifted value has multiple uses, it may be cheaper to use
6712     // v_set0 + movlhps or movhlps, etc.
6713     EVT EltVT = VT.getVectorElementType();
6714     ShAmt *= EltVT.getSizeInBits();
6715     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6716   }
6717
6718   if (isMOVLMask(M, VT)) {
6719     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6720       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6721     if (!isMOVLPMask(M, VT)) {
6722       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6723         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6724
6725       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6726         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6727     }
6728   }
6729
6730   // FIXME: fold these into legal mask.
6731   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6732     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6733
6734   if (isMOVHLPSMask(M, VT))
6735     return getMOVHighToLow(Op, dl, DAG);
6736
6737   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6738     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6739
6740   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6741     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6742
6743   if (isMOVLPMask(M, VT))
6744     return getMOVLP(Op, dl, DAG, HasSSE2);
6745
6746   if (ShouldXformToMOVHLPS(M, VT) ||
6747       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6748     return CommuteVectorShuffle(SVOp, DAG);
6749
6750   if (isShift) {
6751     // No better options. Use a vshldq / vsrldq.
6752     EVT EltVT = VT.getVectorElementType();
6753     ShAmt *= EltVT.getSizeInBits();
6754     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6755   }
6756
6757   bool Commuted = false;
6758   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6759   // 1,1,1,1 -> v8i16 though.
6760   V1IsSplat = isSplatVector(V1.getNode());
6761   V2IsSplat = isSplatVector(V2.getNode());
6762
6763   // Canonicalize the splat or undef, if present, to be on the RHS.
6764   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6765     CommuteVectorShuffleMask(M, NumElems);
6766     std::swap(V1, V2);
6767     std::swap(V1IsSplat, V2IsSplat);
6768     Commuted = true;
6769   }
6770
6771   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6772     // Shuffling low element of v1 into undef, just return v1.
6773     if (V2IsUndef)
6774       return V1;
6775     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6776     // the instruction selector will not match, so get a canonical MOVL with
6777     // swapped operands to undo the commute.
6778     return getMOVL(DAG, dl, VT, V2, V1);
6779   }
6780
6781   if (isUNPCKLMask(M, VT, HasAVX2))
6782     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6783
6784   if (isUNPCKHMask(M, VT, HasAVX2))
6785     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6786
6787   if (V2IsSplat) {
6788     // Normalize mask so all entries that point to V2 points to its first
6789     // element then try to match unpck{h|l} again. If match, return a
6790     // new vector_shuffle with the corrected mask.p
6791     SmallVector<int, 8> NewMask(M.begin(), M.end());
6792     NormalizeMask(NewMask, NumElems);
6793     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6794       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6795     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6796       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6797   }
6798
6799   if (Commuted) {
6800     // Commute is back and try unpck* again.
6801     // FIXME: this seems wrong.
6802     CommuteVectorShuffleMask(M, NumElems);
6803     std::swap(V1, V2);
6804     std::swap(V1IsSplat, V2IsSplat);
6805     Commuted = false;
6806
6807     if (isUNPCKLMask(M, VT, HasAVX2))
6808       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6809
6810     if (isUNPCKHMask(M, VT, HasAVX2))
6811       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6812   }
6813
6814   // Normalize the node to match x86 shuffle ops if needed
6815   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6816     return CommuteVectorShuffle(SVOp, DAG);
6817
6818   // The checks below are all present in isShuffleMaskLegal, but they are
6819   // inlined here right now to enable us to directly emit target specific
6820   // nodes, and remove one by one until they don't return Op anymore.
6821
6822   if (isPALIGNRMask(M, VT, Subtarget))
6823     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6824                                 getShufflePALIGNRImmediate(SVOp),
6825                                 DAG);
6826
6827   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6828       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6829     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6830       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6831   }
6832
6833   if (isPSHUFHWMask(M, VT, HasAVX2))
6834     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6835                                 getShufflePSHUFHWImmediate(SVOp),
6836                                 DAG);
6837
6838   if (isPSHUFLWMask(M, VT, HasAVX2))
6839     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6840                                 getShufflePSHUFLWImmediate(SVOp),
6841                                 DAG);
6842
6843   if (isSHUFPMask(M, VT, HasAVX))
6844     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6845                                 getShuffleSHUFImmediate(SVOp), DAG);
6846
6847   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6848     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6849   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6850     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6851
6852   //===--------------------------------------------------------------------===//
6853   // Generate target specific nodes for 128 or 256-bit shuffles only
6854   // supported in the AVX instruction set.
6855   //
6856
6857   // Handle VMOVDDUPY permutations
6858   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6859     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6860
6861   // Handle VPERMILPS/D* permutations
6862   if (isVPERMILPMask(M, VT, HasAVX)) {
6863     if (HasAVX2 && VT == MVT::v8i32)
6864       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6865                                   getShuffleSHUFImmediate(SVOp), DAG);
6866     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6867                                 getShuffleSHUFImmediate(SVOp), DAG);
6868   }
6869
6870   // Handle VPERM2F128/VPERM2I128 permutations
6871   if (isVPERM2X128Mask(M, VT, HasAVX))
6872     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6873                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6874
6875   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6876   if (BlendOp.getNode())
6877     return BlendOp;
6878
6879   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6880     SmallVector<SDValue, 8> permclMask;
6881     for (unsigned i = 0; i != 8; ++i) {
6882       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6883     }
6884     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6885                                &permclMask[0], 8);
6886     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6887     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6888                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6889   }
6890
6891   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6892     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6893                                 getShuffleCLImmediate(SVOp), DAG);
6894
6895
6896   //===--------------------------------------------------------------------===//
6897   // Since no target specific shuffle was selected for this generic one,
6898   // lower it into other known shuffles. FIXME: this isn't true yet, but
6899   // this is the plan.
6900   //
6901
6902   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6903   if (VT == MVT::v8i16) {
6904     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6905     if (NewOp.getNode())
6906       return NewOp;
6907   }
6908
6909   if (VT == MVT::v16i8) {
6910     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6911     if (NewOp.getNode())
6912       return NewOp;
6913   }
6914
6915   if (VT == MVT::v32i8) {
6916     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
6917     if (NewOp.getNode())
6918       return NewOp;
6919   }
6920
6921   // Handle all 128-bit wide vectors with 4 elements, and match them with
6922   // several different shuffle types.
6923   if (NumElems == 4 && VT.is128BitVector())
6924     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6925
6926   // Handle general 256-bit shuffles
6927   if (VT.is256BitVector())
6928     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6929
6930   return SDValue();
6931 }
6932
6933 SDValue
6934 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6935                                                 SelectionDAG &DAG) const {
6936   EVT VT = Op.getValueType();
6937   DebugLoc dl = Op.getDebugLoc();
6938
6939   if (!Op.getOperand(0).getValueType().is128BitVector())
6940     return SDValue();
6941
6942   if (VT.getSizeInBits() == 8) {
6943     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6944                                   Op.getOperand(0), Op.getOperand(1));
6945     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6946                                   DAG.getValueType(VT));
6947     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6948   }
6949
6950   if (VT.getSizeInBits() == 16) {
6951     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6952     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6953     if (Idx == 0)
6954       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6955                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6956                                      DAG.getNode(ISD::BITCAST, dl,
6957                                                  MVT::v4i32,
6958                                                  Op.getOperand(0)),
6959                                      Op.getOperand(1)));
6960     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6961                                   Op.getOperand(0), Op.getOperand(1));
6962     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6963                                   DAG.getValueType(VT));
6964     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6965   }
6966
6967   if (VT == MVT::f32) {
6968     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6969     // the result back to FR32 register. It's only worth matching if the
6970     // result has a single use which is a store or a bitcast to i32.  And in
6971     // the case of a store, it's not worth it if the index is a constant 0,
6972     // because a MOVSSmr can be used instead, which is smaller and faster.
6973     if (!Op.hasOneUse())
6974       return SDValue();
6975     SDNode *User = *Op.getNode()->use_begin();
6976     if ((User->getOpcode() != ISD::STORE ||
6977          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6978           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6979         (User->getOpcode() != ISD::BITCAST ||
6980          User->getValueType(0) != MVT::i32))
6981       return SDValue();
6982     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6983                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6984                                               Op.getOperand(0)),
6985                                               Op.getOperand(1));
6986     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6987   }
6988
6989   if (VT == MVT::i32 || VT == MVT::i64) {
6990     // ExtractPS/pextrq works with constant index.
6991     if (isa<ConstantSDNode>(Op.getOperand(1)))
6992       return Op;
6993   }
6994   return SDValue();
6995 }
6996
6997
6998 SDValue
6999 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7000                                            SelectionDAG &DAG) const {
7001   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7002     return SDValue();
7003
7004   SDValue Vec = Op.getOperand(0);
7005   EVT VecVT = Vec.getValueType();
7006
7007   // If this is a 256-bit vector result, first extract the 128-bit vector and
7008   // then extract the element from the 128-bit vector.
7009   if (VecVT.is256BitVector()) {
7010     DebugLoc dl = Op.getNode()->getDebugLoc();
7011     unsigned NumElems = VecVT.getVectorNumElements();
7012     SDValue Idx = Op.getOperand(1);
7013     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7014
7015     // Get the 128-bit vector.
7016     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7017
7018     if (IdxVal >= NumElems/2)
7019       IdxVal -= NumElems/2;
7020     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7021                        DAG.getConstant(IdxVal, MVT::i32));
7022   }
7023
7024   assert(VecVT.is128BitVector() && "Unexpected vector length");
7025
7026   if (Subtarget->hasSSE41()) {
7027     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7028     if (Res.getNode())
7029       return Res;
7030   }
7031
7032   EVT VT = Op.getValueType();
7033   DebugLoc dl = Op.getDebugLoc();
7034   // TODO: handle v16i8.
7035   if (VT.getSizeInBits() == 16) {
7036     SDValue Vec = Op.getOperand(0);
7037     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7038     if (Idx == 0)
7039       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7040                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7041                                      DAG.getNode(ISD::BITCAST, dl,
7042                                                  MVT::v4i32, Vec),
7043                                      Op.getOperand(1)));
7044     // Transform it so it match pextrw which produces a 32-bit result.
7045     EVT EltVT = MVT::i32;
7046     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7047                                   Op.getOperand(0), Op.getOperand(1));
7048     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7049                                   DAG.getValueType(VT));
7050     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7051   }
7052
7053   if (VT.getSizeInBits() == 32) {
7054     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7055     if (Idx == 0)
7056       return Op;
7057
7058     // SHUFPS the element to the lowest double word, then movss.
7059     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7060     EVT VVT = Op.getOperand(0).getValueType();
7061     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7062                                        DAG.getUNDEF(VVT), Mask);
7063     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7064                        DAG.getIntPtrConstant(0));
7065   }
7066
7067   if (VT.getSizeInBits() == 64) {
7068     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7069     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7070     //        to match extract_elt for f64.
7071     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7072     if (Idx == 0)
7073       return Op;
7074
7075     // UNPCKHPD the element to the lowest double word, then movsd.
7076     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7077     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7078     int Mask[2] = { 1, -1 };
7079     EVT VVT = Op.getOperand(0).getValueType();
7080     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7081                                        DAG.getUNDEF(VVT), Mask);
7082     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7083                        DAG.getIntPtrConstant(0));
7084   }
7085
7086   return SDValue();
7087 }
7088
7089 SDValue
7090 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7091                                                SelectionDAG &DAG) const {
7092   EVT VT = Op.getValueType();
7093   EVT EltVT = VT.getVectorElementType();
7094   DebugLoc dl = Op.getDebugLoc();
7095
7096   SDValue N0 = Op.getOperand(0);
7097   SDValue N1 = Op.getOperand(1);
7098   SDValue N2 = Op.getOperand(2);
7099
7100   if (!VT.is128BitVector())
7101     return SDValue();
7102
7103   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7104       isa<ConstantSDNode>(N2)) {
7105     unsigned Opc;
7106     if (VT == MVT::v8i16)
7107       Opc = X86ISD::PINSRW;
7108     else if (VT == MVT::v16i8)
7109       Opc = X86ISD::PINSRB;
7110     else
7111       Opc = X86ISD::PINSRB;
7112
7113     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7114     // argument.
7115     if (N1.getValueType() != MVT::i32)
7116       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7117     if (N2.getValueType() != MVT::i32)
7118       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7119     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7120   }
7121
7122   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7123     // Bits [7:6] of the constant are the source select.  This will always be
7124     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7125     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7126     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7127     // Bits [5:4] of the constant are the destination select.  This is the
7128     //  value of the incoming immediate.
7129     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7130     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7131     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7132     // Create this as a scalar to vector..
7133     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7134     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7135   }
7136
7137   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7138     // PINSR* works with constant index.
7139     return Op;
7140   }
7141   return SDValue();
7142 }
7143
7144 SDValue
7145 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7146   EVT VT = Op.getValueType();
7147   EVT EltVT = VT.getVectorElementType();
7148
7149   DebugLoc dl = Op.getDebugLoc();
7150   SDValue N0 = Op.getOperand(0);
7151   SDValue N1 = Op.getOperand(1);
7152   SDValue N2 = Op.getOperand(2);
7153
7154   // If this is a 256-bit vector result, first extract the 128-bit vector,
7155   // insert the element into the extracted half and then place it back.
7156   if (VT.is256BitVector()) {
7157     if (!isa<ConstantSDNode>(N2))
7158       return SDValue();
7159
7160     // Get the desired 128-bit vector half.
7161     unsigned NumElems = VT.getVectorNumElements();
7162     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7163     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7164
7165     // Insert the element into the desired half.
7166     bool Upper = IdxVal >= NumElems/2;
7167     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7168                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7169
7170     // Insert the changed part back to the 256-bit vector
7171     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7172   }
7173
7174   if (Subtarget->hasSSE41())
7175     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7176
7177   if (EltVT == MVT::i8)
7178     return SDValue();
7179
7180   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7181     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7182     // as its second argument.
7183     if (N1.getValueType() != MVT::i32)
7184       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7185     if (N2.getValueType() != MVT::i32)
7186       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7187     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7188   }
7189   return SDValue();
7190 }
7191
7192 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7193   LLVMContext *Context = DAG.getContext();
7194   DebugLoc dl = Op.getDebugLoc();
7195   EVT OpVT = Op.getValueType();
7196
7197   // If this is a 256-bit vector result, first insert into a 128-bit
7198   // vector and then insert into the 256-bit vector.
7199   if (!OpVT.is128BitVector()) {
7200     // Insert into a 128-bit vector.
7201     EVT VT128 = EVT::getVectorVT(*Context,
7202                                  OpVT.getVectorElementType(),
7203                                  OpVT.getVectorNumElements() / 2);
7204
7205     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7206
7207     // Insert the 128-bit vector.
7208     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7209   }
7210
7211   if (OpVT == MVT::v1i64 &&
7212       Op.getOperand(0).getValueType() == MVT::i64)
7213     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7214
7215   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7216   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7217   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7218                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7219 }
7220
7221 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7222 // a simple subregister reference or explicit instructions to grab
7223 // upper bits of a vector.
7224 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7225                                       SelectionDAG &DAG) {
7226   if (Subtarget->hasAVX()) {
7227     DebugLoc dl = Op.getNode()->getDebugLoc();
7228     SDValue Vec = Op.getNode()->getOperand(0);
7229     SDValue Idx = Op.getNode()->getOperand(1);
7230
7231     if (Op.getNode()->getValueType(0).is128BitVector() &&
7232         Vec.getNode()->getValueType(0).is256BitVector() &&
7233         isa<ConstantSDNode>(Idx)) {
7234       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7235       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7236     }
7237   }
7238   return SDValue();
7239 }
7240
7241 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7242 // simple superregister reference or explicit instructions to insert
7243 // the upper bits of a vector.
7244 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7245                                      SelectionDAG &DAG) {
7246   if (Subtarget->hasAVX()) {
7247     DebugLoc dl = Op.getNode()->getDebugLoc();
7248     SDValue Vec = Op.getNode()->getOperand(0);
7249     SDValue SubVec = Op.getNode()->getOperand(1);
7250     SDValue Idx = Op.getNode()->getOperand(2);
7251
7252     if (Op.getNode()->getValueType(0).is256BitVector() &&
7253         SubVec.getNode()->getValueType(0).is128BitVector() &&
7254         isa<ConstantSDNode>(Idx)) {
7255       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7256       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7257     }
7258   }
7259   return SDValue();
7260 }
7261
7262 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7263 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7264 // one of the above mentioned nodes. It has to be wrapped because otherwise
7265 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7266 // be used to form addressing mode. These wrapped nodes will be selected
7267 // into MOV32ri.
7268 SDValue
7269 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7270   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7271
7272   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7273   // global base reg.
7274   unsigned char OpFlag = 0;
7275   unsigned WrapperKind = X86ISD::Wrapper;
7276   CodeModel::Model M = getTargetMachine().getCodeModel();
7277
7278   if (Subtarget->isPICStyleRIPRel() &&
7279       (M == CodeModel::Small || M == CodeModel::Kernel))
7280     WrapperKind = X86ISD::WrapperRIP;
7281   else if (Subtarget->isPICStyleGOT())
7282     OpFlag = X86II::MO_GOTOFF;
7283   else if (Subtarget->isPICStyleStubPIC())
7284     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7285
7286   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7287                                              CP->getAlignment(),
7288                                              CP->getOffset(), OpFlag);
7289   DebugLoc DL = CP->getDebugLoc();
7290   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7291   // With PIC, the address is actually $g + Offset.
7292   if (OpFlag) {
7293     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7294                          DAG.getNode(X86ISD::GlobalBaseReg,
7295                                      DebugLoc(), getPointerTy()),
7296                          Result);
7297   }
7298
7299   return Result;
7300 }
7301
7302 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7303   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7304
7305   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7306   // global base reg.
7307   unsigned char OpFlag = 0;
7308   unsigned WrapperKind = X86ISD::Wrapper;
7309   CodeModel::Model M = getTargetMachine().getCodeModel();
7310
7311   if (Subtarget->isPICStyleRIPRel() &&
7312       (M == CodeModel::Small || M == CodeModel::Kernel))
7313     WrapperKind = X86ISD::WrapperRIP;
7314   else if (Subtarget->isPICStyleGOT())
7315     OpFlag = X86II::MO_GOTOFF;
7316   else if (Subtarget->isPICStyleStubPIC())
7317     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7318
7319   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7320                                           OpFlag);
7321   DebugLoc DL = JT->getDebugLoc();
7322   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7323
7324   // With PIC, the address is actually $g + Offset.
7325   if (OpFlag)
7326     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7327                          DAG.getNode(X86ISD::GlobalBaseReg,
7328                                      DebugLoc(), getPointerTy()),
7329                          Result);
7330
7331   return Result;
7332 }
7333
7334 SDValue
7335 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7336   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7337
7338   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7339   // global base reg.
7340   unsigned char OpFlag = 0;
7341   unsigned WrapperKind = X86ISD::Wrapper;
7342   CodeModel::Model M = getTargetMachine().getCodeModel();
7343
7344   if (Subtarget->isPICStyleRIPRel() &&
7345       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7346     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7347       OpFlag = X86II::MO_GOTPCREL;
7348     WrapperKind = X86ISD::WrapperRIP;
7349   } else if (Subtarget->isPICStyleGOT()) {
7350     OpFlag = X86II::MO_GOT;
7351   } else if (Subtarget->isPICStyleStubPIC()) {
7352     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7353   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7354     OpFlag = X86II::MO_DARWIN_NONLAZY;
7355   }
7356
7357   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7358
7359   DebugLoc DL = Op.getDebugLoc();
7360   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7361
7362
7363   // With PIC, the address is actually $g + Offset.
7364   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7365       !Subtarget->is64Bit()) {
7366     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7367                          DAG.getNode(X86ISD::GlobalBaseReg,
7368                                      DebugLoc(), getPointerTy()),
7369                          Result);
7370   }
7371
7372   // For symbols that require a load from a stub to get the address, emit the
7373   // load.
7374   if (isGlobalStubReference(OpFlag))
7375     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7376                          MachinePointerInfo::getGOT(), false, false, false, 0);
7377
7378   return Result;
7379 }
7380
7381 SDValue
7382 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7383   // Create the TargetBlockAddressAddress node.
7384   unsigned char OpFlags =
7385     Subtarget->ClassifyBlockAddressReference();
7386   CodeModel::Model M = getTargetMachine().getCodeModel();
7387   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7388   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7389   DebugLoc dl = Op.getDebugLoc();
7390   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7391                                              OpFlags);
7392
7393   if (Subtarget->isPICStyleRIPRel() &&
7394       (M == CodeModel::Small || M == CodeModel::Kernel))
7395     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7396   else
7397     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7398
7399   // With PIC, the address is actually $g + Offset.
7400   if (isGlobalRelativeToPICBase(OpFlags)) {
7401     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7402                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7403                          Result);
7404   }
7405
7406   return Result;
7407 }
7408
7409 SDValue
7410 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7411                                       int64_t Offset,
7412                                       SelectionDAG &DAG) const {
7413   // Create the TargetGlobalAddress node, folding in the constant
7414   // offset if it is legal.
7415   unsigned char OpFlags =
7416     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7417   CodeModel::Model M = getTargetMachine().getCodeModel();
7418   SDValue Result;
7419   if (OpFlags == X86II::MO_NO_FLAG &&
7420       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7421     // A direct static reference to a global.
7422     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7423     Offset = 0;
7424   } else {
7425     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7426   }
7427
7428   if (Subtarget->isPICStyleRIPRel() &&
7429       (M == CodeModel::Small || M == CodeModel::Kernel))
7430     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7431   else
7432     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7433
7434   // With PIC, the address is actually $g + Offset.
7435   if (isGlobalRelativeToPICBase(OpFlags)) {
7436     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7437                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7438                          Result);
7439   }
7440
7441   // For globals that require a load from a stub to get the address, emit the
7442   // load.
7443   if (isGlobalStubReference(OpFlags))
7444     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7445                          MachinePointerInfo::getGOT(), false, false, false, 0);
7446
7447   // If there was a non-zero offset that we didn't fold, create an explicit
7448   // addition for it.
7449   if (Offset != 0)
7450     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7451                          DAG.getConstant(Offset, getPointerTy()));
7452
7453   return Result;
7454 }
7455
7456 SDValue
7457 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7458   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7459   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7460   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7461 }
7462
7463 static SDValue
7464 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7465            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7466            unsigned char OperandFlags, bool LocalDynamic = false) {
7467   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7468   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7469   DebugLoc dl = GA->getDebugLoc();
7470   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7471                                            GA->getValueType(0),
7472                                            GA->getOffset(),
7473                                            OperandFlags);
7474
7475   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7476                                            : X86ISD::TLSADDR;
7477
7478   if (InFlag) {
7479     SDValue Ops[] = { Chain,  TGA, *InFlag };
7480     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7481   } else {
7482     SDValue Ops[]  = { Chain, TGA };
7483     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7484   }
7485
7486   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7487   MFI->setAdjustsStack(true);
7488
7489   SDValue Flag = Chain.getValue(1);
7490   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7491 }
7492
7493 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7494 static SDValue
7495 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7496                                 const EVT PtrVT) {
7497   SDValue InFlag;
7498   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7499   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7500                                    DAG.getNode(X86ISD::GlobalBaseReg,
7501                                                DebugLoc(), PtrVT), InFlag);
7502   InFlag = Chain.getValue(1);
7503
7504   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7505 }
7506
7507 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7508 static SDValue
7509 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7510                                 const EVT PtrVT) {
7511   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7512                     X86::RAX, X86II::MO_TLSGD);
7513 }
7514
7515 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7516                                            SelectionDAG &DAG,
7517                                            const EVT PtrVT,
7518                                            bool is64Bit) {
7519   DebugLoc dl = GA->getDebugLoc();
7520
7521   // Get the start address of the TLS block for this module.
7522   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7523       .getInfo<X86MachineFunctionInfo>();
7524   MFI->incNumLocalDynamicTLSAccesses();
7525
7526   SDValue Base;
7527   if (is64Bit) {
7528     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7529                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7530   } else {
7531     SDValue InFlag;
7532     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7533         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7534     InFlag = Chain.getValue(1);
7535     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7536                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7537   }
7538
7539   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7540   // of Base.
7541
7542   // Build x@dtpoff.
7543   unsigned char OperandFlags = X86II::MO_DTPOFF;
7544   unsigned WrapperKind = X86ISD::Wrapper;
7545   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7546                                            GA->getValueType(0),
7547                                            GA->getOffset(), OperandFlags);
7548   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7549
7550   // Add x@dtpoff with the base.
7551   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7552 }
7553
7554 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7555 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7556                                    const EVT PtrVT, TLSModel::Model model,
7557                                    bool is64Bit, bool isPIC) {
7558   DebugLoc dl = GA->getDebugLoc();
7559
7560   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7561   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7562                                                          is64Bit ? 257 : 256));
7563
7564   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7565                                       DAG.getIntPtrConstant(0),
7566                                       MachinePointerInfo(Ptr),
7567                                       false, false, false, 0);
7568
7569   unsigned char OperandFlags = 0;
7570   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7571   // initialexec.
7572   unsigned WrapperKind = X86ISD::Wrapper;
7573   if (model == TLSModel::LocalExec) {
7574     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7575   } else if (model == TLSModel::InitialExec) {
7576     if (is64Bit) {
7577       OperandFlags = X86II::MO_GOTTPOFF;
7578       WrapperKind = X86ISD::WrapperRIP;
7579     } else {
7580       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7581     }
7582   } else {
7583     llvm_unreachable("Unexpected model");
7584   }
7585
7586   // emit "addl x@ntpoff,%eax" (local exec)
7587   // or "addl x@indntpoff,%eax" (initial exec)
7588   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7589   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7590                                            GA->getValueType(0),
7591                                            GA->getOffset(), OperandFlags);
7592   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7593
7594   if (model == TLSModel::InitialExec) {
7595     if (isPIC && !is64Bit) {
7596       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7597                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7598                            Offset);
7599     }
7600
7601     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7602                          MachinePointerInfo::getGOT(), false, false, false,
7603                          0);
7604   }
7605
7606   // The address of the thread local variable is the add of the thread
7607   // pointer with the offset of the variable.
7608   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7609 }
7610
7611 SDValue
7612 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7613
7614   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7615   const GlobalValue *GV = GA->getGlobal();
7616
7617   if (Subtarget->isTargetELF()) {
7618     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7619
7620     switch (model) {
7621       case TLSModel::GeneralDynamic:
7622         if (Subtarget->is64Bit())
7623           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7624         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7625       case TLSModel::LocalDynamic:
7626         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7627                                            Subtarget->is64Bit());
7628       case TLSModel::InitialExec:
7629       case TLSModel::LocalExec:
7630         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7631                                    Subtarget->is64Bit(),
7632                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7633     }
7634     llvm_unreachable("Unknown TLS model.");
7635   }
7636
7637   if (Subtarget->isTargetDarwin()) {
7638     // Darwin only has one model of TLS.  Lower to that.
7639     unsigned char OpFlag = 0;
7640     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7641                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7642
7643     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7644     // global base reg.
7645     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7646                   !Subtarget->is64Bit();
7647     if (PIC32)
7648       OpFlag = X86II::MO_TLVP_PIC_BASE;
7649     else
7650       OpFlag = X86II::MO_TLVP;
7651     DebugLoc DL = Op.getDebugLoc();
7652     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7653                                                 GA->getValueType(0),
7654                                                 GA->getOffset(), OpFlag);
7655     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7656
7657     // With PIC32, the address is actually $g + Offset.
7658     if (PIC32)
7659       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7660                            DAG.getNode(X86ISD::GlobalBaseReg,
7661                                        DebugLoc(), getPointerTy()),
7662                            Offset);
7663
7664     // Lowering the machine isd will make sure everything is in the right
7665     // location.
7666     SDValue Chain = DAG.getEntryNode();
7667     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7668     SDValue Args[] = { Chain, Offset };
7669     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7670
7671     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7672     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7673     MFI->setAdjustsStack(true);
7674
7675     // And our return value (tls address) is in the standard call return value
7676     // location.
7677     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7678     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7679                               Chain.getValue(1));
7680   }
7681
7682   if (Subtarget->isTargetWindows()) {
7683     // Just use the implicit TLS architecture
7684     // Need to generate someting similar to:
7685     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7686     //                                  ; from TEB
7687     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7688     //   mov     rcx, qword [rdx+rcx*8]
7689     //   mov     eax, .tls$:tlsvar
7690     //   [rax+rcx] contains the address
7691     // Windows 64bit: gs:0x58
7692     // Windows 32bit: fs:__tls_array
7693
7694     // If GV is an alias then use the aliasee for determining
7695     // thread-localness.
7696     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7697       GV = GA->resolveAliasedGlobal(false);
7698     DebugLoc dl = GA->getDebugLoc();
7699     SDValue Chain = DAG.getEntryNode();
7700
7701     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7702     // %gs:0x58 (64-bit).
7703     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7704                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7705                                                              256)
7706                                         : Type::getInt32PtrTy(*DAG.getContext(),
7707                                                               257));
7708
7709     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7710                                         Subtarget->is64Bit()
7711                                         ? DAG.getIntPtrConstant(0x58)
7712                                         : DAG.getExternalSymbol("_tls_array",
7713                                                                 getPointerTy()),
7714                                         MachinePointerInfo(Ptr),
7715                                         false, false, false, 0);
7716
7717     // Load the _tls_index variable
7718     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7719     if (Subtarget->is64Bit())
7720       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7721                            IDX, MachinePointerInfo(), MVT::i32,
7722                            false, false, 0);
7723     else
7724       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7725                         false, false, false, 0);
7726
7727     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7728                                     getPointerTy());
7729     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7730
7731     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7732     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7733                       false, false, false, 0);
7734
7735     // Get the offset of start of .tls section
7736     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7737                                              GA->getValueType(0),
7738                                              GA->getOffset(), X86II::MO_SECREL);
7739     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7740
7741     // The address of the thread local variable is the add of the thread
7742     // pointer with the offset of the variable.
7743     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7744   }
7745
7746   llvm_unreachable("TLS not implemented for this target.");
7747 }
7748
7749
7750 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7751 /// and take a 2 x i32 value to shift plus a shift amount.
7752 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7753   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7754   EVT VT = Op.getValueType();
7755   unsigned VTBits = VT.getSizeInBits();
7756   DebugLoc dl = Op.getDebugLoc();
7757   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7758   SDValue ShOpLo = Op.getOperand(0);
7759   SDValue ShOpHi = Op.getOperand(1);
7760   SDValue ShAmt  = Op.getOperand(2);
7761   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7762                                      DAG.getConstant(VTBits - 1, MVT::i8))
7763                        : DAG.getConstant(0, VT);
7764
7765   SDValue Tmp2, Tmp3;
7766   if (Op.getOpcode() == ISD::SHL_PARTS) {
7767     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7768     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7769   } else {
7770     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7771     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7772   }
7773
7774   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7775                                 DAG.getConstant(VTBits, MVT::i8));
7776   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7777                              AndNode, DAG.getConstant(0, MVT::i8));
7778
7779   SDValue Hi, Lo;
7780   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7781   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7782   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7783
7784   if (Op.getOpcode() == ISD::SHL_PARTS) {
7785     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7786     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7787   } else {
7788     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7789     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7790   }
7791
7792   SDValue Ops[2] = { Lo, Hi };
7793   return DAG.getMergeValues(Ops, 2, dl);
7794 }
7795
7796 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7797                                            SelectionDAG &DAG) const {
7798   EVT SrcVT = Op.getOperand(0).getValueType();
7799
7800   if (SrcVT.isVector())
7801     return SDValue();
7802
7803   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7804          "Unknown SINT_TO_FP to lower!");
7805
7806   // These are really Legal; return the operand so the caller accepts it as
7807   // Legal.
7808   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7809     return Op;
7810   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7811       Subtarget->is64Bit()) {
7812     return Op;
7813   }
7814
7815   DebugLoc dl = Op.getDebugLoc();
7816   unsigned Size = SrcVT.getSizeInBits()/8;
7817   MachineFunction &MF = DAG.getMachineFunction();
7818   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7819   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7820   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7821                                StackSlot,
7822                                MachinePointerInfo::getFixedStack(SSFI),
7823                                false, false, 0);
7824   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7825 }
7826
7827 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7828                                      SDValue StackSlot,
7829                                      SelectionDAG &DAG) const {
7830   // Build the FILD
7831   DebugLoc DL = Op.getDebugLoc();
7832   SDVTList Tys;
7833   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7834   if (useSSE)
7835     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7836   else
7837     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7838
7839   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7840
7841   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7842   MachineMemOperand *MMO;
7843   if (FI) {
7844     int SSFI = FI->getIndex();
7845     MMO =
7846       DAG.getMachineFunction()
7847       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7848                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7849   } else {
7850     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7851     StackSlot = StackSlot.getOperand(1);
7852   }
7853   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7854   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7855                                            X86ISD::FILD, DL,
7856                                            Tys, Ops, array_lengthof(Ops),
7857                                            SrcVT, MMO);
7858
7859   if (useSSE) {
7860     Chain = Result.getValue(1);
7861     SDValue InFlag = Result.getValue(2);
7862
7863     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7864     // shouldn't be necessary except that RFP cannot be live across
7865     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7866     MachineFunction &MF = DAG.getMachineFunction();
7867     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7868     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7869     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7870     Tys = DAG.getVTList(MVT::Other);
7871     SDValue Ops[] = {
7872       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7873     };
7874     MachineMemOperand *MMO =
7875       DAG.getMachineFunction()
7876       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7877                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7878
7879     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7880                                     Ops, array_lengthof(Ops),
7881                                     Op.getValueType(), MMO);
7882     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7883                          MachinePointerInfo::getFixedStack(SSFI),
7884                          false, false, false, 0);
7885   }
7886
7887   return Result;
7888 }
7889
7890 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7891 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7892                                                SelectionDAG &DAG) const {
7893   // This algorithm is not obvious. Here it is what we're trying to output:
7894   /*
7895      movq       %rax,  %xmm0
7896      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7897      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7898      #ifdef __SSE3__
7899        haddpd   %xmm0, %xmm0
7900      #else
7901        pshufd   $0x4e, %xmm0, %xmm1
7902        addpd    %xmm1, %xmm0
7903      #endif
7904   */
7905
7906   DebugLoc dl = Op.getDebugLoc();
7907   LLVMContext *Context = DAG.getContext();
7908
7909   // Build some magic constants.
7910   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7911   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7912   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7913
7914   SmallVector<Constant*,2> CV1;
7915   CV1.push_back(
7916         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7917   CV1.push_back(
7918         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7919   Constant *C1 = ConstantVector::get(CV1);
7920   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7921
7922   // Load the 64-bit value into an XMM register.
7923   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7924                             Op.getOperand(0));
7925   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7926                               MachinePointerInfo::getConstantPool(),
7927                               false, false, false, 16);
7928   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7929                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7930                               CLod0);
7931
7932   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7933                               MachinePointerInfo::getConstantPool(),
7934                               false, false, false, 16);
7935   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7936   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7937   SDValue Result;
7938
7939   if (Subtarget->hasSSE3()) {
7940     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7941     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7942   } else {
7943     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7944     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7945                                            S2F, 0x4E, DAG);
7946     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7947                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7948                          Sub);
7949   }
7950
7951   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7952                      DAG.getIntPtrConstant(0));
7953 }
7954
7955 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7956 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7957                                                SelectionDAG &DAG) const {
7958   DebugLoc dl = Op.getDebugLoc();
7959   // FP constant to bias correct the final result.
7960   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7961                                    MVT::f64);
7962
7963   // Load the 32-bit value into an XMM register.
7964   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7965                              Op.getOperand(0));
7966
7967   // Zero out the upper parts of the register.
7968   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7969
7970   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7971                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7972                      DAG.getIntPtrConstant(0));
7973
7974   // Or the load with the bias.
7975   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7976                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7977                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7978                                                    MVT::v2f64, Load)),
7979                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7980                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7981                                                    MVT::v2f64, Bias)));
7982   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7983                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7984                    DAG.getIntPtrConstant(0));
7985
7986   // Subtract the bias.
7987   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7988
7989   // Handle final rounding.
7990   EVT DestVT = Op.getValueType();
7991
7992   if (DestVT.bitsLT(MVT::f64))
7993     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7994                        DAG.getIntPtrConstant(0));
7995   if (DestVT.bitsGT(MVT::f64))
7996     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7997
7998   // Handle final rounding.
7999   return Sub;
8000 }
8001
8002 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8003                                            SelectionDAG &DAG) const {
8004   SDValue N0 = Op.getOperand(0);
8005   DebugLoc dl = Op.getDebugLoc();
8006
8007   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8008   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8009   // the optimization here.
8010   if (DAG.SignBitIsZero(N0))
8011     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8012
8013   EVT SrcVT = N0.getValueType();
8014   EVT DstVT = Op.getValueType();
8015   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8016     return LowerUINT_TO_FP_i64(Op, DAG);
8017   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8018     return LowerUINT_TO_FP_i32(Op, DAG);
8019   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8020     return SDValue();
8021
8022   // Make a 64-bit buffer, and use it to build an FILD.
8023   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8024   if (SrcVT == MVT::i32) {
8025     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8026     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8027                                      getPointerTy(), StackSlot, WordOff);
8028     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8029                                   StackSlot, MachinePointerInfo(),
8030                                   false, false, 0);
8031     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8032                                   OffsetSlot, MachinePointerInfo(),
8033                                   false, false, 0);
8034     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8035     return Fild;
8036   }
8037
8038   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8039   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8040                                StackSlot, MachinePointerInfo(),
8041                                false, false, 0);
8042   // For i64 source, we need to add the appropriate power of 2 if the input
8043   // was negative.  This is the same as the optimization in
8044   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8045   // we must be careful to do the computation in x87 extended precision, not
8046   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8047   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8048   MachineMemOperand *MMO =
8049     DAG.getMachineFunction()
8050     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8051                           MachineMemOperand::MOLoad, 8, 8);
8052
8053   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8054   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8055   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8056                                          MVT::i64, MMO);
8057
8058   APInt FF(32, 0x5F800000ULL);
8059
8060   // Check whether the sign bit is set.
8061   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8062                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8063                                  ISD::SETLT);
8064
8065   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8066   SDValue FudgePtr = DAG.getConstantPool(
8067                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8068                                          getPointerTy());
8069
8070   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8071   SDValue Zero = DAG.getIntPtrConstant(0);
8072   SDValue Four = DAG.getIntPtrConstant(4);
8073   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8074                                Zero, Four);
8075   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8076
8077   // Load the value out, extending it from f32 to f80.
8078   // FIXME: Avoid the extend by constructing the right constant pool?
8079   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8080                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8081                                  MVT::f32, false, false, 4);
8082   // Extend everything to 80 bits to force it to be done on x87.
8083   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8084   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8085 }
8086
8087 std::pair<SDValue,SDValue> X86TargetLowering::
8088 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8089   DebugLoc DL = Op.getDebugLoc();
8090
8091   EVT DstTy = Op.getValueType();
8092
8093   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8094     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8095     DstTy = MVT::i64;
8096   }
8097
8098   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8099          DstTy.getSimpleVT() >= MVT::i16 &&
8100          "Unknown FP_TO_INT to lower!");
8101
8102   // These are really Legal.
8103   if (DstTy == MVT::i32 &&
8104       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8105     return std::make_pair(SDValue(), SDValue());
8106   if (Subtarget->is64Bit() &&
8107       DstTy == MVT::i64 &&
8108       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8109     return std::make_pair(SDValue(), SDValue());
8110
8111   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8112   // stack slot, or into the FTOL runtime function.
8113   MachineFunction &MF = DAG.getMachineFunction();
8114   unsigned MemSize = DstTy.getSizeInBits()/8;
8115   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8116   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8117
8118   unsigned Opc;
8119   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8120     Opc = X86ISD::WIN_FTOL;
8121   else
8122     switch (DstTy.getSimpleVT().SimpleTy) {
8123     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8124     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8125     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8126     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8127     }
8128
8129   SDValue Chain = DAG.getEntryNode();
8130   SDValue Value = Op.getOperand(0);
8131   EVT TheVT = Op.getOperand(0).getValueType();
8132   // FIXME This causes a redundant load/store if the SSE-class value is already
8133   // in memory, such as if it is on the callstack.
8134   if (isScalarFPTypeInSSEReg(TheVT)) {
8135     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8136     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8137                          MachinePointerInfo::getFixedStack(SSFI),
8138                          false, false, 0);
8139     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8140     SDValue Ops[] = {
8141       Chain, StackSlot, DAG.getValueType(TheVT)
8142     };
8143
8144     MachineMemOperand *MMO =
8145       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8146                               MachineMemOperand::MOLoad, MemSize, MemSize);
8147     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8148                                     DstTy, MMO);
8149     Chain = Value.getValue(1);
8150     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8151     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8152   }
8153
8154   MachineMemOperand *MMO =
8155     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8156                             MachineMemOperand::MOStore, MemSize, MemSize);
8157
8158   if (Opc != X86ISD::WIN_FTOL) {
8159     // Build the FP_TO_INT*_IN_MEM
8160     SDValue Ops[] = { Chain, Value, StackSlot };
8161     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8162                                            Ops, 3, DstTy, MMO);
8163     return std::make_pair(FIST, StackSlot);
8164   } else {
8165     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8166       DAG.getVTList(MVT::Other, MVT::Glue),
8167       Chain, Value);
8168     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8169       MVT::i32, ftol.getValue(1));
8170     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8171       MVT::i32, eax.getValue(2));
8172     SDValue Ops[] = { eax, edx };
8173     SDValue pair = IsReplace
8174       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8175       : DAG.getMergeValues(Ops, 2, DL);
8176     return std::make_pair(pair, SDValue());
8177   }
8178 }
8179
8180 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8181                                            SelectionDAG &DAG) const {
8182   if (Op.getValueType().isVector())
8183     return SDValue();
8184
8185   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8186     /*IsSigned=*/ true, /*IsReplace=*/ false);
8187   SDValue FIST = Vals.first, StackSlot = Vals.second;
8188   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8189   if (FIST.getNode() == 0) return Op;
8190
8191   if (StackSlot.getNode())
8192     // Load the result.
8193     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8194                        FIST, StackSlot, MachinePointerInfo(),
8195                        false, false, false, 0);
8196
8197   // The node is the result.
8198   return FIST;
8199 }
8200
8201 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8202                                            SelectionDAG &DAG) const {
8203   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8204     /*IsSigned=*/ false, /*IsReplace=*/ false);
8205   SDValue FIST = Vals.first, StackSlot = Vals.second;
8206   assert(FIST.getNode() && "Unexpected failure");
8207
8208   if (StackSlot.getNode())
8209     // Load the result.
8210     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8211                        FIST, StackSlot, MachinePointerInfo(),
8212                        false, false, false, 0);
8213
8214   // The node is the result.
8215   return FIST;
8216 }
8217
8218 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8219   LLVMContext *Context = DAG.getContext();
8220   DebugLoc dl = Op.getDebugLoc();
8221   EVT VT = Op.getValueType();
8222   EVT EltVT = VT;
8223   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8224   if (VT.isVector()) {
8225     EltVT = VT.getVectorElementType();
8226     NumElts = VT.getVectorNumElements();
8227   }
8228   Constant *C;
8229   if (EltVT == MVT::f64)
8230     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8231   else
8232     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8233   C = ConstantVector::getSplat(NumElts, C);
8234   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8235   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8236   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8237                              MachinePointerInfo::getConstantPool(),
8238                              false, false, false, Alignment);
8239   if (VT.isVector()) {
8240     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8241     return DAG.getNode(ISD::BITCAST, dl, VT,
8242                        DAG.getNode(ISD::AND, dl, ANDVT,
8243                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8244                                                Op.getOperand(0)),
8245                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8246   }
8247   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8248 }
8249
8250 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8251   LLVMContext *Context = DAG.getContext();
8252   DebugLoc dl = Op.getDebugLoc();
8253   EVT VT = Op.getValueType();
8254   EVT EltVT = VT;
8255   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8256   if (VT.isVector()) {
8257     EltVT = VT.getVectorElementType();
8258     NumElts = VT.getVectorNumElements();
8259   }
8260   Constant *C;
8261   if (EltVT == MVT::f64)
8262     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8263   else
8264     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8265   C = ConstantVector::getSplat(NumElts, C);
8266   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8267   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8268   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8269                              MachinePointerInfo::getConstantPool(),
8270                              false, false, false, Alignment);
8271   if (VT.isVector()) {
8272     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8273     return DAG.getNode(ISD::BITCAST, dl, VT,
8274                        DAG.getNode(ISD::XOR, dl, XORVT,
8275                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8276                                                Op.getOperand(0)),
8277                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8278   }
8279
8280   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8281 }
8282
8283 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8284   LLVMContext *Context = DAG.getContext();
8285   SDValue Op0 = Op.getOperand(0);
8286   SDValue Op1 = Op.getOperand(1);
8287   DebugLoc dl = Op.getDebugLoc();
8288   EVT VT = Op.getValueType();
8289   EVT SrcVT = Op1.getValueType();
8290
8291   // If second operand is smaller, extend it first.
8292   if (SrcVT.bitsLT(VT)) {
8293     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8294     SrcVT = VT;
8295   }
8296   // And if it is bigger, shrink it first.
8297   if (SrcVT.bitsGT(VT)) {
8298     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8299     SrcVT = VT;
8300   }
8301
8302   // At this point the operands and the result should have the same
8303   // type, and that won't be f80 since that is not custom lowered.
8304
8305   // First get the sign bit of second operand.
8306   SmallVector<Constant*,4> CV;
8307   if (SrcVT == MVT::f64) {
8308     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8309     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8310   } else {
8311     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8312     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8313     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8314     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8315   }
8316   Constant *C = ConstantVector::get(CV);
8317   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8318   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8319                               MachinePointerInfo::getConstantPool(),
8320                               false, false, false, 16);
8321   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8322
8323   // Shift sign bit right or left if the two operands have different types.
8324   if (SrcVT.bitsGT(VT)) {
8325     // Op0 is MVT::f32, Op1 is MVT::f64.
8326     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8327     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8328                           DAG.getConstant(32, MVT::i32));
8329     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8330     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8331                           DAG.getIntPtrConstant(0));
8332   }
8333
8334   // Clear first operand sign bit.
8335   CV.clear();
8336   if (VT == MVT::f64) {
8337     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8338     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8339   } else {
8340     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8341     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8342     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8343     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8344   }
8345   C = ConstantVector::get(CV);
8346   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8347   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8348                               MachinePointerInfo::getConstantPool(),
8349                               false, false, false, 16);
8350   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8351
8352   // Or the value with the sign bit.
8353   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8354 }
8355
8356 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8357   SDValue N0 = Op.getOperand(0);
8358   DebugLoc dl = Op.getDebugLoc();
8359   EVT VT = Op.getValueType();
8360
8361   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8362   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8363                                   DAG.getConstant(1, VT));
8364   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8365 }
8366
8367 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8368 //
8369 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8370   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8371
8372   if (!Subtarget->hasSSE41())
8373     return SDValue();
8374
8375   if (!Op->hasOneUse())
8376     return SDValue();
8377
8378   SDNode *N = Op.getNode();
8379   DebugLoc DL = N->getDebugLoc();
8380
8381   SmallVector<SDValue, 8> Opnds;
8382   DenseMap<SDValue, unsigned> VecInMap;
8383   EVT VT = MVT::Other;
8384
8385   // Recognize a special case where a vector is casted into wide integer to
8386   // test all 0s.
8387   Opnds.push_back(N->getOperand(0));
8388   Opnds.push_back(N->getOperand(1));
8389
8390   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8391     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8392     // BFS traverse all OR'd operands.
8393     if (I->getOpcode() == ISD::OR) {
8394       Opnds.push_back(I->getOperand(0));
8395       Opnds.push_back(I->getOperand(1));
8396       // Re-evaluate the number of nodes to be traversed.
8397       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8398       continue;
8399     }
8400
8401     // Quit if a non-EXTRACT_VECTOR_ELT
8402     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8403       return SDValue();
8404
8405     // Quit if without a constant index.
8406     SDValue Idx = I->getOperand(1);
8407     if (!isa<ConstantSDNode>(Idx))
8408       return SDValue();
8409
8410     SDValue ExtractedFromVec = I->getOperand(0);
8411     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8412     if (M == VecInMap.end()) {
8413       VT = ExtractedFromVec.getValueType();
8414       // Quit if not 128/256-bit vector.
8415       if (!VT.is128BitVector() && !VT.is256BitVector())
8416         return SDValue();
8417       // Quit if not the same type.
8418       if (VecInMap.begin() != VecInMap.end() &&
8419           VT != VecInMap.begin()->first.getValueType())
8420         return SDValue();
8421       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8422     }
8423     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8424   }
8425
8426   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8427          "Not extracted from 128-/256-bit vector.");
8428
8429   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8430   SmallVector<SDValue, 8> VecIns;
8431
8432   for (DenseMap<SDValue, unsigned>::const_iterator
8433         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8434     // Quit if not all elements are used.
8435     if (I->second != FullMask)
8436       return SDValue();
8437     VecIns.push_back(I->first);
8438   }
8439
8440   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8441
8442   // Cast all vectors into TestVT for PTEST.
8443   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8444     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8445
8446   // If more than one full vectors are evaluated, OR them first before PTEST.
8447   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8448     // Each iteration will OR 2 nodes and append the result until there is only
8449     // 1 node left, i.e. the final OR'd value of all vectors.
8450     SDValue LHS = VecIns[Slot];
8451     SDValue RHS = VecIns[Slot + 1];
8452     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8453   }
8454
8455   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8456                      VecIns.back(), VecIns.back());
8457 }
8458
8459 /// Emit nodes that will be selected as "test Op0,Op0", or something
8460 /// equivalent.
8461 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8462                                     SelectionDAG &DAG) const {
8463   DebugLoc dl = Op.getDebugLoc();
8464
8465   // CF and OF aren't always set the way we want. Determine which
8466   // of these we need.
8467   bool NeedCF = false;
8468   bool NeedOF = false;
8469   switch (X86CC) {
8470   default: break;
8471   case X86::COND_A: case X86::COND_AE:
8472   case X86::COND_B: case X86::COND_BE:
8473     NeedCF = true;
8474     break;
8475   case X86::COND_G: case X86::COND_GE:
8476   case X86::COND_L: case X86::COND_LE:
8477   case X86::COND_O: case X86::COND_NO:
8478     NeedOF = true;
8479     break;
8480   }
8481
8482   // See if we can use the EFLAGS value from the operand instead of
8483   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8484   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8485   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8486     // Emit a CMP with 0, which is the TEST pattern.
8487     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8488                        DAG.getConstant(0, Op.getValueType()));
8489
8490   unsigned Opcode = 0;
8491   unsigned NumOperands = 0;
8492
8493   // Truncate operations may prevent the merge of the SETCC instruction
8494   // and the arithmetic intruction before it. Attempt to truncate the operands
8495   // of the arithmetic instruction and use a reduced bit-width instruction.
8496   bool NeedTruncation = false;
8497   SDValue ArithOp = Op;
8498   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8499     SDValue Arith = Op->getOperand(0);
8500     // Both the trunc and the arithmetic op need to have one user each.
8501     if (Arith->hasOneUse())
8502       switch (Arith.getOpcode()) {
8503         default: break;
8504         case ISD::ADD:
8505         case ISD::SUB:
8506         case ISD::AND:
8507         case ISD::OR:
8508         case ISD::XOR: {
8509           NeedTruncation = true;
8510           ArithOp = Arith;
8511         }
8512       }
8513   }
8514
8515   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8516   // which may be the result of a CAST.  We use the variable 'Op', which is the
8517   // non-casted variable when we check for possible users.
8518   switch (ArithOp.getOpcode()) {
8519   case ISD::ADD:
8520     // Due to an isel shortcoming, be conservative if this add is likely to be
8521     // selected as part of a load-modify-store instruction. When the root node
8522     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8523     // uses of other nodes in the match, such as the ADD in this case. This
8524     // leads to the ADD being left around and reselected, with the result being
8525     // two adds in the output.  Alas, even if none our users are stores, that
8526     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8527     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8528     // climbing the DAG back to the root, and it doesn't seem to be worth the
8529     // effort.
8530     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8531          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8532       if (UI->getOpcode() != ISD::CopyToReg &&
8533           UI->getOpcode() != ISD::SETCC &&
8534           UI->getOpcode() != ISD::STORE)
8535         goto default_case;
8536
8537     if (ConstantSDNode *C =
8538         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8539       // An add of one will be selected as an INC.
8540       if (C->getAPIntValue() == 1) {
8541         Opcode = X86ISD::INC;
8542         NumOperands = 1;
8543         break;
8544       }
8545
8546       // An add of negative one (subtract of one) will be selected as a DEC.
8547       if (C->getAPIntValue().isAllOnesValue()) {
8548         Opcode = X86ISD::DEC;
8549         NumOperands = 1;
8550         break;
8551       }
8552     }
8553
8554     // Otherwise use a regular EFLAGS-setting add.
8555     Opcode = X86ISD::ADD;
8556     NumOperands = 2;
8557     break;
8558   case ISD::AND: {
8559     // If the primary and result isn't used, don't bother using X86ISD::AND,
8560     // because a TEST instruction will be better.
8561     bool NonFlagUse = false;
8562     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8563            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8564       SDNode *User = *UI;
8565       unsigned UOpNo = UI.getOperandNo();
8566       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8567         // Look pass truncate.
8568         UOpNo = User->use_begin().getOperandNo();
8569         User = *User->use_begin();
8570       }
8571
8572       if (User->getOpcode() != ISD::BRCOND &&
8573           User->getOpcode() != ISD::SETCC &&
8574           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8575         NonFlagUse = true;
8576         break;
8577       }
8578     }
8579
8580     if (!NonFlagUse)
8581       break;
8582   }
8583     // FALL THROUGH
8584   case ISD::SUB:
8585   case ISD::OR:
8586   case ISD::XOR:
8587     // Due to the ISEL shortcoming noted above, be conservative if this op is
8588     // likely to be selected as part of a load-modify-store instruction.
8589     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8590            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8591       if (UI->getOpcode() == ISD::STORE)
8592         goto default_case;
8593
8594     // Otherwise use a regular EFLAGS-setting instruction.
8595     switch (ArithOp.getOpcode()) {
8596     default: llvm_unreachable("unexpected operator!");
8597     case ISD::SUB: Opcode = X86ISD::SUB; break;
8598     case ISD::XOR: Opcode = X86ISD::XOR; break;
8599     case ISD::AND: Opcode = X86ISD::AND; break;
8600     case ISD::OR: {
8601       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8602         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8603         if (EFLAGS.getNode())
8604           return EFLAGS;
8605       }
8606       Opcode = X86ISD::OR;
8607       break;
8608     }
8609     }
8610
8611     NumOperands = 2;
8612     break;
8613   case X86ISD::ADD:
8614   case X86ISD::SUB:
8615   case X86ISD::INC:
8616   case X86ISD::DEC:
8617   case X86ISD::OR:
8618   case X86ISD::XOR:
8619   case X86ISD::AND:
8620     return SDValue(Op.getNode(), 1);
8621   default:
8622   default_case:
8623     break;
8624   }
8625
8626   // If we found that truncation is beneficial, perform the truncation and
8627   // update 'Op'.
8628   if (NeedTruncation) {
8629     EVT VT = Op.getValueType();
8630     SDValue WideVal = Op->getOperand(0);
8631     EVT WideVT = WideVal.getValueType();
8632     unsigned ConvertedOp = 0;
8633     // Use a target machine opcode to prevent further DAGCombine
8634     // optimizations that may separate the arithmetic operations
8635     // from the setcc node.
8636     switch (WideVal.getOpcode()) {
8637       default: break;
8638       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8639       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8640       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8641       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8642       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8643     }
8644
8645     if (ConvertedOp) {
8646       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8647       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8648         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8649         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8650         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8651       }
8652     }
8653   }
8654
8655   if (Opcode == 0)
8656     // Emit a CMP with 0, which is the TEST pattern.
8657     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8658                        DAG.getConstant(0, Op.getValueType()));
8659
8660   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8661   SmallVector<SDValue, 4> Ops;
8662   for (unsigned i = 0; i != NumOperands; ++i)
8663     Ops.push_back(Op.getOperand(i));
8664
8665   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8666   DAG.ReplaceAllUsesWith(Op, New);
8667   return SDValue(New.getNode(), 1);
8668 }
8669
8670 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8671 /// equivalent.
8672 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8673                                    SelectionDAG &DAG) const {
8674   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8675     if (C->getAPIntValue() == 0)
8676       return EmitTest(Op0, X86CC, DAG);
8677
8678   DebugLoc dl = Op0.getDebugLoc();
8679   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8680        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8681     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8682     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8683     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8684                               Op0, Op1);
8685     return SDValue(Sub.getNode(), 1);
8686   }
8687   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8688 }
8689
8690 /// Convert a comparison if required by the subtarget.
8691 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8692                                                  SelectionDAG &DAG) const {
8693   // If the subtarget does not support the FUCOMI instruction, floating-point
8694   // comparisons have to be converted.
8695   if (Subtarget->hasCMov() ||
8696       Cmp.getOpcode() != X86ISD::CMP ||
8697       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8698       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8699     return Cmp;
8700
8701   // The instruction selector will select an FUCOM instruction instead of
8702   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8703   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8704   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8705   DebugLoc dl = Cmp.getDebugLoc();
8706   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8707   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8708   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8709                             DAG.getConstant(8, MVT::i8));
8710   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8711   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8712 }
8713
8714 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8715 /// if it's possible.
8716 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8717                                      DebugLoc dl, SelectionDAG &DAG) const {
8718   SDValue Op0 = And.getOperand(0);
8719   SDValue Op1 = And.getOperand(1);
8720   if (Op0.getOpcode() == ISD::TRUNCATE)
8721     Op0 = Op0.getOperand(0);
8722   if (Op1.getOpcode() == ISD::TRUNCATE)
8723     Op1 = Op1.getOperand(0);
8724
8725   SDValue LHS, RHS;
8726   if (Op1.getOpcode() == ISD::SHL)
8727     std::swap(Op0, Op1);
8728   if (Op0.getOpcode() == ISD::SHL) {
8729     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8730       if (And00C->getZExtValue() == 1) {
8731         // If we looked past a truncate, check that it's only truncating away
8732         // known zeros.
8733         unsigned BitWidth = Op0.getValueSizeInBits();
8734         unsigned AndBitWidth = And.getValueSizeInBits();
8735         if (BitWidth > AndBitWidth) {
8736           APInt Zeros, Ones;
8737           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8738           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8739             return SDValue();
8740         }
8741         LHS = Op1;
8742         RHS = Op0.getOperand(1);
8743       }
8744   } else if (Op1.getOpcode() == ISD::Constant) {
8745     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8746     uint64_t AndRHSVal = AndRHS->getZExtValue();
8747     SDValue AndLHS = Op0;
8748
8749     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8750       LHS = AndLHS.getOperand(0);
8751       RHS = AndLHS.getOperand(1);
8752     }
8753
8754     // Use BT if the immediate can't be encoded in a TEST instruction.
8755     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8756       LHS = AndLHS;
8757       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8758     }
8759   }
8760
8761   if (LHS.getNode()) {
8762     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8763     // instruction.  Since the shift amount is in-range-or-undefined, we know
8764     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8765     // the encoding for the i16 version is larger than the i32 version.
8766     // Also promote i16 to i32 for performance / code size reason.
8767     if (LHS.getValueType() == MVT::i8 ||
8768         LHS.getValueType() == MVT::i16)
8769       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8770
8771     // If the operand types disagree, extend the shift amount to match.  Since
8772     // BT ignores high bits (like shifts) we can use anyextend.
8773     if (LHS.getValueType() != RHS.getValueType())
8774       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8775
8776     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8777     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8778     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8779                        DAG.getConstant(Cond, MVT::i8), BT);
8780   }
8781
8782   return SDValue();
8783 }
8784
8785 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8786
8787   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8788
8789   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8790   SDValue Op0 = Op.getOperand(0);
8791   SDValue Op1 = Op.getOperand(1);
8792   DebugLoc dl = Op.getDebugLoc();
8793   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8794
8795   // Optimize to BT if possible.
8796   // Lower (X & (1 << N)) == 0 to BT(X, N).
8797   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8798   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8799   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8800       Op1.getOpcode() == ISD::Constant &&
8801       cast<ConstantSDNode>(Op1)->isNullValue() &&
8802       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8803     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8804     if (NewSetCC.getNode())
8805       return NewSetCC;
8806   }
8807
8808   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8809   // these.
8810   if (Op1.getOpcode() == ISD::Constant &&
8811       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8812        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8813       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8814
8815     // If the input is a setcc, then reuse the input setcc or use a new one with
8816     // the inverted condition.
8817     if (Op0.getOpcode() == X86ISD::SETCC) {
8818       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8819       bool Invert = (CC == ISD::SETNE) ^
8820         cast<ConstantSDNode>(Op1)->isNullValue();
8821       if (!Invert) return Op0;
8822
8823       CCode = X86::GetOppositeBranchCondition(CCode);
8824       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8825                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8826     }
8827   }
8828
8829   bool isFP = Op1.getValueType().isFloatingPoint();
8830   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8831   if (X86CC == X86::COND_INVALID)
8832     return SDValue();
8833
8834   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8835   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8836   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8837                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8838 }
8839
8840 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8841 // ones, and then concatenate the result back.
8842 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8843   EVT VT = Op.getValueType();
8844
8845   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8846          "Unsupported value type for operation");
8847
8848   unsigned NumElems = VT.getVectorNumElements();
8849   DebugLoc dl = Op.getDebugLoc();
8850   SDValue CC = Op.getOperand(2);
8851
8852   // Extract the LHS vectors
8853   SDValue LHS = Op.getOperand(0);
8854   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8855   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8856
8857   // Extract the RHS vectors
8858   SDValue RHS = Op.getOperand(1);
8859   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8860   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8861
8862   // Issue the operation on the smaller types and concatenate the result back
8863   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8864   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8865   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8866                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8867                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8868 }
8869
8870
8871 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8872   SDValue Cond;
8873   SDValue Op0 = Op.getOperand(0);
8874   SDValue Op1 = Op.getOperand(1);
8875   SDValue CC = Op.getOperand(2);
8876   EVT VT = Op.getValueType();
8877   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8878   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8879   DebugLoc dl = Op.getDebugLoc();
8880
8881   if (isFP) {
8882 #ifndef NDEBUG
8883     EVT EltVT = Op0.getValueType().getVectorElementType();
8884     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8885 #endif
8886
8887     unsigned SSECC;
8888     bool Swap = false;
8889
8890     // SSE Condition code mapping:
8891     //  0 - EQ
8892     //  1 - LT
8893     //  2 - LE
8894     //  3 - UNORD
8895     //  4 - NEQ
8896     //  5 - NLT
8897     //  6 - NLE
8898     //  7 - ORD
8899     switch (SetCCOpcode) {
8900     default: llvm_unreachable("Unexpected SETCC condition");
8901     case ISD::SETOEQ:
8902     case ISD::SETEQ:  SSECC = 0; break;
8903     case ISD::SETOGT:
8904     case ISD::SETGT: Swap = true; // Fallthrough
8905     case ISD::SETLT:
8906     case ISD::SETOLT: SSECC = 1; break;
8907     case ISD::SETOGE:
8908     case ISD::SETGE: Swap = true; // Fallthrough
8909     case ISD::SETLE:
8910     case ISD::SETOLE: SSECC = 2; break;
8911     case ISD::SETUO:  SSECC = 3; break;
8912     case ISD::SETUNE:
8913     case ISD::SETNE:  SSECC = 4; break;
8914     case ISD::SETULE: Swap = true; // Fallthrough
8915     case ISD::SETUGE: SSECC = 5; break;
8916     case ISD::SETULT: Swap = true; // Fallthrough
8917     case ISD::SETUGT: SSECC = 6; break;
8918     case ISD::SETO:   SSECC = 7; break;
8919     case ISD::SETUEQ:
8920     case ISD::SETONE: SSECC = 8; break;
8921     }
8922     if (Swap)
8923       std::swap(Op0, Op1);
8924
8925     // In the two special cases we can't handle, emit two comparisons.
8926     if (SSECC == 8) {
8927       unsigned CC0, CC1;
8928       unsigned CombineOpc;
8929       if (SetCCOpcode == ISD::SETUEQ) {
8930         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8931       } else {
8932         assert(SetCCOpcode == ISD::SETONE);
8933         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8934       }
8935
8936       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8937                                  DAG.getConstant(CC0, MVT::i8));
8938       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8939                                  DAG.getConstant(CC1, MVT::i8));
8940       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8941     }
8942     // Handle all other FP comparisons here.
8943     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8944                        DAG.getConstant(SSECC, MVT::i8));
8945   }
8946
8947   // Break 256-bit integer vector compare into smaller ones.
8948   if (VT.is256BitVector() && !Subtarget->hasAVX2())
8949     return Lower256IntVSETCC(Op, DAG);
8950
8951   // We are handling one of the integer comparisons here.  Since SSE only has
8952   // GT and EQ comparisons for integer, swapping operands and multiple
8953   // operations may be required for some comparisons.
8954   unsigned Opc;
8955   bool Swap = false, Invert = false, FlipSigns = false;
8956
8957   switch (SetCCOpcode) {
8958   default: llvm_unreachable("Unexpected SETCC condition");
8959   case ISD::SETNE:  Invert = true;
8960   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8961   case ISD::SETLT:  Swap = true;
8962   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8963   case ISD::SETGE:  Swap = true;
8964   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8965   case ISD::SETULT: Swap = true;
8966   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8967   case ISD::SETUGE: Swap = true;
8968   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8969   }
8970   if (Swap)
8971     std::swap(Op0, Op1);
8972
8973   // Check that the operation in question is available (most are plain SSE2,
8974   // but PCMPGTQ and PCMPEQQ have different requirements).
8975   if (VT == MVT::v2i64) {
8976     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8977       return SDValue();
8978     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8979       return SDValue();
8980   }
8981
8982   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8983   // bits of the inputs before performing those operations.
8984   if (FlipSigns) {
8985     EVT EltVT = VT.getVectorElementType();
8986     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8987                                       EltVT);
8988     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8989     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8990                                     SignBits.size());
8991     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8992     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8993   }
8994
8995   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8996
8997   // If the logical-not of the result is required, perform that now.
8998   if (Invert)
8999     Result = DAG.getNOT(dl, Result, VT);
9000
9001   return Result;
9002 }
9003
9004 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9005 static bool isX86LogicalCmp(SDValue Op) {
9006   unsigned Opc = Op.getNode()->getOpcode();
9007   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9008       Opc == X86ISD::SAHF)
9009     return true;
9010   if (Op.getResNo() == 1 &&
9011       (Opc == X86ISD::ADD ||
9012        Opc == X86ISD::SUB ||
9013        Opc == X86ISD::ADC ||
9014        Opc == X86ISD::SBB ||
9015        Opc == X86ISD::SMUL ||
9016        Opc == X86ISD::UMUL ||
9017        Opc == X86ISD::INC ||
9018        Opc == X86ISD::DEC ||
9019        Opc == X86ISD::OR ||
9020        Opc == X86ISD::XOR ||
9021        Opc == X86ISD::AND))
9022     return true;
9023
9024   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9025     return true;
9026
9027   return false;
9028 }
9029
9030 static bool isZero(SDValue V) {
9031   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9032   return C && C->isNullValue();
9033 }
9034
9035 static bool isAllOnes(SDValue V) {
9036   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9037   return C && C->isAllOnesValue();
9038 }
9039
9040 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9041   if (V.getOpcode() != ISD::TRUNCATE)
9042     return false;
9043
9044   SDValue VOp0 = V.getOperand(0);
9045   unsigned InBits = VOp0.getValueSizeInBits();
9046   unsigned Bits = V.getValueSizeInBits();
9047   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9048 }
9049
9050 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9051   bool addTest = true;
9052   SDValue Cond  = Op.getOperand(0);
9053   SDValue Op1 = Op.getOperand(1);
9054   SDValue Op2 = Op.getOperand(2);
9055   DebugLoc DL = Op.getDebugLoc();
9056   SDValue CC;
9057
9058   if (Cond.getOpcode() == ISD::SETCC) {
9059     SDValue NewCond = LowerSETCC(Cond, DAG);
9060     if (NewCond.getNode())
9061       Cond = NewCond;
9062   }
9063
9064   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9065   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9066   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9067   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9068   if (Cond.getOpcode() == X86ISD::SETCC &&
9069       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9070       isZero(Cond.getOperand(1).getOperand(1))) {
9071     SDValue Cmp = Cond.getOperand(1);
9072
9073     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9074
9075     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9076         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9077       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9078
9079       SDValue CmpOp0 = Cmp.getOperand(0);
9080       // Apply further optimizations for special cases
9081       // (select (x != 0), -1, 0) -> neg & sbb
9082       // (select (x == 0), 0, -1) -> neg & sbb
9083       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9084         if (YC->isNullValue() &&
9085             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9086           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9087           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9088                                     DAG.getConstant(0, CmpOp0.getValueType()),
9089                                     CmpOp0);
9090           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9091                                     DAG.getConstant(X86::COND_B, MVT::i8),
9092                                     SDValue(Neg.getNode(), 1));
9093           return Res;
9094         }
9095
9096       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9097                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9098       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9099
9100       SDValue Res =   // Res = 0 or -1.
9101         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9102                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9103
9104       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9105         Res = DAG.getNOT(DL, Res, Res.getValueType());
9106
9107       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9108       if (N2C == 0 || !N2C->isNullValue())
9109         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9110       return Res;
9111     }
9112   }
9113
9114   // Look past (and (setcc_carry (cmp ...)), 1).
9115   if (Cond.getOpcode() == ISD::AND &&
9116       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9117     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9118     if (C && C->getAPIntValue() == 1)
9119       Cond = Cond.getOperand(0);
9120   }
9121
9122   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9123   // setting operand in place of the X86ISD::SETCC.
9124   unsigned CondOpcode = Cond.getOpcode();
9125   if (CondOpcode == X86ISD::SETCC ||
9126       CondOpcode == X86ISD::SETCC_CARRY) {
9127     CC = Cond.getOperand(0);
9128
9129     SDValue Cmp = Cond.getOperand(1);
9130     unsigned Opc = Cmp.getOpcode();
9131     EVT VT = Op.getValueType();
9132
9133     bool IllegalFPCMov = false;
9134     if (VT.isFloatingPoint() && !VT.isVector() &&
9135         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9136       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9137
9138     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9139         Opc == X86ISD::BT) { // FIXME
9140       Cond = Cmp;
9141       addTest = false;
9142     }
9143   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9144              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9145              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9146               Cond.getOperand(0).getValueType() != MVT::i8)) {
9147     SDValue LHS = Cond.getOperand(0);
9148     SDValue RHS = Cond.getOperand(1);
9149     unsigned X86Opcode;
9150     unsigned X86Cond;
9151     SDVTList VTs;
9152     switch (CondOpcode) {
9153     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9154     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9155     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9156     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9157     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9158     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9159     default: llvm_unreachable("unexpected overflowing operator");
9160     }
9161     if (CondOpcode == ISD::UMULO)
9162       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9163                           MVT::i32);
9164     else
9165       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9166
9167     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9168
9169     if (CondOpcode == ISD::UMULO)
9170       Cond = X86Op.getValue(2);
9171     else
9172       Cond = X86Op.getValue(1);
9173
9174     CC = DAG.getConstant(X86Cond, MVT::i8);
9175     addTest = false;
9176   }
9177
9178   if (addTest) {
9179     // Look pass the truncate if the high bits are known zero.
9180     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9181         Cond = Cond.getOperand(0);
9182
9183     // We know the result of AND is compared against zero. Try to match
9184     // it to BT.
9185     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9186       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9187       if (NewSetCC.getNode()) {
9188         CC = NewSetCC.getOperand(0);
9189         Cond = NewSetCC.getOperand(1);
9190         addTest = false;
9191       }
9192     }
9193   }
9194
9195   if (addTest) {
9196     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9197     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9198   }
9199
9200   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9201   // a <  b ?  0 : -1 -> RES = setcc_carry
9202   // a >= b ? -1 :  0 -> RES = setcc_carry
9203   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9204   if (Cond.getOpcode() == X86ISD::SUB) {
9205     Cond = ConvertCmpIfNecessary(Cond, DAG);
9206     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9207
9208     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9209         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9210       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9211                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9212       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9213         return DAG.getNOT(DL, Res, Res.getValueType());
9214       return Res;
9215     }
9216   }
9217
9218   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9219   // condition is true.
9220   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9221   SDValue Ops[] = { Op2, Op1, CC, Cond };
9222   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9223 }
9224
9225 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9226 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9227 // from the AND / OR.
9228 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9229   Opc = Op.getOpcode();
9230   if (Opc != ISD::OR && Opc != ISD::AND)
9231     return false;
9232   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9233           Op.getOperand(0).hasOneUse() &&
9234           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9235           Op.getOperand(1).hasOneUse());
9236 }
9237
9238 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9239 // 1 and that the SETCC node has a single use.
9240 static bool isXor1OfSetCC(SDValue Op) {
9241   if (Op.getOpcode() != ISD::XOR)
9242     return false;
9243   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9244   if (N1C && N1C->getAPIntValue() == 1) {
9245     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9246       Op.getOperand(0).hasOneUse();
9247   }
9248   return false;
9249 }
9250
9251 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9252   bool addTest = true;
9253   SDValue Chain = Op.getOperand(0);
9254   SDValue Cond  = Op.getOperand(1);
9255   SDValue Dest  = Op.getOperand(2);
9256   DebugLoc dl = Op.getDebugLoc();
9257   SDValue CC;
9258   bool Inverted = false;
9259
9260   if (Cond.getOpcode() == ISD::SETCC) {
9261     // Check for setcc([su]{add,sub,mul}o == 0).
9262     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9263         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9264         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9265         Cond.getOperand(0).getResNo() == 1 &&
9266         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9267          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9268          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9269          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9270          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9271          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9272       Inverted = true;
9273       Cond = Cond.getOperand(0);
9274     } else {
9275       SDValue NewCond = LowerSETCC(Cond, DAG);
9276       if (NewCond.getNode())
9277         Cond = NewCond;
9278     }
9279   }
9280 #if 0
9281   // FIXME: LowerXALUO doesn't handle these!!
9282   else if (Cond.getOpcode() == X86ISD::ADD  ||
9283            Cond.getOpcode() == X86ISD::SUB  ||
9284            Cond.getOpcode() == X86ISD::SMUL ||
9285            Cond.getOpcode() == X86ISD::UMUL)
9286     Cond = LowerXALUO(Cond, DAG);
9287 #endif
9288
9289   // Look pass (and (setcc_carry (cmp ...)), 1).
9290   if (Cond.getOpcode() == ISD::AND &&
9291       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9292     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9293     if (C && C->getAPIntValue() == 1)
9294       Cond = Cond.getOperand(0);
9295   }
9296
9297   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9298   // setting operand in place of the X86ISD::SETCC.
9299   unsigned CondOpcode = Cond.getOpcode();
9300   if (CondOpcode == X86ISD::SETCC ||
9301       CondOpcode == X86ISD::SETCC_CARRY) {
9302     CC = Cond.getOperand(0);
9303
9304     SDValue Cmp = Cond.getOperand(1);
9305     unsigned Opc = Cmp.getOpcode();
9306     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9307     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9308       Cond = Cmp;
9309       addTest = false;
9310     } else {
9311       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9312       default: break;
9313       case X86::COND_O:
9314       case X86::COND_B:
9315         // These can only come from an arithmetic instruction with overflow,
9316         // e.g. SADDO, UADDO.
9317         Cond = Cond.getNode()->getOperand(1);
9318         addTest = false;
9319         break;
9320       }
9321     }
9322   }
9323   CondOpcode = Cond.getOpcode();
9324   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9325       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9326       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9327        Cond.getOperand(0).getValueType() != MVT::i8)) {
9328     SDValue LHS = Cond.getOperand(0);
9329     SDValue RHS = Cond.getOperand(1);
9330     unsigned X86Opcode;
9331     unsigned X86Cond;
9332     SDVTList VTs;
9333     switch (CondOpcode) {
9334     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9335     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9336     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9337     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9338     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9339     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9340     default: llvm_unreachable("unexpected overflowing operator");
9341     }
9342     if (Inverted)
9343       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9344     if (CondOpcode == ISD::UMULO)
9345       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9346                           MVT::i32);
9347     else
9348       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9349
9350     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9351
9352     if (CondOpcode == ISD::UMULO)
9353       Cond = X86Op.getValue(2);
9354     else
9355       Cond = X86Op.getValue(1);
9356
9357     CC = DAG.getConstant(X86Cond, MVT::i8);
9358     addTest = false;
9359   } else {
9360     unsigned CondOpc;
9361     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9362       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9363       if (CondOpc == ISD::OR) {
9364         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9365         // two branches instead of an explicit OR instruction with a
9366         // separate test.
9367         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9368             isX86LogicalCmp(Cmp)) {
9369           CC = Cond.getOperand(0).getOperand(0);
9370           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9371                               Chain, Dest, CC, Cmp);
9372           CC = Cond.getOperand(1).getOperand(0);
9373           Cond = Cmp;
9374           addTest = false;
9375         }
9376       } else { // ISD::AND
9377         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9378         // two branches instead of an explicit AND instruction with a
9379         // separate test. However, we only do this if this block doesn't
9380         // have a fall-through edge, because this requires an explicit
9381         // jmp when the condition is false.
9382         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9383             isX86LogicalCmp(Cmp) &&
9384             Op.getNode()->hasOneUse()) {
9385           X86::CondCode CCode =
9386             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9387           CCode = X86::GetOppositeBranchCondition(CCode);
9388           CC = DAG.getConstant(CCode, MVT::i8);
9389           SDNode *User = *Op.getNode()->use_begin();
9390           // Look for an unconditional branch following this conditional branch.
9391           // We need this because we need to reverse the successors in order
9392           // to implement FCMP_OEQ.
9393           if (User->getOpcode() == ISD::BR) {
9394             SDValue FalseBB = User->getOperand(1);
9395             SDNode *NewBR =
9396               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9397             assert(NewBR == User);
9398             (void)NewBR;
9399             Dest = FalseBB;
9400
9401             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9402                                 Chain, Dest, CC, Cmp);
9403             X86::CondCode CCode =
9404               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9405             CCode = X86::GetOppositeBranchCondition(CCode);
9406             CC = DAG.getConstant(CCode, MVT::i8);
9407             Cond = Cmp;
9408             addTest = false;
9409           }
9410         }
9411       }
9412     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9413       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9414       // It should be transformed during dag combiner except when the condition
9415       // is set by a arithmetics with overflow node.
9416       X86::CondCode CCode =
9417         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9418       CCode = X86::GetOppositeBranchCondition(CCode);
9419       CC = DAG.getConstant(CCode, MVT::i8);
9420       Cond = Cond.getOperand(0).getOperand(1);
9421       addTest = false;
9422     } else if (Cond.getOpcode() == ISD::SETCC &&
9423                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9424       // For FCMP_OEQ, we can emit
9425       // two branches instead of an explicit AND instruction with a
9426       // separate test. However, we only do this if this block doesn't
9427       // have a fall-through edge, because this requires an explicit
9428       // jmp when the condition is false.
9429       if (Op.getNode()->hasOneUse()) {
9430         SDNode *User = *Op.getNode()->use_begin();
9431         // Look for an unconditional branch following this conditional branch.
9432         // We need this because we need to reverse the successors in order
9433         // to implement FCMP_OEQ.
9434         if (User->getOpcode() == ISD::BR) {
9435           SDValue FalseBB = User->getOperand(1);
9436           SDNode *NewBR =
9437             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9438           assert(NewBR == User);
9439           (void)NewBR;
9440           Dest = FalseBB;
9441
9442           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9443                                     Cond.getOperand(0), Cond.getOperand(1));
9444           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9445           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9446           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9447                               Chain, Dest, CC, Cmp);
9448           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9449           Cond = Cmp;
9450           addTest = false;
9451         }
9452       }
9453     } else if (Cond.getOpcode() == ISD::SETCC &&
9454                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9455       // For FCMP_UNE, we can emit
9456       // two branches instead of an explicit AND instruction with a
9457       // separate test. However, we only do this if this block doesn't
9458       // have a fall-through edge, because this requires an explicit
9459       // jmp when the condition is false.
9460       if (Op.getNode()->hasOneUse()) {
9461         SDNode *User = *Op.getNode()->use_begin();
9462         // Look for an unconditional branch following this conditional branch.
9463         // We need this because we need to reverse the successors in order
9464         // to implement FCMP_UNE.
9465         if (User->getOpcode() == ISD::BR) {
9466           SDValue FalseBB = User->getOperand(1);
9467           SDNode *NewBR =
9468             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9469           assert(NewBR == User);
9470           (void)NewBR;
9471
9472           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9473                                     Cond.getOperand(0), Cond.getOperand(1));
9474           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9475           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9476           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9477                               Chain, Dest, CC, Cmp);
9478           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9479           Cond = Cmp;
9480           addTest = false;
9481           Dest = FalseBB;
9482         }
9483       }
9484     }
9485   }
9486
9487   if (addTest) {
9488     // Look pass the truncate if the high bits are known zero.
9489     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9490         Cond = Cond.getOperand(0);
9491
9492     // We know the result of AND is compared against zero. Try to match
9493     // it to BT.
9494     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9495       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9496       if (NewSetCC.getNode()) {
9497         CC = NewSetCC.getOperand(0);
9498         Cond = NewSetCC.getOperand(1);
9499         addTest = false;
9500       }
9501     }
9502   }
9503
9504   if (addTest) {
9505     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9506     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9507   }
9508   Cond = ConvertCmpIfNecessary(Cond, DAG);
9509   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9510                      Chain, Dest, CC, Cond);
9511 }
9512
9513
9514 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9515 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9516 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9517 // that the guard pages used by the OS virtual memory manager are allocated in
9518 // correct sequence.
9519 SDValue
9520 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9521                                            SelectionDAG &DAG) const {
9522   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9523           getTargetMachine().Options.EnableSegmentedStacks) &&
9524          "This should be used only on Windows targets or when segmented stacks "
9525          "are being used");
9526   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9527   DebugLoc dl = Op.getDebugLoc();
9528
9529   // Get the inputs.
9530   SDValue Chain = Op.getOperand(0);
9531   SDValue Size  = Op.getOperand(1);
9532   // FIXME: Ensure alignment here
9533
9534   bool Is64Bit = Subtarget->is64Bit();
9535   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9536
9537   if (getTargetMachine().Options.EnableSegmentedStacks) {
9538     MachineFunction &MF = DAG.getMachineFunction();
9539     MachineRegisterInfo &MRI = MF.getRegInfo();
9540
9541     if (Is64Bit) {
9542       // The 64 bit implementation of segmented stacks needs to clobber both r10
9543       // r11. This makes it impossible to use it along with nested parameters.
9544       const Function *F = MF.getFunction();
9545
9546       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9547            I != E; ++I)
9548         if (I->hasNestAttr())
9549           report_fatal_error("Cannot use segmented stacks with functions that "
9550                              "have nested arguments.");
9551     }
9552
9553     const TargetRegisterClass *AddrRegClass =
9554       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9555     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9556     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9557     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9558                                 DAG.getRegister(Vreg, SPTy));
9559     SDValue Ops1[2] = { Value, Chain };
9560     return DAG.getMergeValues(Ops1, 2, dl);
9561   } else {
9562     SDValue Flag;
9563     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9564
9565     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9566     Flag = Chain.getValue(1);
9567     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9568
9569     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9570     Flag = Chain.getValue(1);
9571
9572     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9573
9574     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9575     return DAG.getMergeValues(Ops1, 2, dl);
9576   }
9577 }
9578
9579 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9580   MachineFunction &MF = DAG.getMachineFunction();
9581   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9582
9583   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9584   DebugLoc DL = Op.getDebugLoc();
9585
9586   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9587     // vastart just stores the address of the VarArgsFrameIndex slot into the
9588     // memory location argument.
9589     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9590                                    getPointerTy());
9591     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9592                         MachinePointerInfo(SV), false, false, 0);
9593   }
9594
9595   // __va_list_tag:
9596   //   gp_offset         (0 - 6 * 8)
9597   //   fp_offset         (48 - 48 + 8 * 16)
9598   //   overflow_arg_area (point to parameters coming in memory).
9599   //   reg_save_area
9600   SmallVector<SDValue, 8> MemOps;
9601   SDValue FIN = Op.getOperand(1);
9602   // Store gp_offset
9603   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9604                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9605                                                MVT::i32),
9606                                FIN, MachinePointerInfo(SV), false, false, 0);
9607   MemOps.push_back(Store);
9608
9609   // Store fp_offset
9610   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9611                     FIN, DAG.getIntPtrConstant(4));
9612   Store = DAG.getStore(Op.getOperand(0), DL,
9613                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9614                                        MVT::i32),
9615                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9616   MemOps.push_back(Store);
9617
9618   // Store ptr to overflow_arg_area
9619   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9620                     FIN, DAG.getIntPtrConstant(4));
9621   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9622                                     getPointerTy());
9623   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9624                        MachinePointerInfo(SV, 8),
9625                        false, false, 0);
9626   MemOps.push_back(Store);
9627
9628   // Store ptr to reg_save_area.
9629   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9630                     FIN, DAG.getIntPtrConstant(8));
9631   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9632                                     getPointerTy());
9633   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9634                        MachinePointerInfo(SV, 16), false, false, 0);
9635   MemOps.push_back(Store);
9636   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9637                      &MemOps[0], MemOps.size());
9638 }
9639
9640 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9641   assert(Subtarget->is64Bit() &&
9642          "LowerVAARG only handles 64-bit va_arg!");
9643   assert((Subtarget->isTargetLinux() ||
9644           Subtarget->isTargetDarwin()) &&
9645           "Unhandled target in LowerVAARG");
9646   assert(Op.getNode()->getNumOperands() == 4);
9647   SDValue Chain = Op.getOperand(0);
9648   SDValue SrcPtr = Op.getOperand(1);
9649   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9650   unsigned Align = Op.getConstantOperandVal(3);
9651   DebugLoc dl = Op.getDebugLoc();
9652
9653   EVT ArgVT = Op.getNode()->getValueType(0);
9654   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9655   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9656   uint8_t ArgMode;
9657
9658   // Decide which area this value should be read from.
9659   // TODO: Implement the AMD64 ABI in its entirety. This simple
9660   // selection mechanism works only for the basic types.
9661   if (ArgVT == MVT::f80) {
9662     llvm_unreachable("va_arg for f80 not yet implemented");
9663   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9664     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9665   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9666     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9667   } else {
9668     llvm_unreachable("Unhandled argument type in LowerVAARG");
9669   }
9670
9671   if (ArgMode == 2) {
9672     // Sanity Check: Make sure using fp_offset makes sense.
9673     assert(!getTargetMachine().Options.UseSoftFloat &&
9674            !(DAG.getMachineFunction()
9675                 .getFunction()->getFnAttributes()
9676                 .hasAttribute(Attributes::NoImplicitFloat)) &&
9677            Subtarget->hasSSE1());
9678   }
9679
9680   // Insert VAARG_64 node into the DAG
9681   // VAARG_64 returns two values: Variable Argument Address, Chain
9682   SmallVector<SDValue, 11> InstOps;
9683   InstOps.push_back(Chain);
9684   InstOps.push_back(SrcPtr);
9685   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9686   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9687   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9688   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9689   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9690                                           VTs, &InstOps[0], InstOps.size(),
9691                                           MVT::i64,
9692                                           MachinePointerInfo(SV),
9693                                           /*Align=*/0,
9694                                           /*Volatile=*/false,
9695                                           /*ReadMem=*/true,
9696                                           /*WriteMem=*/true);
9697   Chain = VAARG.getValue(1);
9698
9699   // Load the next argument and return it
9700   return DAG.getLoad(ArgVT, dl,
9701                      Chain,
9702                      VAARG,
9703                      MachinePointerInfo(),
9704                      false, false, false, 0);
9705 }
9706
9707 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9708                            SelectionDAG &DAG) {
9709   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9710   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9711   SDValue Chain = Op.getOperand(0);
9712   SDValue DstPtr = Op.getOperand(1);
9713   SDValue SrcPtr = Op.getOperand(2);
9714   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9715   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9716   DebugLoc DL = Op.getDebugLoc();
9717
9718   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9719                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9720                        false,
9721                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9722 }
9723
9724 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9725 // may or may not be a constant. Takes immediate version of shift as input.
9726 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9727                                    SDValue SrcOp, SDValue ShAmt,
9728                                    SelectionDAG &DAG) {
9729   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9730
9731   if (isa<ConstantSDNode>(ShAmt)) {
9732     // Constant may be a TargetConstant. Use a regular constant.
9733     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9734     switch (Opc) {
9735       default: llvm_unreachable("Unknown target vector shift node");
9736       case X86ISD::VSHLI:
9737       case X86ISD::VSRLI:
9738       case X86ISD::VSRAI:
9739         return DAG.getNode(Opc, dl, VT, SrcOp,
9740                            DAG.getConstant(ShiftAmt, MVT::i32));
9741     }
9742   }
9743
9744   // Change opcode to non-immediate version
9745   switch (Opc) {
9746     default: llvm_unreachable("Unknown target vector shift node");
9747     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9748     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9749     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9750   }
9751
9752   // Need to build a vector containing shift amount
9753   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9754   SDValue ShOps[4];
9755   ShOps[0] = ShAmt;
9756   ShOps[1] = DAG.getConstant(0, MVT::i32);
9757   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9758   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9759
9760   // The return type has to be a 128-bit type with the same element
9761   // type as the input type.
9762   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9763   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9764
9765   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9766   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9767 }
9768
9769 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9770   DebugLoc dl = Op.getDebugLoc();
9771   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9772   switch (IntNo) {
9773   default: return SDValue();    // Don't custom lower most intrinsics.
9774   // Comparison intrinsics.
9775   case Intrinsic::x86_sse_comieq_ss:
9776   case Intrinsic::x86_sse_comilt_ss:
9777   case Intrinsic::x86_sse_comile_ss:
9778   case Intrinsic::x86_sse_comigt_ss:
9779   case Intrinsic::x86_sse_comige_ss:
9780   case Intrinsic::x86_sse_comineq_ss:
9781   case Intrinsic::x86_sse_ucomieq_ss:
9782   case Intrinsic::x86_sse_ucomilt_ss:
9783   case Intrinsic::x86_sse_ucomile_ss:
9784   case Intrinsic::x86_sse_ucomigt_ss:
9785   case Intrinsic::x86_sse_ucomige_ss:
9786   case Intrinsic::x86_sse_ucomineq_ss:
9787   case Intrinsic::x86_sse2_comieq_sd:
9788   case Intrinsic::x86_sse2_comilt_sd:
9789   case Intrinsic::x86_sse2_comile_sd:
9790   case Intrinsic::x86_sse2_comigt_sd:
9791   case Intrinsic::x86_sse2_comige_sd:
9792   case Intrinsic::x86_sse2_comineq_sd:
9793   case Intrinsic::x86_sse2_ucomieq_sd:
9794   case Intrinsic::x86_sse2_ucomilt_sd:
9795   case Intrinsic::x86_sse2_ucomile_sd:
9796   case Intrinsic::x86_sse2_ucomigt_sd:
9797   case Intrinsic::x86_sse2_ucomige_sd:
9798   case Intrinsic::x86_sse2_ucomineq_sd: {
9799     unsigned Opc;
9800     ISD::CondCode CC;
9801     switch (IntNo) {
9802     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9803     case Intrinsic::x86_sse_comieq_ss:
9804     case Intrinsic::x86_sse2_comieq_sd:
9805       Opc = X86ISD::COMI;
9806       CC = ISD::SETEQ;
9807       break;
9808     case Intrinsic::x86_sse_comilt_ss:
9809     case Intrinsic::x86_sse2_comilt_sd:
9810       Opc = X86ISD::COMI;
9811       CC = ISD::SETLT;
9812       break;
9813     case Intrinsic::x86_sse_comile_ss:
9814     case Intrinsic::x86_sse2_comile_sd:
9815       Opc = X86ISD::COMI;
9816       CC = ISD::SETLE;
9817       break;
9818     case Intrinsic::x86_sse_comigt_ss:
9819     case Intrinsic::x86_sse2_comigt_sd:
9820       Opc = X86ISD::COMI;
9821       CC = ISD::SETGT;
9822       break;
9823     case Intrinsic::x86_sse_comige_ss:
9824     case Intrinsic::x86_sse2_comige_sd:
9825       Opc = X86ISD::COMI;
9826       CC = ISD::SETGE;
9827       break;
9828     case Intrinsic::x86_sse_comineq_ss:
9829     case Intrinsic::x86_sse2_comineq_sd:
9830       Opc = X86ISD::COMI;
9831       CC = ISD::SETNE;
9832       break;
9833     case Intrinsic::x86_sse_ucomieq_ss:
9834     case Intrinsic::x86_sse2_ucomieq_sd:
9835       Opc = X86ISD::UCOMI;
9836       CC = ISD::SETEQ;
9837       break;
9838     case Intrinsic::x86_sse_ucomilt_ss:
9839     case Intrinsic::x86_sse2_ucomilt_sd:
9840       Opc = X86ISD::UCOMI;
9841       CC = ISD::SETLT;
9842       break;
9843     case Intrinsic::x86_sse_ucomile_ss:
9844     case Intrinsic::x86_sse2_ucomile_sd:
9845       Opc = X86ISD::UCOMI;
9846       CC = ISD::SETLE;
9847       break;
9848     case Intrinsic::x86_sse_ucomigt_ss:
9849     case Intrinsic::x86_sse2_ucomigt_sd:
9850       Opc = X86ISD::UCOMI;
9851       CC = ISD::SETGT;
9852       break;
9853     case Intrinsic::x86_sse_ucomige_ss:
9854     case Intrinsic::x86_sse2_ucomige_sd:
9855       Opc = X86ISD::UCOMI;
9856       CC = ISD::SETGE;
9857       break;
9858     case Intrinsic::x86_sse_ucomineq_ss:
9859     case Intrinsic::x86_sse2_ucomineq_sd:
9860       Opc = X86ISD::UCOMI;
9861       CC = ISD::SETNE;
9862       break;
9863     }
9864
9865     SDValue LHS = Op.getOperand(1);
9866     SDValue RHS = Op.getOperand(2);
9867     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9868     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9869     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9870     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9871                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9872     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9873   }
9874
9875   // Arithmetic intrinsics.
9876   case Intrinsic::x86_sse2_pmulu_dq:
9877   case Intrinsic::x86_avx2_pmulu_dq:
9878     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9879                        Op.getOperand(1), Op.getOperand(2));
9880
9881   // SSE3/AVX horizontal add/sub intrinsics
9882   case Intrinsic::x86_sse3_hadd_ps:
9883   case Intrinsic::x86_sse3_hadd_pd:
9884   case Intrinsic::x86_avx_hadd_ps_256:
9885   case Intrinsic::x86_avx_hadd_pd_256:
9886   case Intrinsic::x86_sse3_hsub_ps:
9887   case Intrinsic::x86_sse3_hsub_pd:
9888   case Intrinsic::x86_avx_hsub_ps_256:
9889   case Intrinsic::x86_avx_hsub_pd_256:
9890   case Intrinsic::x86_ssse3_phadd_w_128:
9891   case Intrinsic::x86_ssse3_phadd_d_128:
9892   case Intrinsic::x86_avx2_phadd_w:
9893   case Intrinsic::x86_avx2_phadd_d:
9894   case Intrinsic::x86_ssse3_phsub_w_128:
9895   case Intrinsic::x86_ssse3_phsub_d_128:
9896   case Intrinsic::x86_avx2_phsub_w:
9897   case Intrinsic::x86_avx2_phsub_d: {
9898     unsigned Opcode;
9899     switch (IntNo) {
9900     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9901     case Intrinsic::x86_sse3_hadd_ps:
9902     case Intrinsic::x86_sse3_hadd_pd:
9903     case Intrinsic::x86_avx_hadd_ps_256:
9904     case Intrinsic::x86_avx_hadd_pd_256:
9905       Opcode = X86ISD::FHADD;
9906       break;
9907     case Intrinsic::x86_sse3_hsub_ps:
9908     case Intrinsic::x86_sse3_hsub_pd:
9909     case Intrinsic::x86_avx_hsub_ps_256:
9910     case Intrinsic::x86_avx_hsub_pd_256:
9911       Opcode = X86ISD::FHSUB;
9912       break;
9913     case Intrinsic::x86_ssse3_phadd_w_128:
9914     case Intrinsic::x86_ssse3_phadd_d_128:
9915     case Intrinsic::x86_avx2_phadd_w:
9916     case Intrinsic::x86_avx2_phadd_d:
9917       Opcode = X86ISD::HADD;
9918       break;
9919     case Intrinsic::x86_ssse3_phsub_w_128:
9920     case Intrinsic::x86_ssse3_phsub_d_128:
9921     case Intrinsic::x86_avx2_phsub_w:
9922     case Intrinsic::x86_avx2_phsub_d:
9923       Opcode = X86ISD::HSUB;
9924       break;
9925     }
9926     return DAG.getNode(Opcode, dl, Op.getValueType(),
9927                        Op.getOperand(1), Op.getOperand(2));
9928   }
9929
9930   // AVX2 variable shift intrinsics
9931   case Intrinsic::x86_avx2_psllv_d:
9932   case Intrinsic::x86_avx2_psllv_q:
9933   case Intrinsic::x86_avx2_psllv_d_256:
9934   case Intrinsic::x86_avx2_psllv_q_256:
9935   case Intrinsic::x86_avx2_psrlv_d:
9936   case Intrinsic::x86_avx2_psrlv_q:
9937   case Intrinsic::x86_avx2_psrlv_d_256:
9938   case Intrinsic::x86_avx2_psrlv_q_256:
9939   case Intrinsic::x86_avx2_psrav_d:
9940   case Intrinsic::x86_avx2_psrav_d_256: {
9941     unsigned Opcode;
9942     switch (IntNo) {
9943     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9944     case Intrinsic::x86_avx2_psllv_d:
9945     case Intrinsic::x86_avx2_psllv_q:
9946     case Intrinsic::x86_avx2_psllv_d_256:
9947     case Intrinsic::x86_avx2_psllv_q_256:
9948       Opcode = ISD::SHL;
9949       break;
9950     case Intrinsic::x86_avx2_psrlv_d:
9951     case Intrinsic::x86_avx2_psrlv_q:
9952     case Intrinsic::x86_avx2_psrlv_d_256:
9953     case Intrinsic::x86_avx2_psrlv_q_256:
9954       Opcode = ISD::SRL;
9955       break;
9956     case Intrinsic::x86_avx2_psrav_d:
9957     case Intrinsic::x86_avx2_psrav_d_256:
9958       Opcode = ISD::SRA;
9959       break;
9960     }
9961     return DAG.getNode(Opcode, dl, Op.getValueType(),
9962                        Op.getOperand(1), Op.getOperand(2));
9963   }
9964
9965   case Intrinsic::x86_ssse3_pshuf_b_128:
9966   case Intrinsic::x86_avx2_pshuf_b:
9967     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9968                        Op.getOperand(1), Op.getOperand(2));
9969
9970   case Intrinsic::x86_ssse3_psign_b_128:
9971   case Intrinsic::x86_ssse3_psign_w_128:
9972   case Intrinsic::x86_ssse3_psign_d_128:
9973   case Intrinsic::x86_avx2_psign_b:
9974   case Intrinsic::x86_avx2_psign_w:
9975   case Intrinsic::x86_avx2_psign_d:
9976     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9977                        Op.getOperand(1), Op.getOperand(2));
9978
9979   case Intrinsic::x86_sse41_insertps:
9980     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9981                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9982
9983   case Intrinsic::x86_avx_vperm2f128_ps_256:
9984   case Intrinsic::x86_avx_vperm2f128_pd_256:
9985   case Intrinsic::x86_avx_vperm2f128_si_256:
9986   case Intrinsic::x86_avx2_vperm2i128:
9987     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9988                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9989
9990   case Intrinsic::x86_avx2_permd:
9991   case Intrinsic::x86_avx2_permps:
9992     // Operands intentionally swapped. Mask is last operand to intrinsic,
9993     // but second operand for node/intruction.
9994     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9995                        Op.getOperand(2), Op.getOperand(1));
9996
9997   // ptest and testp intrinsics. The intrinsic these come from are designed to
9998   // return an integer value, not just an instruction so lower it to the ptest
9999   // or testp pattern and a setcc for the result.
10000   case Intrinsic::x86_sse41_ptestz:
10001   case Intrinsic::x86_sse41_ptestc:
10002   case Intrinsic::x86_sse41_ptestnzc:
10003   case Intrinsic::x86_avx_ptestz_256:
10004   case Intrinsic::x86_avx_ptestc_256:
10005   case Intrinsic::x86_avx_ptestnzc_256:
10006   case Intrinsic::x86_avx_vtestz_ps:
10007   case Intrinsic::x86_avx_vtestc_ps:
10008   case Intrinsic::x86_avx_vtestnzc_ps:
10009   case Intrinsic::x86_avx_vtestz_pd:
10010   case Intrinsic::x86_avx_vtestc_pd:
10011   case Intrinsic::x86_avx_vtestnzc_pd:
10012   case Intrinsic::x86_avx_vtestz_ps_256:
10013   case Intrinsic::x86_avx_vtestc_ps_256:
10014   case Intrinsic::x86_avx_vtestnzc_ps_256:
10015   case Intrinsic::x86_avx_vtestz_pd_256:
10016   case Intrinsic::x86_avx_vtestc_pd_256:
10017   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10018     bool IsTestPacked = false;
10019     unsigned X86CC;
10020     switch (IntNo) {
10021     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10022     case Intrinsic::x86_avx_vtestz_ps:
10023     case Intrinsic::x86_avx_vtestz_pd:
10024     case Intrinsic::x86_avx_vtestz_ps_256:
10025     case Intrinsic::x86_avx_vtestz_pd_256:
10026       IsTestPacked = true; // Fallthrough
10027     case Intrinsic::x86_sse41_ptestz:
10028     case Intrinsic::x86_avx_ptestz_256:
10029       // ZF = 1
10030       X86CC = X86::COND_E;
10031       break;
10032     case Intrinsic::x86_avx_vtestc_ps:
10033     case Intrinsic::x86_avx_vtestc_pd:
10034     case Intrinsic::x86_avx_vtestc_ps_256:
10035     case Intrinsic::x86_avx_vtestc_pd_256:
10036       IsTestPacked = true; // Fallthrough
10037     case Intrinsic::x86_sse41_ptestc:
10038     case Intrinsic::x86_avx_ptestc_256:
10039       // CF = 1
10040       X86CC = X86::COND_B;
10041       break;
10042     case Intrinsic::x86_avx_vtestnzc_ps:
10043     case Intrinsic::x86_avx_vtestnzc_pd:
10044     case Intrinsic::x86_avx_vtestnzc_ps_256:
10045     case Intrinsic::x86_avx_vtestnzc_pd_256:
10046       IsTestPacked = true; // Fallthrough
10047     case Intrinsic::x86_sse41_ptestnzc:
10048     case Intrinsic::x86_avx_ptestnzc_256:
10049       // ZF and CF = 0
10050       X86CC = X86::COND_A;
10051       break;
10052     }
10053
10054     SDValue LHS = Op.getOperand(1);
10055     SDValue RHS = Op.getOperand(2);
10056     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10057     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10058     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10059     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10060     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10061   }
10062
10063   // SSE/AVX shift intrinsics
10064   case Intrinsic::x86_sse2_psll_w:
10065   case Intrinsic::x86_sse2_psll_d:
10066   case Intrinsic::x86_sse2_psll_q:
10067   case Intrinsic::x86_avx2_psll_w:
10068   case Intrinsic::x86_avx2_psll_d:
10069   case Intrinsic::x86_avx2_psll_q:
10070   case Intrinsic::x86_sse2_psrl_w:
10071   case Intrinsic::x86_sse2_psrl_d:
10072   case Intrinsic::x86_sse2_psrl_q:
10073   case Intrinsic::x86_avx2_psrl_w:
10074   case Intrinsic::x86_avx2_psrl_d:
10075   case Intrinsic::x86_avx2_psrl_q:
10076   case Intrinsic::x86_sse2_psra_w:
10077   case Intrinsic::x86_sse2_psra_d:
10078   case Intrinsic::x86_avx2_psra_w:
10079   case Intrinsic::x86_avx2_psra_d: {
10080     unsigned Opcode;
10081     switch (IntNo) {
10082     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10083     case Intrinsic::x86_sse2_psll_w:
10084     case Intrinsic::x86_sse2_psll_d:
10085     case Intrinsic::x86_sse2_psll_q:
10086     case Intrinsic::x86_avx2_psll_w:
10087     case Intrinsic::x86_avx2_psll_d:
10088     case Intrinsic::x86_avx2_psll_q:
10089       Opcode = X86ISD::VSHL;
10090       break;
10091     case Intrinsic::x86_sse2_psrl_w:
10092     case Intrinsic::x86_sse2_psrl_d:
10093     case Intrinsic::x86_sse2_psrl_q:
10094     case Intrinsic::x86_avx2_psrl_w:
10095     case Intrinsic::x86_avx2_psrl_d:
10096     case Intrinsic::x86_avx2_psrl_q:
10097       Opcode = X86ISD::VSRL;
10098       break;
10099     case Intrinsic::x86_sse2_psra_w:
10100     case Intrinsic::x86_sse2_psra_d:
10101     case Intrinsic::x86_avx2_psra_w:
10102     case Intrinsic::x86_avx2_psra_d:
10103       Opcode = X86ISD::VSRA;
10104       break;
10105     }
10106     return DAG.getNode(Opcode, dl, Op.getValueType(),
10107                        Op.getOperand(1), Op.getOperand(2));
10108   }
10109
10110   // SSE/AVX immediate shift intrinsics
10111   case Intrinsic::x86_sse2_pslli_w:
10112   case Intrinsic::x86_sse2_pslli_d:
10113   case Intrinsic::x86_sse2_pslli_q:
10114   case Intrinsic::x86_avx2_pslli_w:
10115   case Intrinsic::x86_avx2_pslli_d:
10116   case Intrinsic::x86_avx2_pslli_q:
10117   case Intrinsic::x86_sse2_psrli_w:
10118   case Intrinsic::x86_sse2_psrli_d:
10119   case Intrinsic::x86_sse2_psrli_q:
10120   case Intrinsic::x86_avx2_psrli_w:
10121   case Intrinsic::x86_avx2_psrli_d:
10122   case Intrinsic::x86_avx2_psrli_q:
10123   case Intrinsic::x86_sse2_psrai_w:
10124   case Intrinsic::x86_sse2_psrai_d:
10125   case Intrinsic::x86_avx2_psrai_w:
10126   case Intrinsic::x86_avx2_psrai_d: {
10127     unsigned Opcode;
10128     switch (IntNo) {
10129     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10130     case Intrinsic::x86_sse2_pslli_w:
10131     case Intrinsic::x86_sse2_pslli_d:
10132     case Intrinsic::x86_sse2_pslli_q:
10133     case Intrinsic::x86_avx2_pslli_w:
10134     case Intrinsic::x86_avx2_pslli_d:
10135     case Intrinsic::x86_avx2_pslli_q:
10136       Opcode = X86ISD::VSHLI;
10137       break;
10138     case Intrinsic::x86_sse2_psrli_w:
10139     case Intrinsic::x86_sse2_psrli_d:
10140     case Intrinsic::x86_sse2_psrli_q:
10141     case Intrinsic::x86_avx2_psrli_w:
10142     case Intrinsic::x86_avx2_psrli_d:
10143     case Intrinsic::x86_avx2_psrli_q:
10144       Opcode = X86ISD::VSRLI;
10145       break;
10146     case Intrinsic::x86_sse2_psrai_w:
10147     case Intrinsic::x86_sse2_psrai_d:
10148     case Intrinsic::x86_avx2_psrai_w:
10149     case Intrinsic::x86_avx2_psrai_d:
10150       Opcode = X86ISD::VSRAI;
10151       break;
10152     }
10153     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10154                                Op.getOperand(1), Op.getOperand(2), DAG);
10155   }
10156
10157   case Intrinsic::x86_sse42_pcmpistria128:
10158   case Intrinsic::x86_sse42_pcmpestria128:
10159   case Intrinsic::x86_sse42_pcmpistric128:
10160   case Intrinsic::x86_sse42_pcmpestric128:
10161   case Intrinsic::x86_sse42_pcmpistrio128:
10162   case Intrinsic::x86_sse42_pcmpestrio128:
10163   case Intrinsic::x86_sse42_pcmpistris128:
10164   case Intrinsic::x86_sse42_pcmpestris128:
10165   case Intrinsic::x86_sse42_pcmpistriz128:
10166   case Intrinsic::x86_sse42_pcmpestriz128: {
10167     unsigned Opcode;
10168     unsigned X86CC;
10169     switch (IntNo) {
10170     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10171     case Intrinsic::x86_sse42_pcmpistria128:
10172       Opcode = X86ISD::PCMPISTRI;
10173       X86CC = X86::COND_A;
10174       break;
10175     case Intrinsic::x86_sse42_pcmpestria128:
10176       Opcode = X86ISD::PCMPESTRI;
10177       X86CC = X86::COND_A;
10178       break;
10179     case Intrinsic::x86_sse42_pcmpistric128:
10180       Opcode = X86ISD::PCMPISTRI;
10181       X86CC = X86::COND_B;
10182       break;
10183     case Intrinsic::x86_sse42_pcmpestric128:
10184       Opcode = X86ISD::PCMPESTRI;
10185       X86CC = X86::COND_B;
10186       break;
10187     case Intrinsic::x86_sse42_pcmpistrio128:
10188       Opcode = X86ISD::PCMPISTRI;
10189       X86CC = X86::COND_O;
10190       break;
10191     case Intrinsic::x86_sse42_pcmpestrio128:
10192       Opcode = X86ISD::PCMPESTRI;
10193       X86CC = X86::COND_O;
10194       break;
10195     case Intrinsic::x86_sse42_pcmpistris128:
10196       Opcode = X86ISD::PCMPISTRI;
10197       X86CC = X86::COND_S;
10198       break;
10199     case Intrinsic::x86_sse42_pcmpestris128:
10200       Opcode = X86ISD::PCMPESTRI;
10201       X86CC = X86::COND_S;
10202       break;
10203     case Intrinsic::x86_sse42_pcmpistriz128:
10204       Opcode = X86ISD::PCMPISTRI;
10205       X86CC = X86::COND_E;
10206       break;
10207     case Intrinsic::x86_sse42_pcmpestriz128:
10208       Opcode = X86ISD::PCMPESTRI;
10209       X86CC = X86::COND_E;
10210       break;
10211     }
10212     SmallVector<SDValue, 5> NewOps;
10213     NewOps.append(Op->op_begin()+1, Op->op_end());
10214     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10215     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10216     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10217                                 DAG.getConstant(X86CC, MVT::i8),
10218                                 SDValue(PCMP.getNode(), 1));
10219     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10220   }
10221
10222   case Intrinsic::x86_sse42_pcmpistri128:
10223   case Intrinsic::x86_sse42_pcmpestri128: {
10224     unsigned Opcode;
10225     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10226       Opcode = X86ISD::PCMPISTRI;
10227     else
10228       Opcode = X86ISD::PCMPESTRI;
10229
10230     SmallVector<SDValue, 5> NewOps;
10231     NewOps.append(Op->op_begin()+1, Op->op_end());
10232     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10233     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10234   }
10235   case Intrinsic::x86_fma_vfmadd_ps:
10236   case Intrinsic::x86_fma_vfmadd_pd:
10237   case Intrinsic::x86_fma_vfmsub_ps:
10238   case Intrinsic::x86_fma_vfmsub_pd:
10239   case Intrinsic::x86_fma_vfnmadd_ps:
10240   case Intrinsic::x86_fma_vfnmadd_pd:
10241   case Intrinsic::x86_fma_vfnmsub_ps:
10242   case Intrinsic::x86_fma_vfnmsub_pd:
10243   case Intrinsic::x86_fma_vfmaddsub_ps:
10244   case Intrinsic::x86_fma_vfmaddsub_pd:
10245   case Intrinsic::x86_fma_vfmsubadd_ps:
10246   case Intrinsic::x86_fma_vfmsubadd_pd:
10247   case Intrinsic::x86_fma_vfmadd_ps_256:
10248   case Intrinsic::x86_fma_vfmadd_pd_256:
10249   case Intrinsic::x86_fma_vfmsub_ps_256:
10250   case Intrinsic::x86_fma_vfmsub_pd_256:
10251   case Intrinsic::x86_fma_vfnmadd_ps_256:
10252   case Intrinsic::x86_fma_vfnmadd_pd_256:
10253   case Intrinsic::x86_fma_vfnmsub_ps_256:
10254   case Intrinsic::x86_fma_vfnmsub_pd_256:
10255   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10256   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10257   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10258   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10259     unsigned Opc;
10260     switch (IntNo) {
10261     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10262     case Intrinsic::x86_fma_vfmadd_ps:
10263     case Intrinsic::x86_fma_vfmadd_pd:
10264     case Intrinsic::x86_fma_vfmadd_ps_256:
10265     case Intrinsic::x86_fma_vfmadd_pd_256:
10266       Opc = X86ISD::FMADD;
10267       break;
10268     case Intrinsic::x86_fma_vfmsub_ps:
10269     case Intrinsic::x86_fma_vfmsub_pd:
10270     case Intrinsic::x86_fma_vfmsub_ps_256:
10271     case Intrinsic::x86_fma_vfmsub_pd_256:
10272       Opc = X86ISD::FMSUB;
10273       break;
10274     case Intrinsic::x86_fma_vfnmadd_ps:
10275     case Intrinsic::x86_fma_vfnmadd_pd:
10276     case Intrinsic::x86_fma_vfnmadd_ps_256:
10277     case Intrinsic::x86_fma_vfnmadd_pd_256:
10278       Opc = X86ISD::FNMADD;
10279       break;
10280     case Intrinsic::x86_fma_vfnmsub_ps:
10281     case Intrinsic::x86_fma_vfnmsub_pd:
10282     case Intrinsic::x86_fma_vfnmsub_ps_256:
10283     case Intrinsic::x86_fma_vfnmsub_pd_256:
10284       Opc = X86ISD::FNMSUB;
10285       break;
10286     case Intrinsic::x86_fma_vfmaddsub_ps:
10287     case Intrinsic::x86_fma_vfmaddsub_pd:
10288     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10289     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10290       Opc = X86ISD::FMADDSUB;
10291       break;
10292     case Intrinsic::x86_fma_vfmsubadd_ps:
10293     case Intrinsic::x86_fma_vfmsubadd_pd:
10294     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10295     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10296       Opc = X86ISD::FMSUBADD;
10297       break;
10298     }
10299
10300     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10301                        Op.getOperand(2), Op.getOperand(3));
10302   }
10303   }
10304 }
10305
10306 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10307   DebugLoc dl = Op.getDebugLoc();
10308   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10309   switch (IntNo) {
10310   default: return SDValue();    // Don't custom lower most intrinsics.
10311
10312   // RDRAND intrinsics.
10313   case Intrinsic::x86_rdrand_16:
10314   case Intrinsic::x86_rdrand_32:
10315   case Intrinsic::x86_rdrand_64: {
10316     // Emit the node with the right value type.
10317     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10318     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10319
10320     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10321     // return the value from Rand, which is always 0, casted to i32.
10322     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10323                       DAG.getConstant(1, Op->getValueType(1)),
10324                       DAG.getConstant(X86::COND_B, MVT::i32),
10325                       SDValue(Result.getNode(), 1) };
10326     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10327                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10328                                   Ops, 4);
10329
10330     // Return { result, isValid, chain }.
10331     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10332                        SDValue(Result.getNode(), 2));
10333   }
10334   }
10335 }
10336
10337 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10338                                            SelectionDAG &DAG) const {
10339   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10340   MFI->setReturnAddressIsTaken(true);
10341
10342   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10343   DebugLoc dl = Op.getDebugLoc();
10344
10345   if (Depth > 0) {
10346     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10347     SDValue Offset =
10348       DAG.getConstant(TD->getPointerSize(),
10349                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10350     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10351                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10352                                    FrameAddr, Offset),
10353                        MachinePointerInfo(), false, false, false, 0);
10354   }
10355
10356   // Just load the return address.
10357   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10358   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10359                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10360 }
10361
10362 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10363   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10364   MFI->setFrameAddressIsTaken(true);
10365
10366   EVT VT = Op.getValueType();
10367   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10368   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10369   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10370   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10371   while (Depth--)
10372     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10373                             MachinePointerInfo(),
10374                             false, false, false, 0);
10375   return FrameAddr;
10376 }
10377
10378 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10379                                                      SelectionDAG &DAG) const {
10380   return DAG.getIntPtrConstant(2*TD->getPointerSize());
10381 }
10382
10383 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10384   SDValue Chain     = Op.getOperand(0);
10385   SDValue Offset    = Op.getOperand(1);
10386   SDValue Handler   = Op.getOperand(2);
10387   DebugLoc dl       = Op.getDebugLoc();
10388
10389   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10390                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10391                                      getPointerTy());
10392   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10393
10394   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10395                                   DAG.getIntPtrConstant(TD->getPointerSize()));
10396   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10397   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10398                        false, false, 0);
10399   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10400
10401   return DAG.getNode(X86ISD::EH_RETURN, dl,
10402                      MVT::Other,
10403                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10404 }
10405
10406 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10407   return Op.getOperand(0);
10408 }
10409
10410 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10411                                                 SelectionDAG &DAG) const {
10412   SDValue Root = Op.getOperand(0);
10413   SDValue Trmp = Op.getOperand(1); // trampoline
10414   SDValue FPtr = Op.getOperand(2); // nested function
10415   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10416   DebugLoc dl  = Op.getDebugLoc();
10417
10418   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10419   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10420
10421   if (Subtarget->is64Bit()) {
10422     SDValue OutChains[6];
10423
10424     // Large code-model.
10425     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10426     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10427
10428     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10429     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10430
10431     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10432
10433     // Load the pointer to the nested function into R11.
10434     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10435     SDValue Addr = Trmp;
10436     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10437                                 Addr, MachinePointerInfo(TrmpAddr),
10438                                 false, false, 0);
10439
10440     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10441                        DAG.getConstant(2, MVT::i64));
10442     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10443                                 MachinePointerInfo(TrmpAddr, 2),
10444                                 false, false, 2);
10445
10446     // Load the 'nest' parameter value into R10.
10447     // R10 is specified in X86CallingConv.td
10448     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10449     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10450                        DAG.getConstant(10, MVT::i64));
10451     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10452                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10453                                 false, false, 0);
10454
10455     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10456                        DAG.getConstant(12, MVT::i64));
10457     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10458                                 MachinePointerInfo(TrmpAddr, 12),
10459                                 false, false, 2);
10460
10461     // Jump to the nested function.
10462     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10463     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10464                        DAG.getConstant(20, MVT::i64));
10465     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10466                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10467                                 false, false, 0);
10468
10469     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10470     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10471                        DAG.getConstant(22, MVT::i64));
10472     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10473                                 MachinePointerInfo(TrmpAddr, 22),
10474                                 false, false, 0);
10475
10476     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10477   } else {
10478     const Function *Func =
10479       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10480     CallingConv::ID CC = Func->getCallingConv();
10481     unsigned NestReg;
10482
10483     switch (CC) {
10484     default:
10485       llvm_unreachable("Unsupported calling convention");
10486     case CallingConv::C:
10487     case CallingConv::X86_StdCall: {
10488       // Pass 'nest' parameter in ECX.
10489       // Must be kept in sync with X86CallingConv.td
10490       NestReg = X86::ECX;
10491
10492       // Check that ECX wasn't needed by an 'inreg' parameter.
10493       FunctionType *FTy = Func->getFunctionType();
10494       const AttrListPtr &Attrs = Func->getAttributes();
10495
10496       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10497         unsigned InRegCount = 0;
10498         unsigned Idx = 1;
10499
10500         for (FunctionType::param_iterator I = FTy->param_begin(),
10501              E = FTy->param_end(); I != E; ++I, ++Idx)
10502           if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10503             // FIXME: should only count parameters that are lowered to integers.
10504             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10505
10506         if (InRegCount > 2) {
10507           report_fatal_error("Nest register in use - reduce number of inreg"
10508                              " parameters!");
10509         }
10510       }
10511       break;
10512     }
10513     case CallingConv::X86_FastCall:
10514     case CallingConv::X86_ThisCall:
10515     case CallingConv::Fast:
10516       // Pass 'nest' parameter in EAX.
10517       // Must be kept in sync with X86CallingConv.td
10518       NestReg = X86::EAX;
10519       break;
10520     }
10521
10522     SDValue OutChains[4];
10523     SDValue Addr, Disp;
10524
10525     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10526                        DAG.getConstant(10, MVT::i32));
10527     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10528
10529     // This is storing the opcode for MOV32ri.
10530     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10531     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10532     OutChains[0] = DAG.getStore(Root, dl,
10533                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10534                                 Trmp, MachinePointerInfo(TrmpAddr),
10535                                 false, false, 0);
10536
10537     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10538                        DAG.getConstant(1, MVT::i32));
10539     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10540                                 MachinePointerInfo(TrmpAddr, 1),
10541                                 false, false, 1);
10542
10543     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10544     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10545                        DAG.getConstant(5, MVT::i32));
10546     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10547                                 MachinePointerInfo(TrmpAddr, 5),
10548                                 false, false, 1);
10549
10550     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10551                        DAG.getConstant(6, MVT::i32));
10552     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10553                                 MachinePointerInfo(TrmpAddr, 6),
10554                                 false, false, 1);
10555
10556     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10557   }
10558 }
10559
10560 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10561                                             SelectionDAG &DAG) const {
10562   /*
10563    The rounding mode is in bits 11:10 of FPSR, and has the following
10564    settings:
10565      00 Round to nearest
10566      01 Round to -inf
10567      10 Round to +inf
10568      11 Round to 0
10569
10570   FLT_ROUNDS, on the other hand, expects the following:
10571     -1 Undefined
10572      0 Round to 0
10573      1 Round to nearest
10574      2 Round to +inf
10575      3 Round to -inf
10576
10577   To perform the conversion, we do:
10578     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10579   */
10580
10581   MachineFunction &MF = DAG.getMachineFunction();
10582   const TargetMachine &TM = MF.getTarget();
10583   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10584   unsigned StackAlignment = TFI.getStackAlignment();
10585   EVT VT = Op.getValueType();
10586   DebugLoc DL = Op.getDebugLoc();
10587
10588   // Save FP Control Word to stack slot
10589   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10590   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10591
10592
10593   MachineMemOperand *MMO =
10594    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10595                            MachineMemOperand::MOStore, 2, 2);
10596
10597   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10598   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10599                                           DAG.getVTList(MVT::Other),
10600                                           Ops, 2, MVT::i16, MMO);
10601
10602   // Load FP Control Word from stack slot
10603   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10604                             MachinePointerInfo(), false, false, false, 0);
10605
10606   // Transform as necessary
10607   SDValue CWD1 =
10608     DAG.getNode(ISD::SRL, DL, MVT::i16,
10609                 DAG.getNode(ISD::AND, DL, MVT::i16,
10610                             CWD, DAG.getConstant(0x800, MVT::i16)),
10611                 DAG.getConstant(11, MVT::i8));
10612   SDValue CWD2 =
10613     DAG.getNode(ISD::SRL, DL, MVT::i16,
10614                 DAG.getNode(ISD::AND, DL, MVT::i16,
10615                             CWD, DAG.getConstant(0x400, MVT::i16)),
10616                 DAG.getConstant(9, MVT::i8));
10617
10618   SDValue RetVal =
10619     DAG.getNode(ISD::AND, DL, MVT::i16,
10620                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10621                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10622                             DAG.getConstant(1, MVT::i16)),
10623                 DAG.getConstant(3, MVT::i16));
10624
10625
10626   return DAG.getNode((VT.getSizeInBits() < 16 ?
10627                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10628 }
10629
10630 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10631   EVT VT = Op.getValueType();
10632   EVT OpVT = VT;
10633   unsigned NumBits = VT.getSizeInBits();
10634   DebugLoc dl = Op.getDebugLoc();
10635
10636   Op = Op.getOperand(0);
10637   if (VT == MVT::i8) {
10638     // Zero extend to i32 since there is not an i8 bsr.
10639     OpVT = MVT::i32;
10640     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10641   }
10642
10643   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10644   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10645   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10646
10647   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10648   SDValue Ops[] = {
10649     Op,
10650     DAG.getConstant(NumBits+NumBits-1, OpVT),
10651     DAG.getConstant(X86::COND_E, MVT::i8),
10652     Op.getValue(1)
10653   };
10654   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10655
10656   // Finally xor with NumBits-1.
10657   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10658
10659   if (VT == MVT::i8)
10660     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10661   return Op;
10662 }
10663
10664 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10665   EVT VT = Op.getValueType();
10666   EVT OpVT = VT;
10667   unsigned NumBits = VT.getSizeInBits();
10668   DebugLoc dl = Op.getDebugLoc();
10669
10670   Op = Op.getOperand(0);
10671   if (VT == MVT::i8) {
10672     // Zero extend to i32 since there is not an i8 bsr.
10673     OpVT = MVT::i32;
10674     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10675   }
10676
10677   // Issue a bsr (scan bits in reverse).
10678   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10679   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10680
10681   // And xor with NumBits-1.
10682   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10683
10684   if (VT == MVT::i8)
10685     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10686   return Op;
10687 }
10688
10689 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10690   EVT VT = Op.getValueType();
10691   unsigned NumBits = VT.getSizeInBits();
10692   DebugLoc dl = Op.getDebugLoc();
10693   Op = Op.getOperand(0);
10694
10695   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10696   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10697   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10698
10699   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10700   SDValue Ops[] = {
10701     Op,
10702     DAG.getConstant(NumBits, VT),
10703     DAG.getConstant(X86::COND_E, MVT::i8),
10704     Op.getValue(1)
10705   };
10706   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10707 }
10708
10709 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10710 // ones, and then concatenate the result back.
10711 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10712   EVT VT = Op.getValueType();
10713
10714   assert(VT.is256BitVector() && VT.isInteger() &&
10715          "Unsupported value type for operation");
10716
10717   unsigned NumElems = VT.getVectorNumElements();
10718   DebugLoc dl = Op.getDebugLoc();
10719
10720   // Extract the LHS vectors
10721   SDValue LHS = Op.getOperand(0);
10722   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10723   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10724
10725   // Extract the RHS vectors
10726   SDValue RHS = Op.getOperand(1);
10727   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10728   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10729
10730   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10731   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10732
10733   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10734                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10735                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10736 }
10737
10738 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10739   assert(Op.getValueType().is256BitVector() &&
10740          Op.getValueType().isInteger() &&
10741          "Only handle AVX 256-bit vector integer operation");
10742   return Lower256IntArith(Op, DAG);
10743 }
10744
10745 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10746   assert(Op.getValueType().is256BitVector() &&
10747          Op.getValueType().isInteger() &&
10748          "Only handle AVX 256-bit vector integer operation");
10749   return Lower256IntArith(Op, DAG);
10750 }
10751
10752 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10753                         SelectionDAG &DAG) {
10754   EVT VT = Op.getValueType();
10755
10756   // Decompose 256-bit ops into smaller 128-bit ops.
10757   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10758     return Lower256IntArith(Op, DAG);
10759
10760   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10761          "Only know how to lower V2I64/V4I64 multiply");
10762
10763   DebugLoc dl = Op.getDebugLoc();
10764
10765   //  Ahi = psrlqi(a, 32);
10766   //  Bhi = psrlqi(b, 32);
10767   //
10768   //  AloBlo = pmuludq(a, b);
10769   //  AloBhi = pmuludq(a, Bhi);
10770   //  AhiBlo = pmuludq(Ahi, b);
10771
10772   //  AloBhi = psllqi(AloBhi, 32);
10773   //  AhiBlo = psllqi(AhiBlo, 32);
10774   //  return AloBlo + AloBhi + AhiBlo;
10775
10776   SDValue A = Op.getOperand(0);
10777   SDValue B = Op.getOperand(1);
10778
10779   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10780
10781   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10782   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10783
10784   // Bit cast to 32-bit vectors for MULUDQ
10785   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10786   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10787   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10788   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10789   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10790
10791   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10792   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10793   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10794
10795   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10796   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10797
10798   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10799   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10800 }
10801
10802 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10803
10804   EVT VT = Op.getValueType();
10805   DebugLoc dl = Op.getDebugLoc();
10806   SDValue R = Op.getOperand(0);
10807   SDValue Amt = Op.getOperand(1);
10808   LLVMContext *Context = DAG.getContext();
10809
10810   if (!Subtarget->hasSSE2())
10811     return SDValue();
10812
10813   // Optimize shl/srl/sra with constant shift amount.
10814   if (isSplatVector(Amt.getNode())) {
10815     SDValue SclrAmt = Amt->getOperand(0);
10816     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10817       uint64_t ShiftAmt = C->getZExtValue();
10818
10819       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10820           (Subtarget->hasAVX2() &&
10821            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10822         if (Op.getOpcode() == ISD::SHL)
10823           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10824                              DAG.getConstant(ShiftAmt, MVT::i32));
10825         if (Op.getOpcode() == ISD::SRL)
10826           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10827                              DAG.getConstant(ShiftAmt, MVT::i32));
10828         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10829           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10830                              DAG.getConstant(ShiftAmt, MVT::i32));
10831       }
10832
10833       if (VT == MVT::v16i8) {
10834         if (Op.getOpcode() == ISD::SHL) {
10835           // Make a large shift.
10836           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10837                                     DAG.getConstant(ShiftAmt, MVT::i32));
10838           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10839           // Zero out the rightmost bits.
10840           SmallVector<SDValue, 16> V(16,
10841                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10842                                                      MVT::i8));
10843           return DAG.getNode(ISD::AND, dl, VT, SHL,
10844                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10845         }
10846         if (Op.getOpcode() == ISD::SRL) {
10847           // Make a large shift.
10848           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10849                                     DAG.getConstant(ShiftAmt, MVT::i32));
10850           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10851           // Zero out the leftmost bits.
10852           SmallVector<SDValue, 16> V(16,
10853                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10854                                                      MVT::i8));
10855           return DAG.getNode(ISD::AND, dl, VT, SRL,
10856                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10857         }
10858         if (Op.getOpcode() == ISD::SRA) {
10859           if (ShiftAmt == 7) {
10860             // R s>> 7  ===  R s< 0
10861             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10862             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10863           }
10864
10865           // R s>> a === ((R u>> a) ^ m) - m
10866           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10867           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10868                                                          MVT::i8));
10869           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10870           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10871           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10872           return Res;
10873         }
10874         llvm_unreachable("Unknown shift opcode.");
10875       }
10876
10877       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10878         if (Op.getOpcode() == ISD::SHL) {
10879           // Make a large shift.
10880           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10881                                     DAG.getConstant(ShiftAmt, MVT::i32));
10882           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10883           // Zero out the rightmost bits.
10884           SmallVector<SDValue, 32> V(32,
10885                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10886                                                      MVT::i8));
10887           return DAG.getNode(ISD::AND, dl, VT, SHL,
10888                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10889         }
10890         if (Op.getOpcode() == ISD::SRL) {
10891           // Make a large shift.
10892           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10893                                     DAG.getConstant(ShiftAmt, MVT::i32));
10894           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10895           // Zero out the leftmost bits.
10896           SmallVector<SDValue, 32> V(32,
10897                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10898                                                      MVT::i8));
10899           return DAG.getNode(ISD::AND, dl, VT, SRL,
10900                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10901         }
10902         if (Op.getOpcode() == ISD::SRA) {
10903           if (ShiftAmt == 7) {
10904             // R s>> 7  ===  R s< 0
10905             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10906             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10907           }
10908
10909           // R s>> a === ((R u>> a) ^ m) - m
10910           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10911           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10912                                                          MVT::i8));
10913           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10914           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10915           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10916           return Res;
10917         }
10918         llvm_unreachable("Unknown shift opcode.");
10919       }
10920     }
10921   }
10922
10923   // Lower SHL with variable shift amount.
10924   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10925     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10926                      DAG.getConstant(23, MVT::i32));
10927
10928     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10929     Constant *C = ConstantDataVector::get(*Context, CV);
10930     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10931     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10932                                  MachinePointerInfo::getConstantPool(),
10933                                  false, false, false, 16);
10934
10935     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10936     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10937     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10938     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10939   }
10940   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10941     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10942
10943     // a = a << 5;
10944     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10945                      DAG.getConstant(5, MVT::i32));
10946     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10947
10948     // Turn 'a' into a mask suitable for VSELECT
10949     SDValue VSelM = DAG.getConstant(0x80, VT);
10950     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10951     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10952
10953     SDValue CM1 = DAG.getConstant(0x0f, VT);
10954     SDValue CM2 = DAG.getConstant(0x3f, VT);
10955
10956     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10957     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10958     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10959                             DAG.getConstant(4, MVT::i32), DAG);
10960     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10961     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10962
10963     // a += a
10964     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10965     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10966     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10967
10968     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10969     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10970     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10971                             DAG.getConstant(2, MVT::i32), DAG);
10972     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10973     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10974
10975     // a += a
10976     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10977     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10978     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10979
10980     // return VSELECT(r, r+r, a);
10981     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10982                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10983     return R;
10984   }
10985
10986   // Decompose 256-bit shifts into smaller 128-bit shifts.
10987   if (VT.is256BitVector()) {
10988     unsigned NumElems = VT.getVectorNumElements();
10989     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10990     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10991
10992     // Extract the two vectors
10993     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10994     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10995
10996     // Recreate the shift amount vectors
10997     SDValue Amt1, Amt2;
10998     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10999       // Constant shift amount
11000       SmallVector<SDValue, 4> Amt1Csts;
11001       SmallVector<SDValue, 4> Amt2Csts;
11002       for (unsigned i = 0; i != NumElems/2; ++i)
11003         Amt1Csts.push_back(Amt->getOperand(i));
11004       for (unsigned i = NumElems/2; i != NumElems; ++i)
11005         Amt2Csts.push_back(Amt->getOperand(i));
11006
11007       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11008                                  &Amt1Csts[0], NumElems/2);
11009       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11010                                  &Amt2Csts[0], NumElems/2);
11011     } else {
11012       // Variable shift amount
11013       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11014       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11015     }
11016
11017     // Issue new vector shifts for the smaller types
11018     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11019     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11020
11021     // Concatenate the result back
11022     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11023   }
11024
11025   return SDValue();
11026 }
11027
11028 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11029   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11030   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11031   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11032   // has only one use.
11033   SDNode *N = Op.getNode();
11034   SDValue LHS = N->getOperand(0);
11035   SDValue RHS = N->getOperand(1);
11036   unsigned BaseOp = 0;
11037   unsigned Cond = 0;
11038   DebugLoc DL = Op.getDebugLoc();
11039   switch (Op.getOpcode()) {
11040   default: llvm_unreachable("Unknown ovf instruction!");
11041   case ISD::SADDO:
11042     // A subtract of one will be selected as a INC. Note that INC doesn't
11043     // set CF, so we can't do this for UADDO.
11044     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11045       if (C->isOne()) {
11046         BaseOp = X86ISD::INC;
11047         Cond = X86::COND_O;
11048         break;
11049       }
11050     BaseOp = X86ISD::ADD;
11051     Cond = X86::COND_O;
11052     break;
11053   case ISD::UADDO:
11054     BaseOp = X86ISD::ADD;
11055     Cond = X86::COND_B;
11056     break;
11057   case ISD::SSUBO:
11058     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11059     // set CF, so we can't do this for USUBO.
11060     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11061       if (C->isOne()) {
11062         BaseOp = X86ISD::DEC;
11063         Cond = X86::COND_O;
11064         break;
11065       }
11066     BaseOp = X86ISD::SUB;
11067     Cond = X86::COND_O;
11068     break;
11069   case ISD::USUBO:
11070     BaseOp = X86ISD::SUB;
11071     Cond = X86::COND_B;
11072     break;
11073   case ISD::SMULO:
11074     BaseOp = X86ISD::SMUL;
11075     Cond = X86::COND_O;
11076     break;
11077   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11078     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11079                                  MVT::i32);
11080     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11081
11082     SDValue SetCC =
11083       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11084                   DAG.getConstant(X86::COND_O, MVT::i32),
11085                   SDValue(Sum.getNode(), 2));
11086
11087     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11088   }
11089   }
11090
11091   // Also sets EFLAGS.
11092   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11093   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11094
11095   SDValue SetCC =
11096     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11097                 DAG.getConstant(Cond, MVT::i32),
11098                 SDValue(Sum.getNode(), 1));
11099
11100   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11101 }
11102
11103 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11104                                                   SelectionDAG &DAG) const {
11105   DebugLoc dl = Op.getDebugLoc();
11106   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11107   EVT VT = Op.getValueType();
11108
11109   if (!Subtarget->hasSSE2() || !VT.isVector())
11110     return SDValue();
11111
11112   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11113                       ExtraVT.getScalarType().getSizeInBits();
11114   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11115
11116   switch (VT.getSimpleVT().SimpleTy) {
11117     default: return SDValue();
11118     case MVT::v8i32:
11119     case MVT::v16i16:
11120       if (!Subtarget->hasAVX())
11121         return SDValue();
11122       if (!Subtarget->hasAVX2()) {
11123         // needs to be split
11124         unsigned NumElems = VT.getVectorNumElements();
11125
11126         // Extract the LHS vectors
11127         SDValue LHS = Op.getOperand(0);
11128         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11129         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11130
11131         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11132         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11133
11134         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11135         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11136         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11137                                    ExtraNumElems/2);
11138         SDValue Extra = DAG.getValueType(ExtraVT);
11139
11140         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11141         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11142
11143         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11144       }
11145       // fall through
11146     case MVT::v4i32:
11147     case MVT::v8i16: {
11148       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11149                                          Op.getOperand(0), ShAmt, DAG);
11150       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11151     }
11152   }
11153 }
11154
11155
11156 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11157                               SelectionDAG &DAG) {
11158   DebugLoc dl = Op.getDebugLoc();
11159
11160   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11161   // There isn't any reason to disable it if the target processor supports it.
11162   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11163     SDValue Chain = Op.getOperand(0);
11164     SDValue Zero = DAG.getConstant(0, MVT::i32);
11165     SDValue Ops[] = {
11166       DAG.getRegister(X86::ESP, MVT::i32), // Base
11167       DAG.getTargetConstant(1, MVT::i8),   // Scale
11168       DAG.getRegister(0, MVT::i32),        // Index
11169       DAG.getTargetConstant(0, MVT::i32),  // Disp
11170       DAG.getRegister(0, MVT::i32),        // Segment.
11171       Zero,
11172       Chain
11173     };
11174     SDNode *Res =
11175       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11176                           array_lengthof(Ops));
11177     return SDValue(Res, 0);
11178   }
11179
11180   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11181   if (!isDev)
11182     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11183
11184   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11185   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11186   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11187   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11188
11189   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11190   if (!Op1 && !Op2 && !Op3 && Op4)
11191     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11192
11193   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11194   if (Op1 && !Op2 && !Op3 && !Op4)
11195     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11196
11197   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11198   //           (MFENCE)>;
11199   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11200 }
11201
11202 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11203                                  SelectionDAG &DAG) {
11204   DebugLoc dl = Op.getDebugLoc();
11205   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11206     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11207   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11208     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11209
11210   // The only fence that needs an instruction is a sequentially-consistent
11211   // cross-thread fence.
11212   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11213     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11214     // no-sse2). There isn't any reason to disable it if the target processor
11215     // supports it.
11216     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11217       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11218
11219     SDValue Chain = Op.getOperand(0);
11220     SDValue Zero = DAG.getConstant(0, MVT::i32);
11221     SDValue Ops[] = {
11222       DAG.getRegister(X86::ESP, MVT::i32), // Base
11223       DAG.getTargetConstant(1, MVT::i8),   // Scale
11224       DAG.getRegister(0, MVT::i32),        // Index
11225       DAG.getTargetConstant(0, MVT::i32),  // Disp
11226       DAG.getRegister(0, MVT::i32),        // Segment.
11227       Zero,
11228       Chain
11229     };
11230     SDNode *Res =
11231       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11232                          array_lengthof(Ops));
11233     return SDValue(Res, 0);
11234   }
11235
11236   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11237   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11238 }
11239
11240
11241 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11242                              SelectionDAG &DAG) {
11243   EVT T = Op.getValueType();
11244   DebugLoc DL = Op.getDebugLoc();
11245   unsigned Reg = 0;
11246   unsigned size = 0;
11247   switch(T.getSimpleVT().SimpleTy) {
11248   default: llvm_unreachable("Invalid value type!");
11249   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11250   case MVT::i16: Reg = X86::AX;  size = 2; break;
11251   case MVT::i32: Reg = X86::EAX; size = 4; break;
11252   case MVT::i64:
11253     assert(Subtarget->is64Bit() && "Node not type legal!");
11254     Reg = X86::RAX; size = 8;
11255     break;
11256   }
11257   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11258                                     Op.getOperand(2), SDValue());
11259   SDValue Ops[] = { cpIn.getValue(0),
11260                     Op.getOperand(1),
11261                     Op.getOperand(3),
11262                     DAG.getTargetConstant(size, MVT::i8),
11263                     cpIn.getValue(1) };
11264   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11265   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11266   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11267                                            Ops, 5, T, MMO);
11268   SDValue cpOut =
11269     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11270   return cpOut;
11271 }
11272
11273 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11274                                      SelectionDAG &DAG) {
11275   assert(Subtarget->is64Bit() && "Result not type legalized?");
11276   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11277   SDValue TheChain = Op.getOperand(0);
11278   DebugLoc dl = Op.getDebugLoc();
11279   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11280   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11281   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11282                                    rax.getValue(2));
11283   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11284                             DAG.getConstant(32, MVT::i8));
11285   SDValue Ops[] = {
11286     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11287     rdx.getValue(1)
11288   };
11289   return DAG.getMergeValues(Ops, 2, dl);
11290 }
11291
11292 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11293   EVT SrcVT = Op.getOperand(0).getValueType();
11294   EVT DstVT = Op.getValueType();
11295   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11296          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11297   assert((DstVT == MVT::i64 ||
11298           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11299          "Unexpected custom BITCAST");
11300   // i64 <=> MMX conversions are Legal.
11301   if (SrcVT==MVT::i64 && DstVT.isVector())
11302     return Op;
11303   if (DstVT==MVT::i64 && SrcVT.isVector())
11304     return Op;
11305   // MMX <=> MMX conversions are Legal.
11306   if (SrcVT.isVector() && DstVT.isVector())
11307     return Op;
11308   // All other conversions need to be expanded.
11309   return SDValue();
11310 }
11311
11312 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11313   SDNode *Node = Op.getNode();
11314   DebugLoc dl = Node->getDebugLoc();
11315   EVT T = Node->getValueType(0);
11316   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11317                               DAG.getConstant(0, T), Node->getOperand(2));
11318   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11319                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11320                        Node->getOperand(0),
11321                        Node->getOperand(1), negOp,
11322                        cast<AtomicSDNode>(Node)->getSrcValue(),
11323                        cast<AtomicSDNode>(Node)->getAlignment(),
11324                        cast<AtomicSDNode>(Node)->getOrdering(),
11325                        cast<AtomicSDNode>(Node)->getSynchScope());
11326 }
11327
11328 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11329   SDNode *Node = Op.getNode();
11330   DebugLoc dl = Node->getDebugLoc();
11331   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11332
11333   // Convert seq_cst store -> xchg
11334   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11335   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11336   //        (The only way to get a 16-byte store is cmpxchg16b)
11337   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11338   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11339       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11340     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11341                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11342                                  Node->getOperand(0),
11343                                  Node->getOperand(1), Node->getOperand(2),
11344                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11345                                  cast<AtomicSDNode>(Node)->getOrdering(),
11346                                  cast<AtomicSDNode>(Node)->getSynchScope());
11347     return Swap.getValue(1);
11348   }
11349   // Other atomic stores have a simple pattern.
11350   return Op;
11351 }
11352
11353 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11354   EVT VT = Op.getNode()->getValueType(0);
11355
11356   // Let legalize expand this if it isn't a legal type yet.
11357   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11358     return SDValue();
11359
11360   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11361
11362   unsigned Opc;
11363   bool ExtraOp = false;
11364   switch (Op.getOpcode()) {
11365   default: llvm_unreachable("Invalid code");
11366   case ISD::ADDC: Opc = X86ISD::ADD; break;
11367   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11368   case ISD::SUBC: Opc = X86ISD::SUB; break;
11369   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11370   }
11371
11372   if (!ExtraOp)
11373     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11374                        Op.getOperand(1));
11375   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11376                      Op.getOperand(1), Op.getOperand(2));
11377 }
11378
11379 /// LowerOperation - Provide custom lowering hooks for some operations.
11380 ///
11381 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11382   switch (Op.getOpcode()) {
11383   default: llvm_unreachable("Should not custom lower this!");
11384   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11385   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11386   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11387   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11388   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11389   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11390   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11391   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11392   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11393   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11394   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11395   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11396   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11397   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11398   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11399   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11400   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11401   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11402   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11403   case ISD::SHL_PARTS:
11404   case ISD::SRA_PARTS:
11405   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11406   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11407   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11408   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11409   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11410   case ISD::FABS:               return LowerFABS(Op, DAG);
11411   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11412   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11413   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11414   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11415   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11416   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11417   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11418   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11419   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11420   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11421   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11422   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11423   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11424   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11425   case ISD::FRAME_TO_ARGS_OFFSET:
11426                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11427   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11428   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11429   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11430   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11431   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11432   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11433   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11434   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11435   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11436   case ISD::SRA:
11437   case ISD::SRL:
11438   case ISD::SHL:                return LowerShift(Op, DAG);
11439   case ISD::SADDO:
11440   case ISD::UADDO:
11441   case ISD::SSUBO:
11442   case ISD::USUBO:
11443   case ISD::SMULO:
11444   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11445   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11446   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11447   case ISD::ADDC:
11448   case ISD::ADDE:
11449   case ISD::SUBC:
11450   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11451   case ISD::ADD:                return LowerADD(Op, DAG);
11452   case ISD::SUB:                return LowerSUB(Op, DAG);
11453   }
11454 }
11455
11456 static void ReplaceATOMIC_LOAD(SDNode *Node,
11457                                   SmallVectorImpl<SDValue> &Results,
11458                                   SelectionDAG &DAG) {
11459   DebugLoc dl = Node->getDebugLoc();
11460   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11461
11462   // Convert wide load -> cmpxchg8b/cmpxchg16b
11463   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11464   //        (The only way to get a 16-byte load is cmpxchg16b)
11465   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11466   SDValue Zero = DAG.getConstant(0, VT);
11467   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11468                                Node->getOperand(0),
11469                                Node->getOperand(1), Zero, Zero,
11470                                cast<AtomicSDNode>(Node)->getMemOperand(),
11471                                cast<AtomicSDNode>(Node)->getOrdering(),
11472                                cast<AtomicSDNode>(Node)->getSynchScope());
11473   Results.push_back(Swap.getValue(0));
11474   Results.push_back(Swap.getValue(1));
11475 }
11476
11477 static void
11478 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11479                         SelectionDAG &DAG, unsigned NewOp) {
11480   DebugLoc dl = Node->getDebugLoc();
11481   assert (Node->getValueType(0) == MVT::i64 &&
11482           "Only know how to expand i64 atomics");
11483
11484   SDValue Chain = Node->getOperand(0);
11485   SDValue In1 = Node->getOperand(1);
11486   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11487                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11488   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11489                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11490   SDValue Ops[] = { Chain, In1, In2L, In2H };
11491   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11492   SDValue Result =
11493     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11494                             cast<MemSDNode>(Node)->getMemOperand());
11495   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11496   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11497   Results.push_back(Result.getValue(2));
11498 }
11499
11500 /// ReplaceNodeResults - Replace a node with an illegal result type
11501 /// with a new node built out of custom code.
11502 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11503                                            SmallVectorImpl<SDValue>&Results,
11504                                            SelectionDAG &DAG) const {
11505   DebugLoc dl = N->getDebugLoc();
11506   switch (N->getOpcode()) {
11507   default:
11508     llvm_unreachable("Do not know how to custom type legalize this operation!");
11509   case ISD::SIGN_EXTEND_INREG:
11510   case ISD::ADDC:
11511   case ISD::ADDE:
11512   case ISD::SUBC:
11513   case ISD::SUBE:
11514     // We don't want to expand or promote these.
11515     return;
11516   case ISD::FP_TO_SINT:
11517   case ISD::FP_TO_UINT: {
11518     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11519
11520     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11521       return;
11522
11523     std::pair<SDValue,SDValue> Vals =
11524         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11525     SDValue FIST = Vals.first, StackSlot = Vals.second;
11526     if (FIST.getNode() != 0) {
11527       EVT VT = N->getValueType(0);
11528       // Return a load from the stack slot.
11529       if (StackSlot.getNode() != 0)
11530         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11531                                       MachinePointerInfo(),
11532                                       false, false, false, 0));
11533       else
11534         Results.push_back(FIST);
11535     }
11536     return;
11537   }
11538   case ISD::READCYCLECOUNTER: {
11539     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11540     SDValue TheChain = N->getOperand(0);
11541     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11542     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11543                                      rd.getValue(1));
11544     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11545                                      eax.getValue(2));
11546     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11547     SDValue Ops[] = { eax, edx };
11548     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11549     Results.push_back(edx.getValue(1));
11550     return;
11551   }
11552   case ISD::ATOMIC_CMP_SWAP: {
11553     EVT T = N->getValueType(0);
11554     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11555     bool Regs64bit = T == MVT::i128;
11556     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11557     SDValue cpInL, cpInH;
11558     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11559                         DAG.getConstant(0, HalfT));
11560     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11561                         DAG.getConstant(1, HalfT));
11562     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11563                              Regs64bit ? X86::RAX : X86::EAX,
11564                              cpInL, SDValue());
11565     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11566                              Regs64bit ? X86::RDX : X86::EDX,
11567                              cpInH, cpInL.getValue(1));
11568     SDValue swapInL, swapInH;
11569     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11570                           DAG.getConstant(0, HalfT));
11571     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11572                           DAG.getConstant(1, HalfT));
11573     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11574                                Regs64bit ? X86::RBX : X86::EBX,
11575                                swapInL, cpInH.getValue(1));
11576     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11577                                Regs64bit ? X86::RCX : X86::ECX,
11578                                swapInH, swapInL.getValue(1));
11579     SDValue Ops[] = { swapInH.getValue(0),
11580                       N->getOperand(1),
11581                       swapInH.getValue(1) };
11582     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11583     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11584     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11585                                   X86ISD::LCMPXCHG8_DAG;
11586     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11587                                              Ops, 3, T, MMO);
11588     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11589                                         Regs64bit ? X86::RAX : X86::EAX,
11590                                         HalfT, Result.getValue(1));
11591     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11592                                         Regs64bit ? X86::RDX : X86::EDX,
11593                                         HalfT, cpOutL.getValue(2));
11594     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11595     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11596     Results.push_back(cpOutH.getValue(1));
11597     return;
11598   }
11599   case ISD::ATOMIC_LOAD_ADD:
11600   case ISD::ATOMIC_LOAD_AND:
11601   case ISD::ATOMIC_LOAD_NAND:
11602   case ISD::ATOMIC_LOAD_OR:
11603   case ISD::ATOMIC_LOAD_SUB:
11604   case ISD::ATOMIC_LOAD_XOR:
11605   case ISD::ATOMIC_LOAD_MAX:
11606   case ISD::ATOMIC_LOAD_MIN:
11607   case ISD::ATOMIC_LOAD_UMAX:
11608   case ISD::ATOMIC_LOAD_UMIN:
11609   case ISD::ATOMIC_SWAP: {
11610     unsigned Opc;
11611     switch (N->getOpcode()) {
11612     default: llvm_unreachable("Unexpected opcode");
11613     case ISD::ATOMIC_LOAD_ADD:
11614       Opc = X86ISD::ATOMADD64_DAG;
11615       break;
11616     case ISD::ATOMIC_LOAD_AND:
11617       Opc = X86ISD::ATOMAND64_DAG;
11618       break;
11619     case ISD::ATOMIC_LOAD_NAND:
11620       Opc = X86ISD::ATOMNAND64_DAG;
11621       break;
11622     case ISD::ATOMIC_LOAD_OR:
11623       Opc = X86ISD::ATOMOR64_DAG;
11624       break;
11625     case ISD::ATOMIC_LOAD_SUB:
11626       Opc = X86ISD::ATOMSUB64_DAG;
11627       break;
11628     case ISD::ATOMIC_LOAD_XOR:
11629       Opc = X86ISD::ATOMXOR64_DAG;
11630       break;
11631     case ISD::ATOMIC_LOAD_MAX:
11632       Opc = X86ISD::ATOMMAX64_DAG;
11633       break;
11634     case ISD::ATOMIC_LOAD_MIN:
11635       Opc = X86ISD::ATOMMIN64_DAG;
11636       break;
11637     case ISD::ATOMIC_LOAD_UMAX:
11638       Opc = X86ISD::ATOMUMAX64_DAG;
11639       break;
11640     case ISD::ATOMIC_LOAD_UMIN:
11641       Opc = X86ISD::ATOMUMIN64_DAG;
11642       break;
11643     case ISD::ATOMIC_SWAP:
11644       Opc = X86ISD::ATOMSWAP64_DAG;
11645       break;
11646     }
11647     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11648     return;
11649   }
11650   case ISD::ATOMIC_LOAD:
11651     ReplaceATOMIC_LOAD(N, Results, DAG);
11652   }
11653 }
11654
11655 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11656   switch (Opcode) {
11657   default: return NULL;
11658   case X86ISD::BSF:                return "X86ISD::BSF";
11659   case X86ISD::BSR:                return "X86ISD::BSR";
11660   case X86ISD::SHLD:               return "X86ISD::SHLD";
11661   case X86ISD::SHRD:               return "X86ISD::SHRD";
11662   case X86ISD::FAND:               return "X86ISD::FAND";
11663   case X86ISD::FOR:                return "X86ISD::FOR";
11664   case X86ISD::FXOR:               return "X86ISD::FXOR";
11665   case X86ISD::FSRL:               return "X86ISD::FSRL";
11666   case X86ISD::FILD:               return "X86ISD::FILD";
11667   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11668   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11669   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11670   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11671   case X86ISD::FLD:                return "X86ISD::FLD";
11672   case X86ISD::FST:                return "X86ISD::FST";
11673   case X86ISD::CALL:               return "X86ISD::CALL";
11674   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11675   case X86ISD::BT:                 return "X86ISD::BT";
11676   case X86ISD::CMP:                return "X86ISD::CMP";
11677   case X86ISD::COMI:               return "X86ISD::COMI";
11678   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11679   case X86ISD::SETCC:              return "X86ISD::SETCC";
11680   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11681   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11682   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11683   case X86ISD::CMOV:               return "X86ISD::CMOV";
11684   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11685   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11686   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11687   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11688   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11689   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11690   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11691   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11692   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11693   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11694   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11695   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11696   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11697   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11698   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11699   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11700   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11701   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11702   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11703   case X86ISD::HADD:               return "X86ISD::HADD";
11704   case X86ISD::HSUB:               return "X86ISD::HSUB";
11705   case X86ISD::FHADD:              return "X86ISD::FHADD";
11706   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11707   case X86ISD::FMAX:               return "X86ISD::FMAX";
11708   case X86ISD::FMIN:               return "X86ISD::FMIN";
11709   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11710   case X86ISD::FMINC:              return "X86ISD::FMINC";
11711   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11712   case X86ISD::FRCP:               return "X86ISD::FRCP";
11713   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11714   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11715   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11716   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11717   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11718   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11719   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11720   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11721   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11722   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11723   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11724   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11725   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11726   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11727   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11728   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11729   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11730   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11731   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11732   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11733   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11734   case X86ISD::VSHL:               return "X86ISD::VSHL";
11735   case X86ISD::VSRL:               return "X86ISD::VSRL";
11736   case X86ISD::VSRA:               return "X86ISD::VSRA";
11737   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11738   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11739   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11740   case X86ISD::CMPP:               return "X86ISD::CMPP";
11741   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11742   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11743   case X86ISD::ADD:                return "X86ISD::ADD";
11744   case X86ISD::SUB:                return "X86ISD::SUB";
11745   case X86ISD::ADC:                return "X86ISD::ADC";
11746   case X86ISD::SBB:                return "X86ISD::SBB";
11747   case X86ISD::SMUL:               return "X86ISD::SMUL";
11748   case X86ISD::UMUL:               return "X86ISD::UMUL";
11749   case X86ISD::INC:                return "X86ISD::INC";
11750   case X86ISD::DEC:                return "X86ISD::DEC";
11751   case X86ISD::OR:                 return "X86ISD::OR";
11752   case X86ISD::XOR:                return "X86ISD::XOR";
11753   case X86ISD::AND:                return "X86ISD::AND";
11754   case X86ISD::ANDN:               return "X86ISD::ANDN";
11755   case X86ISD::BLSI:               return "X86ISD::BLSI";
11756   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11757   case X86ISD::BLSR:               return "X86ISD::BLSR";
11758   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11759   case X86ISD::PTEST:              return "X86ISD::PTEST";
11760   case X86ISD::TESTP:              return "X86ISD::TESTP";
11761   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11762   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11763   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11764   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11765   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11766   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11767   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11768   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11769   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11770   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11771   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11772   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11773   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11774   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11775   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11776   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11777   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11778   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11779   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11780   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11781   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11782   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11783   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11784   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11785   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11786   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11787   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11788   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11789   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11790   case X86ISD::SAHF:               return "X86ISD::SAHF";
11791   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11792   case X86ISD::FMADD:              return "X86ISD::FMADD";
11793   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11794   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11795   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11796   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11797   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11798   }
11799 }
11800
11801 // isLegalAddressingMode - Return true if the addressing mode represented
11802 // by AM is legal for this target, for a load/store of the specified type.
11803 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11804                                               Type *Ty) const {
11805   // X86 supports extremely general addressing modes.
11806   CodeModel::Model M = getTargetMachine().getCodeModel();
11807   Reloc::Model R = getTargetMachine().getRelocationModel();
11808
11809   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11810   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11811     return false;
11812
11813   if (AM.BaseGV) {
11814     unsigned GVFlags =
11815       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11816
11817     // If a reference to this global requires an extra load, we can't fold it.
11818     if (isGlobalStubReference(GVFlags))
11819       return false;
11820
11821     // If BaseGV requires a register for the PIC base, we cannot also have a
11822     // BaseReg specified.
11823     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11824       return false;
11825
11826     // If lower 4G is not available, then we must use rip-relative addressing.
11827     if ((M != CodeModel::Small || R != Reloc::Static) &&
11828         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11829       return false;
11830   }
11831
11832   switch (AM.Scale) {
11833   case 0:
11834   case 1:
11835   case 2:
11836   case 4:
11837   case 8:
11838     // These scales always work.
11839     break;
11840   case 3:
11841   case 5:
11842   case 9:
11843     // These scales are formed with basereg+scalereg.  Only accept if there is
11844     // no basereg yet.
11845     if (AM.HasBaseReg)
11846       return false;
11847     break;
11848   default:  // Other stuff never works.
11849     return false;
11850   }
11851
11852   return true;
11853 }
11854
11855
11856 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11857   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11858     return false;
11859   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11860   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11861   if (NumBits1 <= NumBits2)
11862     return false;
11863   return true;
11864 }
11865
11866 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11867   return Imm == (int32_t)Imm;
11868 }
11869
11870 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11871   // Can also use sub to handle negated immediates.
11872   return Imm == (int32_t)Imm;
11873 }
11874
11875 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11876   if (!VT1.isInteger() || !VT2.isInteger())
11877     return false;
11878   unsigned NumBits1 = VT1.getSizeInBits();
11879   unsigned NumBits2 = VT2.getSizeInBits();
11880   if (NumBits1 <= NumBits2)
11881     return false;
11882   return true;
11883 }
11884
11885 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11886   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11887   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11888 }
11889
11890 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11891   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11892   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11893 }
11894
11895 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11896   // i16 instructions are longer (0x66 prefix) and potentially slower.
11897   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11898 }
11899
11900 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11901 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11902 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11903 /// are assumed to be legal.
11904 bool
11905 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11906                                       EVT VT) const {
11907   // Very little shuffling can be done for 64-bit vectors right now.
11908   if (VT.getSizeInBits() == 64)
11909     return false;
11910
11911   // FIXME: pshufb, blends, shifts.
11912   return (VT.getVectorNumElements() == 2 ||
11913           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11914           isMOVLMask(M, VT) ||
11915           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11916           isPSHUFDMask(M, VT) ||
11917           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11918           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11919           isPALIGNRMask(M, VT, Subtarget) ||
11920           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11921           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11922           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11923           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11924 }
11925
11926 bool
11927 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11928                                           EVT VT) const {
11929   unsigned NumElts = VT.getVectorNumElements();
11930   // FIXME: This collection of masks seems suspect.
11931   if (NumElts == 2)
11932     return true;
11933   if (NumElts == 4 && VT.is128BitVector()) {
11934     return (isMOVLMask(Mask, VT)  ||
11935             isCommutedMOVLMask(Mask, VT, true) ||
11936             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11937             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11938   }
11939   return false;
11940 }
11941
11942 //===----------------------------------------------------------------------===//
11943 //                           X86 Scheduler Hooks
11944 //===----------------------------------------------------------------------===//
11945
11946 // private utility function
11947
11948 // Get CMPXCHG opcode for the specified data type.
11949 static unsigned getCmpXChgOpcode(EVT VT) {
11950   switch (VT.getSimpleVT().SimpleTy) {
11951   case MVT::i8:  return X86::LCMPXCHG8;
11952   case MVT::i16: return X86::LCMPXCHG16;
11953   case MVT::i32: return X86::LCMPXCHG32;
11954   case MVT::i64: return X86::LCMPXCHG64;
11955   default:
11956     break;
11957   }
11958   llvm_unreachable("Invalid operand size!");
11959 }
11960
11961 // Get LOAD opcode for the specified data type.
11962 static unsigned getLoadOpcode(EVT VT) {
11963   switch (VT.getSimpleVT().SimpleTy) {
11964   case MVT::i8:  return X86::MOV8rm;
11965   case MVT::i16: return X86::MOV16rm;
11966   case MVT::i32: return X86::MOV32rm;
11967   case MVT::i64: return X86::MOV64rm;
11968   default:
11969     break;
11970   }
11971   llvm_unreachable("Invalid operand size!");
11972 }
11973
11974 // Get opcode of the non-atomic one from the specified atomic instruction.
11975 static unsigned getNonAtomicOpcode(unsigned Opc) {
11976   switch (Opc) {
11977   case X86::ATOMAND8:  return X86::AND8rr;
11978   case X86::ATOMAND16: return X86::AND16rr;
11979   case X86::ATOMAND32: return X86::AND32rr;
11980   case X86::ATOMAND64: return X86::AND64rr;
11981   case X86::ATOMOR8:   return X86::OR8rr;
11982   case X86::ATOMOR16:  return X86::OR16rr;
11983   case X86::ATOMOR32:  return X86::OR32rr;
11984   case X86::ATOMOR64:  return X86::OR64rr;
11985   case X86::ATOMXOR8:  return X86::XOR8rr;
11986   case X86::ATOMXOR16: return X86::XOR16rr;
11987   case X86::ATOMXOR32: return X86::XOR32rr;
11988   case X86::ATOMXOR64: return X86::XOR64rr;
11989   }
11990   llvm_unreachable("Unhandled atomic-load-op opcode!");
11991 }
11992
11993 // Get opcode of the non-atomic one from the specified atomic instruction with
11994 // extra opcode.
11995 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
11996                                                unsigned &ExtraOpc) {
11997   switch (Opc) {
11998   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
11999   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12000   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12001   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12002   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12003   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12004   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12005   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12006   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12007   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12008   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12009   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12010   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12011   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12012   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12013   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12014   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12015   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12016   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12017   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12018   }
12019   llvm_unreachable("Unhandled atomic-load-op opcode!");
12020 }
12021
12022 // Get opcode of the non-atomic one from the specified atomic instruction for
12023 // 64-bit data type on 32-bit target.
12024 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12025   switch (Opc) {
12026   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12027   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12028   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12029   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12030   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12031   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12032   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12033   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12034   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12035   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12036   }
12037   llvm_unreachable("Unhandled atomic-load-op opcode!");
12038 }
12039
12040 // Get opcode of the non-atomic one from the specified atomic instruction for
12041 // 64-bit data type on 32-bit target with extra opcode.
12042 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12043                                                    unsigned &HiOpc,
12044                                                    unsigned &ExtraOpc) {
12045   switch (Opc) {
12046   case X86::ATOMNAND6432:
12047     ExtraOpc = X86::NOT32r;
12048     HiOpc = X86::AND32rr;
12049     return X86::AND32rr;
12050   }
12051   llvm_unreachable("Unhandled atomic-load-op opcode!");
12052 }
12053
12054 // Get pseudo CMOV opcode from the specified data type.
12055 static unsigned getPseudoCMOVOpc(EVT VT) {
12056   switch (VT.getSimpleVT().SimpleTy) {
12057   case MVT::i8:  return X86::CMOV_GR8;
12058   case MVT::i16: return X86::CMOV_GR16;
12059   case MVT::i32: return X86::CMOV_GR32;
12060   default:
12061     break;
12062   }
12063   llvm_unreachable("Unknown CMOV opcode!");
12064 }
12065
12066 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12067 // They will be translated into a spin-loop or compare-exchange loop from
12068 //
12069 //    ...
12070 //    dst = atomic-fetch-op MI.addr, MI.val
12071 //    ...
12072 //
12073 // to
12074 //
12075 //    ...
12076 //    EAX = LOAD MI.addr
12077 // loop:
12078 //    t1 = OP MI.val, EAX
12079 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12080 //    JNE loop
12081 // sink:
12082 //    dst = EAX
12083 //    ...
12084 MachineBasicBlock *
12085 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12086                                        MachineBasicBlock *MBB) const {
12087   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12088   DebugLoc DL = MI->getDebugLoc();
12089
12090   MachineFunction *MF = MBB->getParent();
12091   MachineRegisterInfo &MRI = MF->getRegInfo();
12092
12093   const BasicBlock *BB = MBB->getBasicBlock();
12094   MachineFunction::iterator I = MBB;
12095   ++I;
12096
12097   assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12098          "Unexpected number of operands");
12099
12100   assert(MI->hasOneMemOperand() &&
12101          "Expected atomic-load-op to have one memoperand");
12102
12103   // Memory Reference
12104   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12105   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12106
12107   unsigned DstReg, SrcReg;
12108   unsigned MemOpndSlot;
12109
12110   unsigned CurOp = 0;
12111
12112   DstReg = MI->getOperand(CurOp++).getReg();
12113   MemOpndSlot = CurOp;
12114   CurOp += X86::AddrNumOperands;
12115   SrcReg = MI->getOperand(CurOp++).getReg();
12116
12117   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12118   MVT::SimpleValueType VT = *RC->vt_begin();
12119   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12120
12121   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12122   unsigned LOADOpc = getLoadOpcode(VT);
12123
12124   // For the atomic load-arith operator, we generate
12125   //
12126   //  thisMBB:
12127   //    EAX = LOAD [MI.addr]
12128   //  mainMBB:
12129   //    t1 = OP MI.val, EAX
12130   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12131   //    JNE mainMBB
12132   //  sinkMBB:
12133
12134   MachineBasicBlock *thisMBB = MBB;
12135   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12136   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12137   MF->insert(I, mainMBB);
12138   MF->insert(I, sinkMBB);
12139
12140   MachineInstrBuilder MIB;
12141
12142   // Transfer the remainder of BB and its successor edges to sinkMBB.
12143   sinkMBB->splice(sinkMBB->begin(), MBB,
12144                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12145   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12146
12147   // thisMBB:
12148   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12149   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12150     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12151   MIB.setMemRefs(MMOBegin, MMOEnd);
12152
12153   thisMBB->addSuccessor(mainMBB);
12154
12155   // mainMBB:
12156   MachineBasicBlock *origMainMBB = mainMBB;
12157   mainMBB->addLiveIn(AccPhyReg);
12158
12159   // Copy AccPhyReg as it is used more than once.
12160   unsigned AccReg = MRI.createVirtualRegister(RC);
12161   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12162     .addReg(AccPhyReg);
12163
12164   unsigned t1 = MRI.createVirtualRegister(RC);
12165   unsigned Opc = MI->getOpcode();
12166   switch (Opc) {
12167   default:
12168     llvm_unreachable("Unhandled atomic-load-op opcode!");
12169   case X86::ATOMAND8:
12170   case X86::ATOMAND16:
12171   case X86::ATOMAND32:
12172   case X86::ATOMAND64:
12173   case X86::ATOMOR8:
12174   case X86::ATOMOR16:
12175   case X86::ATOMOR32:
12176   case X86::ATOMOR64:
12177   case X86::ATOMXOR8:
12178   case X86::ATOMXOR16:
12179   case X86::ATOMXOR32:
12180   case X86::ATOMXOR64: {
12181     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12182     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12183       .addReg(AccReg);
12184     break;
12185   }
12186   case X86::ATOMNAND8:
12187   case X86::ATOMNAND16:
12188   case X86::ATOMNAND32:
12189   case X86::ATOMNAND64: {
12190     unsigned t2 = MRI.createVirtualRegister(RC);
12191     unsigned NOTOpc;
12192     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12193     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12194       .addReg(AccReg);
12195     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12196     break;
12197   }
12198   case X86::ATOMMAX8:
12199   case X86::ATOMMAX16:
12200   case X86::ATOMMAX32:
12201   case X86::ATOMMAX64:
12202   case X86::ATOMMIN8:
12203   case X86::ATOMMIN16:
12204   case X86::ATOMMIN32:
12205   case X86::ATOMMIN64:
12206   case X86::ATOMUMAX8:
12207   case X86::ATOMUMAX16:
12208   case X86::ATOMUMAX32:
12209   case X86::ATOMUMAX64:
12210   case X86::ATOMUMIN8:
12211   case X86::ATOMUMIN16:
12212   case X86::ATOMUMIN32:
12213   case X86::ATOMUMIN64: {
12214     unsigned CMPOpc;
12215     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12216
12217     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12218       .addReg(SrcReg)
12219       .addReg(AccReg);
12220
12221     if (Subtarget->hasCMov()) {
12222       if (VT != MVT::i8) {
12223         // Native support
12224         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12225           .addReg(SrcReg)
12226           .addReg(AccReg);
12227       } else {
12228         // Promote i8 to i32 to use CMOV32
12229         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12230         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12231         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12232         unsigned t2 = MRI.createVirtualRegister(RC32);
12233
12234         unsigned Undef = MRI.createVirtualRegister(RC32);
12235         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12236
12237         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12238           .addReg(Undef)
12239           .addReg(SrcReg)
12240           .addImm(X86::sub_8bit);
12241         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12242           .addReg(Undef)
12243           .addReg(AccReg)
12244           .addImm(X86::sub_8bit);
12245
12246         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12247           .addReg(SrcReg32)
12248           .addReg(AccReg32);
12249
12250         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12251           .addReg(t2, 0, X86::sub_8bit);
12252       }
12253     } else {
12254       // Use pseudo select and lower them.
12255       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12256              "Invalid atomic-load-op transformation!");
12257       unsigned SelOpc = getPseudoCMOVOpc(VT);
12258       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12259       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12260       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12261               .addReg(SrcReg).addReg(AccReg)
12262               .addImm(CC);
12263       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12264     }
12265     break;
12266   }
12267   }
12268
12269   // Copy AccPhyReg back from virtual register.
12270   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12271     .addReg(AccReg);
12272
12273   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12274   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12275     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12276   MIB.addReg(t1);
12277   MIB.setMemRefs(MMOBegin, MMOEnd);
12278
12279   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12280
12281   mainMBB->addSuccessor(origMainMBB);
12282   mainMBB->addSuccessor(sinkMBB);
12283
12284   // sinkMBB:
12285   sinkMBB->addLiveIn(AccPhyReg);
12286
12287   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12288           TII->get(TargetOpcode::COPY), DstReg)
12289     .addReg(AccPhyReg);
12290
12291   MI->eraseFromParent();
12292   return sinkMBB;
12293 }
12294
12295 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12296 // instructions. They will be translated into a spin-loop or compare-exchange
12297 // loop from
12298 //
12299 //    ...
12300 //    dst = atomic-fetch-op MI.addr, MI.val
12301 //    ...
12302 //
12303 // to
12304 //
12305 //    ...
12306 //    EAX = LOAD [MI.addr + 0]
12307 //    EDX = LOAD [MI.addr + 4]
12308 // loop:
12309 //    EBX = OP MI.val.lo, EAX
12310 //    ECX = OP MI.val.hi, EDX
12311 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12312 //    JNE loop
12313 // sink:
12314 //    dst = EDX:EAX
12315 //    ...
12316 MachineBasicBlock *
12317 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12318                                            MachineBasicBlock *MBB) const {
12319   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12320   DebugLoc DL = MI->getDebugLoc();
12321
12322   MachineFunction *MF = MBB->getParent();
12323   MachineRegisterInfo &MRI = MF->getRegInfo();
12324
12325   const BasicBlock *BB = MBB->getBasicBlock();
12326   MachineFunction::iterator I = MBB;
12327   ++I;
12328
12329   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12330          "Unexpected number of operands");
12331
12332   assert(MI->hasOneMemOperand() &&
12333          "Expected atomic-load-op32 to have one memoperand");
12334
12335   // Memory Reference
12336   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12337   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12338
12339   unsigned DstLoReg, DstHiReg;
12340   unsigned SrcLoReg, SrcHiReg;
12341   unsigned MemOpndSlot;
12342
12343   unsigned CurOp = 0;
12344
12345   DstLoReg = MI->getOperand(CurOp++).getReg();
12346   DstHiReg = MI->getOperand(CurOp++).getReg();
12347   MemOpndSlot = CurOp;
12348   CurOp += X86::AddrNumOperands;
12349   SrcLoReg = MI->getOperand(CurOp++).getReg();
12350   SrcHiReg = MI->getOperand(CurOp++).getReg();
12351
12352   const TargetRegisterClass *RC = &X86::GR32RegClass;
12353   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12354
12355   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12356   unsigned LOADOpc = X86::MOV32rm;
12357
12358   // For the atomic load-arith operator, we generate
12359   //
12360   //  thisMBB:
12361   //    EAX = LOAD [MI.addr + 0]
12362   //    EDX = LOAD [MI.addr + 4]
12363   //  mainMBB:
12364   //    EBX = OP MI.vallo, EAX
12365   //    ECX = OP MI.valhi, EDX
12366   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12367   //    JNE mainMBB
12368   //  sinkMBB:
12369
12370   MachineBasicBlock *thisMBB = MBB;
12371   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12372   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12373   MF->insert(I, mainMBB);
12374   MF->insert(I, sinkMBB);
12375
12376   MachineInstrBuilder MIB;
12377
12378   // Transfer the remainder of BB and its successor edges to sinkMBB.
12379   sinkMBB->splice(sinkMBB->begin(), MBB,
12380                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12381   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12382
12383   // thisMBB:
12384   // Lo
12385   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12386   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12387     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12388   MIB.setMemRefs(MMOBegin, MMOEnd);
12389   // Hi
12390   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12391   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12392     if (i == X86::AddrDisp) {
12393       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12394       // Don't forget to transfer the target flag.
12395       MachineOperand &MO = MIB->getOperand(MIB->getNumOperands()-1);
12396       MO.setTargetFlags(MI->getOperand(MemOpndSlot + i).getTargetFlags());
12397     } else
12398       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12399   }
12400   MIB.setMemRefs(MMOBegin, MMOEnd);
12401
12402   thisMBB->addSuccessor(mainMBB);
12403
12404   // mainMBB:
12405   MachineBasicBlock *origMainMBB = mainMBB;
12406   mainMBB->addLiveIn(X86::EAX);
12407   mainMBB->addLiveIn(X86::EDX);
12408
12409   // Copy EDX:EAX as they are used more than once.
12410   unsigned LoReg = MRI.createVirtualRegister(RC);
12411   unsigned HiReg = MRI.createVirtualRegister(RC);
12412   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12413   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12414
12415   unsigned t1L = MRI.createVirtualRegister(RC);
12416   unsigned t1H = MRI.createVirtualRegister(RC);
12417
12418   unsigned Opc = MI->getOpcode();
12419   switch (Opc) {
12420   default:
12421     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12422   case X86::ATOMAND6432:
12423   case X86::ATOMOR6432:
12424   case X86::ATOMXOR6432:
12425   case X86::ATOMADD6432:
12426   case X86::ATOMSUB6432: {
12427     unsigned HiOpc;
12428     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12429     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12430     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12431     break;
12432   }
12433   case X86::ATOMNAND6432: {
12434     unsigned HiOpc, NOTOpc;
12435     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12436     unsigned t2L = MRI.createVirtualRegister(RC);
12437     unsigned t2H = MRI.createVirtualRegister(RC);
12438     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12439     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12440     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12441     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12442     break;
12443   }
12444   case X86::ATOMMAX6432:
12445   case X86::ATOMMIN6432:
12446   case X86::ATOMUMAX6432:
12447   case X86::ATOMUMIN6432: {
12448     unsigned HiOpc;
12449     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12450     unsigned cL = MRI.createVirtualRegister(RC8);
12451     unsigned cH = MRI.createVirtualRegister(RC8);
12452     unsigned cL32 = MRI.createVirtualRegister(RC);
12453     unsigned cH32 = MRI.createVirtualRegister(RC);
12454     unsigned cc = MRI.createVirtualRegister(RC);
12455     // cl := cmp src_lo, lo
12456     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12457       .addReg(SrcLoReg).addReg(LoReg);
12458     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12459     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12460     // ch := cmp src_hi, hi
12461     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12462       .addReg(SrcHiReg).addReg(HiReg);
12463     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12464     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12465     // cc := if (src_hi == hi) ? cl : ch;
12466     if (Subtarget->hasCMov()) {
12467       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12468         .addReg(cH32).addReg(cL32);
12469     } else {
12470       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12471               .addReg(cH32).addReg(cL32)
12472               .addImm(X86::COND_E);
12473       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12474     }
12475     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12476     if (Subtarget->hasCMov()) {
12477       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12478         .addReg(SrcLoReg).addReg(LoReg);
12479       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12480         .addReg(SrcHiReg).addReg(HiReg);
12481     } else {
12482       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12483               .addReg(SrcLoReg).addReg(LoReg)
12484               .addImm(X86::COND_NE);
12485       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12486       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12487               .addReg(SrcHiReg).addReg(HiReg)
12488               .addImm(X86::COND_NE);
12489       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12490     }
12491     break;
12492   }
12493   case X86::ATOMSWAP6432: {
12494     unsigned HiOpc;
12495     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12496     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12497     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12498     break;
12499   }
12500   }
12501
12502   // Copy EDX:EAX back from HiReg:LoReg
12503   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12504   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12505   // Copy ECX:EBX from t1H:t1L
12506   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12507   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12508
12509   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12510   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12511     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12512   MIB.setMemRefs(MMOBegin, MMOEnd);
12513
12514   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12515
12516   mainMBB->addSuccessor(origMainMBB);
12517   mainMBB->addSuccessor(sinkMBB);
12518
12519   // sinkMBB:
12520   sinkMBB->addLiveIn(X86::EAX);
12521   sinkMBB->addLiveIn(X86::EDX);
12522
12523   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12524           TII->get(TargetOpcode::COPY), DstLoReg)
12525     .addReg(X86::EAX);
12526   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12527           TII->get(TargetOpcode::COPY), DstHiReg)
12528     .addReg(X86::EDX);
12529
12530   MI->eraseFromParent();
12531   return sinkMBB;
12532 }
12533
12534 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12535 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12536 // in the .td file.
12537 MachineBasicBlock *
12538 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12539                             unsigned numArgs, bool memArg) const {
12540   assert(Subtarget->hasSSE42() &&
12541          "Target must have SSE4.2 or AVX features enabled");
12542
12543   DebugLoc dl = MI->getDebugLoc();
12544   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12545   unsigned Opc;
12546   if (!Subtarget->hasAVX()) {
12547     if (memArg)
12548       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12549     else
12550       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12551   } else {
12552     if (memArg)
12553       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12554     else
12555       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12556   }
12557
12558   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12559   for (unsigned i = 0; i < numArgs; ++i) {
12560     MachineOperand &Op = MI->getOperand(i+1);
12561     if (!(Op.isReg() && Op.isImplicit()))
12562       MIB.addOperand(Op);
12563   }
12564   BuildMI(*BB, MI, dl,
12565     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12566     .addReg(X86::XMM0);
12567
12568   MI->eraseFromParent();
12569   return BB;
12570 }
12571
12572 MachineBasicBlock *
12573 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12574   DebugLoc dl = MI->getDebugLoc();
12575   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12576
12577   // Address into RAX/EAX, other two args into ECX, EDX.
12578   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12579   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12580   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12581   for (int i = 0; i < X86::AddrNumOperands; ++i)
12582     MIB.addOperand(MI->getOperand(i));
12583
12584   unsigned ValOps = X86::AddrNumOperands;
12585   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12586     .addReg(MI->getOperand(ValOps).getReg());
12587   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12588     .addReg(MI->getOperand(ValOps+1).getReg());
12589
12590   // The instruction doesn't actually take any operands though.
12591   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12592
12593   MI->eraseFromParent(); // The pseudo is gone now.
12594   return BB;
12595 }
12596
12597 MachineBasicBlock *
12598 X86TargetLowering::EmitVAARG64WithCustomInserter(
12599                    MachineInstr *MI,
12600                    MachineBasicBlock *MBB) const {
12601   // Emit va_arg instruction on X86-64.
12602
12603   // Operands to this pseudo-instruction:
12604   // 0  ) Output        : destination address (reg)
12605   // 1-5) Input         : va_list address (addr, i64mem)
12606   // 6  ) ArgSize       : Size (in bytes) of vararg type
12607   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12608   // 8  ) Align         : Alignment of type
12609   // 9  ) EFLAGS (implicit-def)
12610
12611   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12612   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12613
12614   unsigned DestReg = MI->getOperand(0).getReg();
12615   MachineOperand &Base = MI->getOperand(1);
12616   MachineOperand &Scale = MI->getOperand(2);
12617   MachineOperand &Index = MI->getOperand(3);
12618   MachineOperand &Disp = MI->getOperand(4);
12619   MachineOperand &Segment = MI->getOperand(5);
12620   unsigned ArgSize = MI->getOperand(6).getImm();
12621   unsigned ArgMode = MI->getOperand(7).getImm();
12622   unsigned Align = MI->getOperand(8).getImm();
12623
12624   // Memory Reference
12625   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12626   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12627   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12628
12629   // Machine Information
12630   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12631   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12632   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12633   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12634   DebugLoc DL = MI->getDebugLoc();
12635
12636   // struct va_list {
12637   //   i32   gp_offset
12638   //   i32   fp_offset
12639   //   i64   overflow_area (address)
12640   //   i64   reg_save_area (address)
12641   // }
12642   // sizeof(va_list) = 24
12643   // alignment(va_list) = 8
12644
12645   unsigned TotalNumIntRegs = 6;
12646   unsigned TotalNumXMMRegs = 8;
12647   bool UseGPOffset = (ArgMode == 1);
12648   bool UseFPOffset = (ArgMode == 2);
12649   unsigned MaxOffset = TotalNumIntRegs * 8 +
12650                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12651
12652   /* Align ArgSize to a multiple of 8 */
12653   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12654   bool NeedsAlign = (Align > 8);
12655
12656   MachineBasicBlock *thisMBB = MBB;
12657   MachineBasicBlock *overflowMBB;
12658   MachineBasicBlock *offsetMBB;
12659   MachineBasicBlock *endMBB;
12660
12661   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12662   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12663   unsigned OffsetReg = 0;
12664
12665   if (!UseGPOffset && !UseFPOffset) {
12666     // If we only pull from the overflow region, we don't create a branch.
12667     // We don't need to alter control flow.
12668     OffsetDestReg = 0; // unused
12669     OverflowDestReg = DestReg;
12670
12671     offsetMBB = NULL;
12672     overflowMBB = thisMBB;
12673     endMBB = thisMBB;
12674   } else {
12675     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12676     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12677     // If not, pull from overflow_area. (branch to overflowMBB)
12678     //
12679     //       thisMBB
12680     //         |     .
12681     //         |        .
12682     //     offsetMBB   overflowMBB
12683     //         |        .
12684     //         |     .
12685     //        endMBB
12686
12687     // Registers for the PHI in endMBB
12688     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12689     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12690
12691     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12692     MachineFunction *MF = MBB->getParent();
12693     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12694     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12695     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12696
12697     MachineFunction::iterator MBBIter = MBB;
12698     ++MBBIter;
12699
12700     // Insert the new basic blocks
12701     MF->insert(MBBIter, offsetMBB);
12702     MF->insert(MBBIter, overflowMBB);
12703     MF->insert(MBBIter, endMBB);
12704
12705     // Transfer the remainder of MBB and its successor edges to endMBB.
12706     endMBB->splice(endMBB->begin(), thisMBB,
12707                     llvm::next(MachineBasicBlock::iterator(MI)),
12708                     thisMBB->end());
12709     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12710
12711     // Make offsetMBB and overflowMBB successors of thisMBB
12712     thisMBB->addSuccessor(offsetMBB);
12713     thisMBB->addSuccessor(overflowMBB);
12714
12715     // endMBB is a successor of both offsetMBB and overflowMBB
12716     offsetMBB->addSuccessor(endMBB);
12717     overflowMBB->addSuccessor(endMBB);
12718
12719     // Load the offset value into a register
12720     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12721     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12722       .addOperand(Base)
12723       .addOperand(Scale)
12724       .addOperand(Index)
12725       .addDisp(Disp, UseFPOffset ? 4 : 0)
12726       .addOperand(Segment)
12727       .setMemRefs(MMOBegin, MMOEnd);
12728
12729     // Check if there is enough room left to pull this argument.
12730     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12731       .addReg(OffsetReg)
12732       .addImm(MaxOffset + 8 - ArgSizeA8);
12733
12734     // Branch to "overflowMBB" if offset >= max
12735     // Fall through to "offsetMBB" otherwise
12736     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12737       .addMBB(overflowMBB);
12738   }
12739
12740   // In offsetMBB, emit code to use the reg_save_area.
12741   if (offsetMBB) {
12742     assert(OffsetReg != 0);
12743
12744     // Read the reg_save_area address.
12745     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12746     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12747       .addOperand(Base)
12748       .addOperand(Scale)
12749       .addOperand(Index)
12750       .addDisp(Disp, 16)
12751       .addOperand(Segment)
12752       .setMemRefs(MMOBegin, MMOEnd);
12753
12754     // Zero-extend the offset
12755     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12756       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12757         .addImm(0)
12758         .addReg(OffsetReg)
12759         .addImm(X86::sub_32bit);
12760
12761     // Add the offset to the reg_save_area to get the final address.
12762     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12763       .addReg(OffsetReg64)
12764       .addReg(RegSaveReg);
12765
12766     // Compute the offset for the next argument
12767     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12768     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12769       .addReg(OffsetReg)
12770       .addImm(UseFPOffset ? 16 : 8);
12771
12772     // Store it back into the va_list.
12773     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12774       .addOperand(Base)
12775       .addOperand(Scale)
12776       .addOperand(Index)
12777       .addDisp(Disp, UseFPOffset ? 4 : 0)
12778       .addOperand(Segment)
12779       .addReg(NextOffsetReg)
12780       .setMemRefs(MMOBegin, MMOEnd);
12781
12782     // Jump to endMBB
12783     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12784       .addMBB(endMBB);
12785   }
12786
12787   //
12788   // Emit code to use overflow area
12789   //
12790
12791   // Load the overflow_area address into a register.
12792   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12793   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12794     .addOperand(Base)
12795     .addOperand(Scale)
12796     .addOperand(Index)
12797     .addDisp(Disp, 8)
12798     .addOperand(Segment)
12799     .setMemRefs(MMOBegin, MMOEnd);
12800
12801   // If we need to align it, do so. Otherwise, just copy the address
12802   // to OverflowDestReg.
12803   if (NeedsAlign) {
12804     // Align the overflow address
12805     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12806     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12807
12808     // aligned_addr = (addr + (align-1)) & ~(align-1)
12809     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12810       .addReg(OverflowAddrReg)
12811       .addImm(Align-1);
12812
12813     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12814       .addReg(TmpReg)
12815       .addImm(~(uint64_t)(Align-1));
12816   } else {
12817     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12818       .addReg(OverflowAddrReg);
12819   }
12820
12821   // Compute the next overflow address after this argument.
12822   // (the overflow address should be kept 8-byte aligned)
12823   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12824   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12825     .addReg(OverflowDestReg)
12826     .addImm(ArgSizeA8);
12827
12828   // Store the new overflow address.
12829   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12830     .addOperand(Base)
12831     .addOperand(Scale)
12832     .addOperand(Index)
12833     .addDisp(Disp, 8)
12834     .addOperand(Segment)
12835     .addReg(NextAddrReg)
12836     .setMemRefs(MMOBegin, MMOEnd);
12837
12838   // If we branched, emit the PHI to the front of endMBB.
12839   if (offsetMBB) {
12840     BuildMI(*endMBB, endMBB->begin(), DL,
12841             TII->get(X86::PHI), DestReg)
12842       .addReg(OffsetDestReg).addMBB(offsetMBB)
12843       .addReg(OverflowDestReg).addMBB(overflowMBB);
12844   }
12845
12846   // Erase the pseudo instruction
12847   MI->eraseFromParent();
12848
12849   return endMBB;
12850 }
12851
12852 MachineBasicBlock *
12853 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12854                                                  MachineInstr *MI,
12855                                                  MachineBasicBlock *MBB) const {
12856   // Emit code to save XMM registers to the stack. The ABI says that the
12857   // number of registers to save is given in %al, so it's theoretically
12858   // possible to do an indirect jump trick to avoid saving all of them,
12859   // however this code takes a simpler approach and just executes all
12860   // of the stores if %al is non-zero. It's less code, and it's probably
12861   // easier on the hardware branch predictor, and stores aren't all that
12862   // expensive anyway.
12863
12864   // Create the new basic blocks. One block contains all the XMM stores,
12865   // and one block is the final destination regardless of whether any
12866   // stores were performed.
12867   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12868   MachineFunction *F = MBB->getParent();
12869   MachineFunction::iterator MBBIter = MBB;
12870   ++MBBIter;
12871   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12872   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12873   F->insert(MBBIter, XMMSaveMBB);
12874   F->insert(MBBIter, EndMBB);
12875
12876   // Transfer the remainder of MBB and its successor edges to EndMBB.
12877   EndMBB->splice(EndMBB->begin(), MBB,
12878                  llvm::next(MachineBasicBlock::iterator(MI)),
12879                  MBB->end());
12880   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12881
12882   // The original block will now fall through to the XMM save block.
12883   MBB->addSuccessor(XMMSaveMBB);
12884   // The XMMSaveMBB will fall through to the end block.
12885   XMMSaveMBB->addSuccessor(EndMBB);
12886
12887   // Now add the instructions.
12888   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12889   DebugLoc DL = MI->getDebugLoc();
12890
12891   unsigned CountReg = MI->getOperand(0).getReg();
12892   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12893   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12894
12895   if (!Subtarget->isTargetWin64()) {
12896     // If %al is 0, branch around the XMM save block.
12897     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12898     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12899     MBB->addSuccessor(EndMBB);
12900   }
12901
12902   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12903   // In the XMM save block, save all the XMM argument registers.
12904   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12905     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12906     MachineMemOperand *MMO =
12907       F->getMachineMemOperand(
12908           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12909         MachineMemOperand::MOStore,
12910         /*Size=*/16, /*Align=*/16);
12911     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12912       .addFrameIndex(RegSaveFrameIndex)
12913       .addImm(/*Scale=*/1)
12914       .addReg(/*IndexReg=*/0)
12915       .addImm(/*Disp=*/Offset)
12916       .addReg(/*Segment=*/0)
12917       .addReg(MI->getOperand(i).getReg())
12918       .addMemOperand(MMO);
12919   }
12920
12921   MI->eraseFromParent();   // The pseudo instruction is gone now.
12922
12923   return EndMBB;
12924 }
12925
12926 // The EFLAGS operand of SelectItr might be missing a kill marker
12927 // because there were multiple uses of EFLAGS, and ISel didn't know
12928 // which to mark. Figure out whether SelectItr should have had a
12929 // kill marker, and set it if it should. Returns the correct kill
12930 // marker value.
12931 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12932                                      MachineBasicBlock* BB,
12933                                      const TargetRegisterInfo* TRI) {
12934   // Scan forward through BB for a use/def of EFLAGS.
12935   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12936   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12937     const MachineInstr& mi = *miI;
12938     if (mi.readsRegister(X86::EFLAGS))
12939       return false;
12940     if (mi.definesRegister(X86::EFLAGS))
12941       break; // Should have kill-flag - update below.
12942   }
12943
12944   // If we hit the end of the block, check whether EFLAGS is live into a
12945   // successor.
12946   if (miI == BB->end()) {
12947     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12948                                           sEnd = BB->succ_end();
12949          sItr != sEnd; ++sItr) {
12950       MachineBasicBlock* succ = *sItr;
12951       if (succ->isLiveIn(X86::EFLAGS))
12952         return false;
12953     }
12954   }
12955
12956   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12957   // out. SelectMI should have a kill flag on EFLAGS.
12958   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12959   return true;
12960 }
12961
12962 MachineBasicBlock *
12963 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12964                                      MachineBasicBlock *BB) const {
12965   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12966   DebugLoc DL = MI->getDebugLoc();
12967
12968   // To "insert" a SELECT_CC instruction, we actually have to insert the
12969   // diamond control-flow pattern.  The incoming instruction knows the
12970   // destination vreg to set, the condition code register to branch on, the
12971   // true/false values to select between, and a branch opcode to use.
12972   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12973   MachineFunction::iterator It = BB;
12974   ++It;
12975
12976   //  thisMBB:
12977   //  ...
12978   //   TrueVal = ...
12979   //   cmpTY ccX, r1, r2
12980   //   bCC copy1MBB
12981   //   fallthrough --> copy0MBB
12982   MachineBasicBlock *thisMBB = BB;
12983   MachineFunction *F = BB->getParent();
12984   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12985   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12986   F->insert(It, copy0MBB);
12987   F->insert(It, sinkMBB);
12988
12989   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12990   // live into the sink and copy blocks.
12991   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12992   if (!MI->killsRegister(X86::EFLAGS) &&
12993       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12994     copy0MBB->addLiveIn(X86::EFLAGS);
12995     sinkMBB->addLiveIn(X86::EFLAGS);
12996   }
12997
12998   // Transfer the remainder of BB and its successor edges to sinkMBB.
12999   sinkMBB->splice(sinkMBB->begin(), BB,
13000                   llvm::next(MachineBasicBlock::iterator(MI)),
13001                   BB->end());
13002   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13003
13004   // Add the true and fallthrough blocks as its successors.
13005   BB->addSuccessor(copy0MBB);
13006   BB->addSuccessor(sinkMBB);
13007
13008   // Create the conditional branch instruction.
13009   unsigned Opc =
13010     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13011   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13012
13013   //  copy0MBB:
13014   //   %FalseValue = ...
13015   //   # fallthrough to sinkMBB
13016   copy0MBB->addSuccessor(sinkMBB);
13017
13018   //  sinkMBB:
13019   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13020   //  ...
13021   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13022           TII->get(X86::PHI), MI->getOperand(0).getReg())
13023     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13024     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13025
13026   MI->eraseFromParent();   // The pseudo instruction is gone now.
13027   return sinkMBB;
13028 }
13029
13030 MachineBasicBlock *
13031 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13032                                         bool Is64Bit) const {
13033   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13034   DebugLoc DL = MI->getDebugLoc();
13035   MachineFunction *MF = BB->getParent();
13036   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13037
13038   assert(getTargetMachine().Options.EnableSegmentedStacks);
13039
13040   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13041   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13042
13043   // BB:
13044   //  ... [Till the alloca]
13045   // If stacklet is not large enough, jump to mallocMBB
13046   //
13047   // bumpMBB:
13048   //  Allocate by subtracting from RSP
13049   //  Jump to continueMBB
13050   //
13051   // mallocMBB:
13052   //  Allocate by call to runtime
13053   //
13054   // continueMBB:
13055   //  ...
13056   //  [rest of original BB]
13057   //
13058
13059   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13060   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13061   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13062
13063   MachineRegisterInfo &MRI = MF->getRegInfo();
13064   const TargetRegisterClass *AddrRegClass =
13065     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13066
13067   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13068     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13069     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13070     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13071     sizeVReg = MI->getOperand(1).getReg(),
13072     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13073
13074   MachineFunction::iterator MBBIter = BB;
13075   ++MBBIter;
13076
13077   MF->insert(MBBIter, bumpMBB);
13078   MF->insert(MBBIter, mallocMBB);
13079   MF->insert(MBBIter, continueMBB);
13080
13081   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13082                       (MachineBasicBlock::iterator(MI)), BB->end());
13083   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13084
13085   // Add code to the main basic block to check if the stack limit has been hit,
13086   // and if so, jump to mallocMBB otherwise to bumpMBB.
13087   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13088   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13089     .addReg(tmpSPVReg).addReg(sizeVReg);
13090   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13091     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13092     .addReg(SPLimitVReg);
13093   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13094
13095   // bumpMBB simply decreases the stack pointer, since we know the current
13096   // stacklet has enough space.
13097   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13098     .addReg(SPLimitVReg);
13099   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13100     .addReg(SPLimitVReg);
13101   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13102
13103   // Calls into a routine in libgcc to allocate more space from the heap.
13104   const uint32_t *RegMask =
13105     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13106   if (Is64Bit) {
13107     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13108       .addReg(sizeVReg);
13109     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13110       .addExternalSymbol("__morestack_allocate_stack_space")
13111       .addRegMask(RegMask)
13112       .addReg(X86::RDI, RegState::Implicit)
13113       .addReg(X86::RAX, RegState::ImplicitDefine);
13114   } else {
13115     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13116       .addImm(12);
13117     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13118     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13119       .addExternalSymbol("__morestack_allocate_stack_space")
13120       .addRegMask(RegMask)
13121       .addReg(X86::EAX, RegState::ImplicitDefine);
13122   }
13123
13124   if (!Is64Bit)
13125     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13126       .addImm(16);
13127
13128   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13129     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13130   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13131
13132   // Set up the CFG correctly.
13133   BB->addSuccessor(bumpMBB);
13134   BB->addSuccessor(mallocMBB);
13135   mallocMBB->addSuccessor(continueMBB);
13136   bumpMBB->addSuccessor(continueMBB);
13137
13138   // Take care of the PHI nodes.
13139   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13140           MI->getOperand(0).getReg())
13141     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13142     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13143
13144   // Delete the original pseudo instruction.
13145   MI->eraseFromParent();
13146
13147   // And we're done.
13148   return continueMBB;
13149 }
13150
13151 MachineBasicBlock *
13152 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13153                                           MachineBasicBlock *BB) const {
13154   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13155   DebugLoc DL = MI->getDebugLoc();
13156
13157   assert(!Subtarget->isTargetEnvMacho());
13158
13159   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13160   // non-trivial part is impdef of ESP.
13161
13162   if (Subtarget->isTargetWin64()) {
13163     if (Subtarget->isTargetCygMing()) {
13164       // ___chkstk(Mingw64):
13165       // Clobbers R10, R11, RAX and EFLAGS.
13166       // Updates RSP.
13167       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13168         .addExternalSymbol("___chkstk")
13169         .addReg(X86::RAX, RegState::Implicit)
13170         .addReg(X86::RSP, RegState::Implicit)
13171         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13172         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13173         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13174     } else {
13175       // __chkstk(MSVCRT): does not update stack pointer.
13176       // Clobbers R10, R11 and EFLAGS.
13177       // FIXME: RAX(allocated size) might be reused and not killed.
13178       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13179         .addExternalSymbol("__chkstk")
13180         .addReg(X86::RAX, RegState::Implicit)
13181         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13182       // RAX has the offset to subtracted from RSP.
13183       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13184         .addReg(X86::RSP)
13185         .addReg(X86::RAX);
13186     }
13187   } else {
13188     const char *StackProbeSymbol =
13189       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13190
13191     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13192       .addExternalSymbol(StackProbeSymbol)
13193       .addReg(X86::EAX, RegState::Implicit)
13194       .addReg(X86::ESP, RegState::Implicit)
13195       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13196       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13197       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13198   }
13199
13200   MI->eraseFromParent();   // The pseudo instruction is gone now.
13201   return BB;
13202 }
13203
13204 MachineBasicBlock *
13205 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13206                                       MachineBasicBlock *BB) const {
13207   // This is pretty easy.  We're taking the value that we received from
13208   // our load from the relocation, sticking it in either RDI (x86-64)
13209   // or EAX and doing an indirect call.  The return value will then
13210   // be in the normal return register.
13211   const X86InstrInfo *TII
13212     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13213   DebugLoc DL = MI->getDebugLoc();
13214   MachineFunction *F = BB->getParent();
13215
13216   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13217   assert(MI->getOperand(3).isGlobal() && "This should be a global");
13218
13219   // Get a register mask for the lowered call.
13220   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13221   // proper register mask.
13222   const uint32_t *RegMask =
13223     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13224   if (Subtarget->is64Bit()) {
13225     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13226                                       TII->get(X86::MOV64rm), X86::RDI)
13227     .addReg(X86::RIP)
13228     .addImm(0).addReg(0)
13229     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13230                       MI->getOperand(3).getTargetFlags())
13231     .addReg(0);
13232     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13233     addDirectMem(MIB, X86::RDI);
13234     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13235   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13236     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13237                                       TII->get(X86::MOV32rm), X86::EAX)
13238     .addReg(0)
13239     .addImm(0).addReg(0)
13240     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13241                       MI->getOperand(3).getTargetFlags())
13242     .addReg(0);
13243     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13244     addDirectMem(MIB, X86::EAX);
13245     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13246   } else {
13247     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13248                                       TII->get(X86::MOV32rm), X86::EAX)
13249     .addReg(TII->getGlobalBaseReg(F))
13250     .addImm(0).addReg(0)
13251     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13252                       MI->getOperand(3).getTargetFlags())
13253     .addReg(0);
13254     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13255     addDirectMem(MIB, X86::EAX);
13256     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13257   }
13258
13259   MI->eraseFromParent(); // The pseudo instruction is gone now.
13260   return BB;
13261 }
13262
13263 MachineBasicBlock *
13264 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13265                                                MachineBasicBlock *BB) const {
13266   switch (MI->getOpcode()) {
13267   default: llvm_unreachable("Unexpected instr type to insert");
13268   case X86::TAILJMPd64:
13269   case X86::TAILJMPr64:
13270   case X86::TAILJMPm64:
13271     llvm_unreachable("TAILJMP64 would not be touched here.");
13272   case X86::TCRETURNdi64:
13273   case X86::TCRETURNri64:
13274   case X86::TCRETURNmi64:
13275     return BB;
13276   case X86::WIN_ALLOCA:
13277     return EmitLoweredWinAlloca(MI, BB);
13278   case X86::SEG_ALLOCA_32:
13279     return EmitLoweredSegAlloca(MI, BB, false);
13280   case X86::SEG_ALLOCA_64:
13281     return EmitLoweredSegAlloca(MI, BB, true);
13282   case X86::TLSCall_32:
13283   case X86::TLSCall_64:
13284     return EmitLoweredTLSCall(MI, BB);
13285   case X86::CMOV_GR8:
13286   case X86::CMOV_FR32:
13287   case X86::CMOV_FR64:
13288   case X86::CMOV_V4F32:
13289   case X86::CMOV_V2F64:
13290   case X86::CMOV_V2I64:
13291   case X86::CMOV_V8F32:
13292   case X86::CMOV_V4F64:
13293   case X86::CMOV_V4I64:
13294   case X86::CMOV_GR16:
13295   case X86::CMOV_GR32:
13296   case X86::CMOV_RFP32:
13297   case X86::CMOV_RFP64:
13298   case X86::CMOV_RFP80:
13299     return EmitLoweredSelect(MI, BB);
13300
13301   case X86::FP32_TO_INT16_IN_MEM:
13302   case X86::FP32_TO_INT32_IN_MEM:
13303   case X86::FP32_TO_INT64_IN_MEM:
13304   case X86::FP64_TO_INT16_IN_MEM:
13305   case X86::FP64_TO_INT32_IN_MEM:
13306   case X86::FP64_TO_INT64_IN_MEM:
13307   case X86::FP80_TO_INT16_IN_MEM:
13308   case X86::FP80_TO_INT32_IN_MEM:
13309   case X86::FP80_TO_INT64_IN_MEM: {
13310     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13311     DebugLoc DL = MI->getDebugLoc();
13312
13313     // Change the floating point control register to use "round towards zero"
13314     // mode when truncating to an integer value.
13315     MachineFunction *F = BB->getParent();
13316     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13317     addFrameReference(BuildMI(*BB, MI, DL,
13318                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
13319
13320     // Load the old value of the high byte of the control word...
13321     unsigned OldCW =
13322       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13323     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13324                       CWFrameIdx);
13325
13326     // Set the high part to be round to zero...
13327     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13328       .addImm(0xC7F);
13329
13330     // Reload the modified control word now...
13331     addFrameReference(BuildMI(*BB, MI, DL,
13332                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13333
13334     // Restore the memory image of control word to original value
13335     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13336       .addReg(OldCW);
13337
13338     // Get the X86 opcode to use.
13339     unsigned Opc;
13340     switch (MI->getOpcode()) {
13341     default: llvm_unreachable("illegal opcode!");
13342     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13343     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13344     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13345     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13346     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13347     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13348     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13349     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13350     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13351     }
13352
13353     X86AddressMode AM;
13354     MachineOperand &Op = MI->getOperand(0);
13355     if (Op.isReg()) {
13356       AM.BaseType = X86AddressMode::RegBase;
13357       AM.Base.Reg = Op.getReg();
13358     } else {
13359       AM.BaseType = X86AddressMode::FrameIndexBase;
13360       AM.Base.FrameIndex = Op.getIndex();
13361     }
13362     Op = MI->getOperand(1);
13363     if (Op.isImm())
13364       AM.Scale = Op.getImm();
13365     Op = MI->getOperand(2);
13366     if (Op.isImm())
13367       AM.IndexReg = Op.getImm();
13368     Op = MI->getOperand(3);
13369     if (Op.isGlobal()) {
13370       AM.GV = Op.getGlobal();
13371     } else {
13372       AM.Disp = Op.getImm();
13373     }
13374     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13375                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13376
13377     // Reload the original control word now.
13378     addFrameReference(BuildMI(*BB, MI, DL,
13379                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13380
13381     MI->eraseFromParent();   // The pseudo instruction is gone now.
13382     return BB;
13383   }
13384     // String/text processing lowering.
13385   case X86::PCMPISTRM128REG:
13386   case X86::VPCMPISTRM128REG:
13387   case X86::PCMPISTRM128MEM:
13388   case X86::VPCMPISTRM128MEM:
13389   case X86::PCMPESTRM128REG:
13390   case X86::VPCMPESTRM128REG:
13391   case X86::PCMPESTRM128MEM:
13392   case X86::VPCMPESTRM128MEM: {
13393     unsigned NumArgs;
13394     bool MemArg;
13395     switch (MI->getOpcode()) {
13396     default: llvm_unreachable("illegal opcode!");
13397     case X86::PCMPISTRM128REG:
13398     case X86::VPCMPISTRM128REG:
13399       NumArgs = 3; MemArg = false; break;
13400     case X86::PCMPISTRM128MEM:
13401     case X86::VPCMPISTRM128MEM:
13402       NumArgs = 3; MemArg = true; break;
13403     case X86::PCMPESTRM128REG:
13404     case X86::VPCMPESTRM128REG:
13405       NumArgs = 5; MemArg = false; break;
13406     case X86::PCMPESTRM128MEM:
13407     case X86::VPCMPESTRM128MEM:
13408       NumArgs = 5; MemArg = true; break;
13409     }
13410     return EmitPCMP(MI, BB, NumArgs, MemArg);
13411   }
13412
13413     // Thread synchronization.
13414   case X86::MONITOR:
13415     return EmitMonitor(MI, BB);
13416
13417     // Atomic Lowering.
13418   case X86::ATOMAND8:
13419   case X86::ATOMAND16:
13420   case X86::ATOMAND32:
13421   case X86::ATOMAND64:
13422     // Fall through
13423   case X86::ATOMOR8:
13424   case X86::ATOMOR16:
13425   case X86::ATOMOR32:
13426   case X86::ATOMOR64:
13427     // Fall through
13428   case X86::ATOMXOR16:
13429   case X86::ATOMXOR8:
13430   case X86::ATOMXOR32:
13431   case X86::ATOMXOR64:
13432     // Fall through
13433   case X86::ATOMNAND8:
13434   case X86::ATOMNAND16:
13435   case X86::ATOMNAND32:
13436   case X86::ATOMNAND64:
13437     // Fall through
13438   case X86::ATOMMAX8:
13439   case X86::ATOMMAX16:
13440   case X86::ATOMMAX32:
13441   case X86::ATOMMAX64:
13442     // Fall through
13443   case X86::ATOMMIN8:
13444   case X86::ATOMMIN16:
13445   case X86::ATOMMIN32:
13446   case X86::ATOMMIN64:
13447     // Fall through
13448   case X86::ATOMUMAX8:
13449   case X86::ATOMUMAX16:
13450   case X86::ATOMUMAX32:
13451   case X86::ATOMUMAX64:
13452     // Fall through
13453   case X86::ATOMUMIN8:
13454   case X86::ATOMUMIN16:
13455   case X86::ATOMUMIN32:
13456   case X86::ATOMUMIN64:
13457     return EmitAtomicLoadArith(MI, BB);
13458
13459   // This group does 64-bit operations on a 32-bit host.
13460   case X86::ATOMAND6432:
13461   case X86::ATOMOR6432:
13462   case X86::ATOMXOR6432:
13463   case X86::ATOMNAND6432:
13464   case X86::ATOMADD6432:
13465   case X86::ATOMSUB6432:
13466   case X86::ATOMMAX6432:
13467   case X86::ATOMMIN6432:
13468   case X86::ATOMUMAX6432:
13469   case X86::ATOMUMIN6432:
13470   case X86::ATOMSWAP6432:
13471     return EmitAtomicLoadArith6432(MI, BB);
13472
13473   case X86::VASTART_SAVE_XMM_REGS:
13474     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13475
13476   case X86::VAARG_64:
13477     return EmitVAARG64WithCustomInserter(MI, BB);
13478   }
13479 }
13480
13481 //===----------------------------------------------------------------------===//
13482 //                           X86 Optimization Hooks
13483 //===----------------------------------------------------------------------===//
13484
13485 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13486                                                        APInt &KnownZero,
13487                                                        APInt &KnownOne,
13488                                                        const SelectionDAG &DAG,
13489                                                        unsigned Depth) const {
13490   unsigned BitWidth = KnownZero.getBitWidth();
13491   unsigned Opc = Op.getOpcode();
13492   assert((Opc >= ISD::BUILTIN_OP_END ||
13493           Opc == ISD::INTRINSIC_WO_CHAIN ||
13494           Opc == ISD::INTRINSIC_W_CHAIN ||
13495           Opc == ISD::INTRINSIC_VOID) &&
13496          "Should use MaskedValueIsZero if you don't know whether Op"
13497          " is a target node!");
13498
13499   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13500   switch (Opc) {
13501   default: break;
13502   case X86ISD::ADD:
13503   case X86ISD::SUB:
13504   case X86ISD::ADC:
13505   case X86ISD::SBB:
13506   case X86ISD::SMUL:
13507   case X86ISD::UMUL:
13508   case X86ISD::INC:
13509   case X86ISD::DEC:
13510   case X86ISD::OR:
13511   case X86ISD::XOR:
13512   case X86ISD::AND:
13513     // These nodes' second result is a boolean.
13514     if (Op.getResNo() == 0)
13515       break;
13516     // Fallthrough
13517   case X86ISD::SETCC:
13518     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13519     break;
13520   case ISD::INTRINSIC_WO_CHAIN: {
13521     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13522     unsigned NumLoBits = 0;
13523     switch (IntId) {
13524     default: break;
13525     case Intrinsic::x86_sse_movmsk_ps:
13526     case Intrinsic::x86_avx_movmsk_ps_256:
13527     case Intrinsic::x86_sse2_movmsk_pd:
13528     case Intrinsic::x86_avx_movmsk_pd_256:
13529     case Intrinsic::x86_mmx_pmovmskb:
13530     case Intrinsic::x86_sse2_pmovmskb_128:
13531     case Intrinsic::x86_avx2_pmovmskb: {
13532       // High bits of movmskp{s|d}, pmovmskb are known zero.
13533       switch (IntId) {
13534         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13535         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13536         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13537         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13538         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13539         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13540         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13541         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13542       }
13543       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13544       break;
13545     }
13546     }
13547     break;
13548   }
13549   }
13550 }
13551
13552 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13553                                                          unsigned Depth) const {
13554   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13555   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13556     return Op.getValueType().getScalarType().getSizeInBits();
13557
13558   // Fallback case.
13559   return 1;
13560 }
13561
13562 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13563 /// node is a GlobalAddress + offset.
13564 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13565                                        const GlobalValue* &GA,
13566                                        int64_t &Offset) const {
13567   if (N->getOpcode() == X86ISD::Wrapper) {
13568     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13569       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13570       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13571       return true;
13572     }
13573   }
13574   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13575 }
13576
13577 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13578 /// same as extracting the high 128-bit part of 256-bit vector and then
13579 /// inserting the result into the low part of a new 256-bit vector
13580 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13581   EVT VT = SVOp->getValueType(0);
13582   unsigned NumElems = VT.getVectorNumElements();
13583
13584   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13585   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13586     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13587         SVOp->getMaskElt(j) >= 0)
13588       return false;
13589
13590   return true;
13591 }
13592
13593 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13594 /// same as extracting the low 128-bit part of 256-bit vector and then
13595 /// inserting the result into the high part of a new 256-bit vector
13596 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13597   EVT VT = SVOp->getValueType(0);
13598   unsigned NumElems = VT.getVectorNumElements();
13599
13600   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13601   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13602     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13603         SVOp->getMaskElt(j) >= 0)
13604       return false;
13605
13606   return true;
13607 }
13608
13609 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13610 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13611                                         TargetLowering::DAGCombinerInfo &DCI,
13612                                         const X86Subtarget* Subtarget) {
13613   DebugLoc dl = N->getDebugLoc();
13614   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13615   SDValue V1 = SVOp->getOperand(0);
13616   SDValue V2 = SVOp->getOperand(1);
13617   EVT VT = SVOp->getValueType(0);
13618   unsigned NumElems = VT.getVectorNumElements();
13619
13620   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13621       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13622     //
13623     //                   0,0,0,...
13624     //                      |
13625     //    V      UNDEF    BUILD_VECTOR    UNDEF
13626     //     \      /           \           /
13627     //  CONCAT_VECTOR         CONCAT_VECTOR
13628     //         \                  /
13629     //          \                /
13630     //          RESULT: V + zero extended
13631     //
13632     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13633         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13634         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13635       return SDValue();
13636
13637     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13638       return SDValue();
13639
13640     // To match the shuffle mask, the first half of the mask should
13641     // be exactly the first vector, and all the rest a splat with the
13642     // first element of the second one.
13643     for (unsigned i = 0; i != NumElems/2; ++i)
13644       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13645           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13646         return SDValue();
13647
13648     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13649     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13650       if (Ld->hasNUsesOfValue(1, 0)) {
13651         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13652         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13653         SDValue ResNode =
13654           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13655                                   Ld->getMemoryVT(),
13656                                   Ld->getPointerInfo(),
13657                                   Ld->getAlignment(),
13658                                   false/*isVolatile*/, true/*ReadMem*/,
13659                                   false/*WriteMem*/);
13660         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13661       }
13662     }
13663
13664     // Emit a zeroed vector and insert the desired subvector on its
13665     // first half.
13666     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13667     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13668     return DCI.CombineTo(N, InsV);
13669   }
13670
13671   //===--------------------------------------------------------------------===//
13672   // Combine some shuffles into subvector extracts and inserts:
13673   //
13674
13675   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13676   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13677     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13678     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13679     return DCI.CombineTo(N, InsV);
13680   }
13681
13682   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13683   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13684     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13685     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13686     return DCI.CombineTo(N, InsV);
13687   }
13688
13689   return SDValue();
13690 }
13691
13692 /// PerformShuffleCombine - Performs several different shuffle combines.
13693 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13694                                      TargetLowering::DAGCombinerInfo &DCI,
13695                                      const X86Subtarget *Subtarget) {
13696   DebugLoc dl = N->getDebugLoc();
13697   EVT VT = N->getValueType(0);
13698
13699   // Don't create instructions with illegal types after legalize types has run.
13700   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13701   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13702     return SDValue();
13703
13704   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13705   if (Subtarget->hasAVX() && VT.is256BitVector() &&
13706       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13707     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13708
13709   // Only handle 128 wide vector from here on.
13710   if (!VT.is128BitVector())
13711     return SDValue();
13712
13713   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13714   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13715   // consecutive, non-overlapping, and in the right order.
13716   SmallVector<SDValue, 16> Elts;
13717   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13718     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13719
13720   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13721 }
13722
13723
13724 /// PerformTruncateCombine - Converts truncate operation to
13725 /// a sequence of vector shuffle operations.
13726 /// It is possible when we truncate 256-bit vector to 128-bit vector
13727 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13728                                       TargetLowering::DAGCombinerInfo &DCI,
13729                                       const X86Subtarget *Subtarget)  {
13730   if (!DCI.isBeforeLegalizeOps())
13731     return SDValue();
13732
13733   if (!Subtarget->hasAVX())
13734     return SDValue();
13735
13736   EVT VT = N->getValueType(0);
13737   SDValue Op = N->getOperand(0);
13738   EVT OpVT = Op.getValueType();
13739   DebugLoc dl = N->getDebugLoc();
13740
13741   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13742
13743     if (Subtarget->hasAVX2()) {
13744       // AVX2: v4i64 -> v4i32
13745
13746       // VPERMD
13747       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13748
13749       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13750       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13751                                 ShufMask);
13752
13753       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13754                          DAG.getIntPtrConstant(0));
13755     }
13756
13757     // AVX: v4i64 -> v4i32
13758     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13759                                DAG.getIntPtrConstant(0));
13760
13761     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13762                                DAG.getIntPtrConstant(2));
13763
13764     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13765     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13766
13767     // PSHUFD
13768     static const int ShufMask1[] = {0, 2, 0, 0};
13769
13770     SDValue Undef = DAG.getUNDEF(VT);
13771     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13772     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13773
13774     // MOVLHPS
13775     static const int ShufMask2[] = {0, 1, 4, 5};
13776
13777     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13778   }
13779
13780   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13781
13782     if (Subtarget->hasAVX2()) {
13783       // AVX2: v8i32 -> v8i16
13784
13785       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13786
13787       // PSHUFB
13788       SmallVector<SDValue,32> pshufbMask;
13789       for (unsigned i = 0; i < 2; ++i) {
13790         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13791         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13792         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13793         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13794         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13795         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13796         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13797         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13798         for (unsigned j = 0; j < 8; ++j)
13799           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13800       }
13801       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13802                                &pshufbMask[0], 32);
13803       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13804
13805       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13806
13807       static const int ShufMask[] = {0,  2,  -1,  -1};
13808       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13809                                 &ShufMask[0]);
13810
13811       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13812                        DAG.getIntPtrConstant(0));
13813
13814       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13815     }
13816
13817     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13818                                DAG.getIntPtrConstant(0));
13819
13820     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13821                                DAG.getIntPtrConstant(4));
13822
13823     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13824     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13825
13826     // PSHUFB
13827     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13828                                    -1, -1, -1, -1, -1, -1, -1, -1};
13829
13830     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13831     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13832     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13833
13834     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13835     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13836
13837     // MOVLHPS
13838     static const int ShufMask2[] = {0, 1, 4, 5};
13839
13840     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13841     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13842   }
13843
13844   return SDValue();
13845 }
13846
13847 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13848 /// specific shuffle of a load can be folded into a single element load.
13849 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13850 /// shuffles have been customed lowered so we need to handle those here.
13851 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13852                                          TargetLowering::DAGCombinerInfo &DCI) {
13853   if (DCI.isBeforeLegalizeOps())
13854     return SDValue();
13855
13856   SDValue InVec = N->getOperand(0);
13857   SDValue EltNo = N->getOperand(1);
13858
13859   if (!isa<ConstantSDNode>(EltNo))
13860     return SDValue();
13861
13862   EVT VT = InVec.getValueType();
13863
13864   bool HasShuffleIntoBitcast = false;
13865   if (InVec.getOpcode() == ISD::BITCAST) {
13866     // Don't duplicate a load with other uses.
13867     if (!InVec.hasOneUse())
13868       return SDValue();
13869     EVT BCVT = InVec.getOperand(0).getValueType();
13870     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13871       return SDValue();
13872     InVec = InVec.getOperand(0);
13873     HasShuffleIntoBitcast = true;
13874   }
13875
13876   if (!isTargetShuffle(InVec.getOpcode()))
13877     return SDValue();
13878
13879   // Don't duplicate a load with other uses.
13880   if (!InVec.hasOneUse())
13881     return SDValue();
13882
13883   SmallVector<int, 16> ShuffleMask;
13884   bool UnaryShuffle;
13885   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13886                             UnaryShuffle))
13887     return SDValue();
13888
13889   // Select the input vector, guarding against out of range extract vector.
13890   unsigned NumElems = VT.getVectorNumElements();
13891   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13892   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13893   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13894                                          : InVec.getOperand(1);
13895
13896   // If inputs to shuffle are the same for both ops, then allow 2 uses
13897   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13898
13899   if (LdNode.getOpcode() == ISD::BITCAST) {
13900     // Don't duplicate a load with other uses.
13901     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13902       return SDValue();
13903
13904     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13905     LdNode = LdNode.getOperand(0);
13906   }
13907
13908   if (!ISD::isNormalLoad(LdNode.getNode()))
13909     return SDValue();
13910
13911   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13912
13913   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13914     return SDValue();
13915
13916   if (HasShuffleIntoBitcast) {
13917     // If there's a bitcast before the shuffle, check if the load type and
13918     // alignment is valid.
13919     unsigned Align = LN0->getAlignment();
13920     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13921     unsigned NewAlign = TLI.getDataLayout()->
13922       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13923
13924     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13925       return SDValue();
13926   }
13927
13928   // All checks match so transform back to vector_shuffle so that DAG combiner
13929   // can finish the job
13930   DebugLoc dl = N->getDebugLoc();
13931
13932   // Create shuffle node taking into account the case that its a unary shuffle
13933   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13934   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13935                                  InVec.getOperand(0), Shuffle,
13936                                  &ShuffleMask[0]);
13937   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13938   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13939                      EltNo);
13940 }
13941
13942 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13943 /// generation and convert it from being a bunch of shuffles and extracts
13944 /// to a simple store and scalar loads to extract the elements.
13945 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13946                                          TargetLowering::DAGCombinerInfo &DCI) {
13947   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13948   if (NewOp.getNode())
13949     return NewOp;
13950
13951   SDValue InputVector = N->getOperand(0);
13952
13953   // Only operate on vectors of 4 elements, where the alternative shuffling
13954   // gets to be more expensive.
13955   if (InputVector.getValueType() != MVT::v4i32)
13956     return SDValue();
13957
13958   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13959   // single use which is a sign-extend or zero-extend, and all elements are
13960   // used.
13961   SmallVector<SDNode *, 4> Uses;
13962   unsigned ExtractedElements = 0;
13963   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13964        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13965     if (UI.getUse().getResNo() != InputVector.getResNo())
13966       return SDValue();
13967
13968     SDNode *Extract = *UI;
13969     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13970       return SDValue();
13971
13972     if (Extract->getValueType(0) != MVT::i32)
13973       return SDValue();
13974     if (!Extract->hasOneUse())
13975       return SDValue();
13976     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13977         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13978       return SDValue();
13979     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13980       return SDValue();
13981
13982     // Record which element was extracted.
13983     ExtractedElements |=
13984       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13985
13986     Uses.push_back(Extract);
13987   }
13988
13989   // If not all the elements were used, this may not be worthwhile.
13990   if (ExtractedElements != 15)
13991     return SDValue();
13992
13993   // Ok, we've now decided to do the transformation.
13994   DebugLoc dl = InputVector.getDebugLoc();
13995
13996   // Store the value to a temporary stack slot.
13997   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13998   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13999                             MachinePointerInfo(), false, false, 0);
14000
14001   // Replace each use (extract) with a load of the appropriate element.
14002   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14003        UE = Uses.end(); UI != UE; ++UI) {
14004     SDNode *Extract = *UI;
14005
14006     // cOMpute the element's address.
14007     SDValue Idx = Extract->getOperand(1);
14008     unsigned EltSize =
14009         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14010     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14011     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14012     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14013
14014     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14015                                      StackPtr, OffsetVal);
14016
14017     // Load the scalar.
14018     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14019                                      ScalarAddr, MachinePointerInfo(),
14020                                      false, false, false, 0);
14021
14022     // Replace the exact with the load.
14023     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14024   }
14025
14026   // The replacement was made in place; don't return anything.
14027   return SDValue();
14028 }
14029
14030 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14031 /// nodes.
14032 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14033                                     TargetLowering::DAGCombinerInfo &DCI,
14034                                     const X86Subtarget *Subtarget) {
14035   DebugLoc DL = N->getDebugLoc();
14036   SDValue Cond = N->getOperand(0);
14037   // Get the LHS/RHS of the select.
14038   SDValue LHS = N->getOperand(1);
14039   SDValue RHS = N->getOperand(2);
14040   EVT VT = LHS.getValueType();
14041
14042   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14043   // instructions match the semantics of the common C idiom x<y?x:y but not
14044   // x<=y?x:y, because of how they handle negative zero (which can be
14045   // ignored in unsafe-math mode).
14046   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14047       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14048       (Subtarget->hasSSE2() ||
14049        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14050     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14051
14052     unsigned Opcode = 0;
14053     // Check for x CC y ? x : y.
14054     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14055         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14056       switch (CC) {
14057       default: break;
14058       case ISD::SETULT:
14059         // Converting this to a min would handle NaNs incorrectly, and swapping
14060         // the operands would cause it to handle comparisons between positive
14061         // and negative zero incorrectly.
14062         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14063           if (!DAG.getTarget().Options.UnsafeFPMath &&
14064               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14065             break;
14066           std::swap(LHS, RHS);
14067         }
14068         Opcode = X86ISD::FMIN;
14069         break;
14070       case ISD::SETOLE:
14071         // Converting this to a min would handle comparisons between positive
14072         // and negative zero incorrectly.
14073         if (!DAG.getTarget().Options.UnsafeFPMath &&
14074             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14075           break;
14076         Opcode = X86ISD::FMIN;
14077         break;
14078       case ISD::SETULE:
14079         // Converting this to a min would handle both negative zeros and NaNs
14080         // incorrectly, but we can swap the operands to fix both.
14081         std::swap(LHS, RHS);
14082       case ISD::SETOLT:
14083       case ISD::SETLT:
14084       case ISD::SETLE:
14085         Opcode = X86ISD::FMIN;
14086         break;
14087
14088       case ISD::SETOGE:
14089         // Converting this to a max would handle comparisons between positive
14090         // and negative zero incorrectly.
14091         if (!DAG.getTarget().Options.UnsafeFPMath &&
14092             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14093           break;
14094         Opcode = X86ISD::FMAX;
14095         break;
14096       case ISD::SETUGT:
14097         // Converting this to a max would handle NaNs incorrectly, and swapping
14098         // the operands would cause it to handle comparisons between positive
14099         // and negative zero incorrectly.
14100         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14101           if (!DAG.getTarget().Options.UnsafeFPMath &&
14102               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14103             break;
14104           std::swap(LHS, RHS);
14105         }
14106         Opcode = X86ISD::FMAX;
14107         break;
14108       case ISD::SETUGE:
14109         // Converting this to a max would handle both negative zeros and NaNs
14110         // incorrectly, but we can swap the operands to fix both.
14111         std::swap(LHS, RHS);
14112       case ISD::SETOGT:
14113       case ISD::SETGT:
14114       case ISD::SETGE:
14115         Opcode = X86ISD::FMAX;
14116         break;
14117       }
14118     // Check for x CC y ? y : x -- a min/max with reversed arms.
14119     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14120                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14121       switch (CC) {
14122       default: break;
14123       case ISD::SETOGE:
14124         // Converting this to a min would handle comparisons between positive
14125         // and negative zero incorrectly, and swapping the operands would
14126         // cause it to handle NaNs incorrectly.
14127         if (!DAG.getTarget().Options.UnsafeFPMath &&
14128             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14129           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14130             break;
14131           std::swap(LHS, RHS);
14132         }
14133         Opcode = X86ISD::FMIN;
14134         break;
14135       case ISD::SETUGT:
14136         // Converting this to a min would handle NaNs incorrectly.
14137         if (!DAG.getTarget().Options.UnsafeFPMath &&
14138             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14139           break;
14140         Opcode = X86ISD::FMIN;
14141         break;
14142       case ISD::SETUGE:
14143         // Converting this to a min would handle both negative zeros and NaNs
14144         // incorrectly, but we can swap the operands to fix both.
14145         std::swap(LHS, RHS);
14146       case ISD::SETOGT:
14147       case ISD::SETGT:
14148       case ISD::SETGE:
14149         Opcode = X86ISD::FMIN;
14150         break;
14151
14152       case ISD::SETULT:
14153         // Converting this to a max would handle NaNs incorrectly.
14154         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14155           break;
14156         Opcode = X86ISD::FMAX;
14157         break;
14158       case ISD::SETOLE:
14159         // Converting this to a max would handle comparisons between positive
14160         // and negative zero incorrectly, and swapping the operands would
14161         // cause it to handle NaNs incorrectly.
14162         if (!DAG.getTarget().Options.UnsafeFPMath &&
14163             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14164           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14165             break;
14166           std::swap(LHS, RHS);
14167         }
14168         Opcode = X86ISD::FMAX;
14169         break;
14170       case ISD::SETULE:
14171         // Converting this to a max would handle both negative zeros and NaNs
14172         // incorrectly, but we can swap the operands to fix both.
14173         std::swap(LHS, RHS);
14174       case ISD::SETOLT:
14175       case ISD::SETLT:
14176       case ISD::SETLE:
14177         Opcode = X86ISD::FMAX;
14178         break;
14179       }
14180     }
14181
14182     if (Opcode)
14183       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14184   }
14185
14186   // If this is a select between two integer constants, try to do some
14187   // optimizations.
14188   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14189     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14190       // Don't do this for crazy integer types.
14191       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14192         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14193         // so that TrueC (the true value) is larger than FalseC.
14194         bool NeedsCondInvert = false;
14195
14196         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14197             // Efficiently invertible.
14198             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
14199              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
14200               isa<ConstantSDNode>(Cond.getOperand(1))))) {
14201           NeedsCondInvert = true;
14202           std::swap(TrueC, FalseC);
14203         }
14204
14205         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
14206         if (FalseC->getAPIntValue() == 0 &&
14207             TrueC->getAPIntValue().isPowerOf2()) {
14208           if (NeedsCondInvert) // Invert the condition if needed.
14209             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14210                                DAG.getConstant(1, Cond.getValueType()));
14211
14212           // Zero extend the condition if needed.
14213           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14214
14215           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14216           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14217                              DAG.getConstant(ShAmt, MVT::i8));
14218         }
14219
14220         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14221         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14222           if (NeedsCondInvert) // Invert the condition if needed.
14223             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14224                                DAG.getConstant(1, Cond.getValueType()));
14225
14226           // Zero extend the condition if needed.
14227           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14228                              FalseC->getValueType(0), Cond);
14229           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14230                              SDValue(FalseC, 0));
14231         }
14232
14233         // Optimize cases that will turn into an LEA instruction.  This requires
14234         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14235         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14236           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14237           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14238
14239           bool isFastMultiplier = false;
14240           if (Diff < 10) {
14241             switch ((unsigned char)Diff) {
14242               default: break;
14243               case 1:  // result = add base, cond
14244               case 2:  // result = lea base(    , cond*2)
14245               case 3:  // result = lea base(cond, cond*2)
14246               case 4:  // result = lea base(    , cond*4)
14247               case 5:  // result = lea base(cond, cond*4)
14248               case 8:  // result = lea base(    , cond*8)
14249               case 9:  // result = lea base(cond, cond*8)
14250                 isFastMultiplier = true;
14251                 break;
14252             }
14253           }
14254
14255           if (isFastMultiplier) {
14256             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14257             if (NeedsCondInvert) // Invert the condition if needed.
14258               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14259                                  DAG.getConstant(1, Cond.getValueType()));
14260
14261             // Zero extend the condition if needed.
14262             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14263                                Cond);
14264             // Scale the condition by the difference.
14265             if (Diff != 1)
14266               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14267                                  DAG.getConstant(Diff, Cond.getValueType()));
14268
14269             // Add the base if non-zero.
14270             if (FalseC->getAPIntValue() != 0)
14271               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14272                                  SDValue(FalseC, 0));
14273             return Cond;
14274           }
14275         }
14276       }
14277   }
14278
14279   // Canonicalize max and min:
14280   // (x > y) ? x : y -> (x >= y) ? x : y
14281   // (x < y) ? x : y -> (x <= y) ? x : y
14282   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14283   // the need for an extra compare
14284   // against zero. e.g.
14285   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14286   // subl   %esi, %edi
14287   // testl  %edi, %edi
14288   // movl   $0, %eax
14289   // cmovgl %edi, %eax
14290   // =>
14291   // xorl   %eax, %eax
14292   // subl   %esi, $edi
14293   // cmovsl %eax, %edi
14294   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14295       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14296       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14297     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14298     switch (CC) {
14299     default: break;
14300     case ISD::SETLT:
14301     case ISD::SETGT: {
14302       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14303       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14304                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14305       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14306     }
14307     }
14308   }
14309
14310   // If we know that this node is legal then we know that it is going to be
14311   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14312   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14313   // to simplify previous instructions.
14314   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14315   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14316       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14317     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14318
14319     // Don't optimize vector selects that map to mask-registers.
14320     if (BitWidth == 1)
14321       return SDValue();
14322
14323     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14324     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14325
14326     APInt KnownZero, KnownOne;
14327     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14328                                           DCI.isBeforeLegalizeOps());
14329     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14330         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14331       DCI.CommitTargetLoweringOpt(TLO);
14332   }
14333
14334   return SDValue();
14335 }
14336
14337 // Check whether a boolean test is testing a boolean value generated by
14338 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14339 // code.
14340 //
14341 // Simplify the following patterns:
14342 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14343 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14344 // to (Op EFLAGS Cond)
14345 //
14346 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14347 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14348 // to (Op EFLAGS !Cond)
14349 //
14350 // where Op could be BRCOND or CMOV.
14351 //
14352 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14353   // Quit if not CMP and SUB with its value result used.
14354   if (Cmp.getOpcode() != X86ISD::CMP &&
14355       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14356       return SDValue();
14357
14358   // Quit if not used as a boolean value.
14359   if (CC != X86::COND_E && CC != X86::COND_NE)
14360     return SDValue();
14361
14362   // Check CMP operands. One of them should be 0 or 1 and the other should be
14363   // an SetCC or extended from it.
14364   SDValue Op1 = Cmp.getOperand(0);
14365   SDValue Op2 = Cmp.getOperand(1);
14366
14367   SDValue SetCC;
14368   const ConstantSDNode* C = 0;
14369   bool needOppositeCond = (CC == X86::COND_E);
14370
14371   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14372     SetCC = Op2;
14373   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14374     SetCC = Op1;
14375   else // Quit if all operands are not constants.
14376     return SDValue();
14377
14378   if (C->getZExtValue() == 1)
14379     needOppositeCond = !needOppositeCond;
14380   else if (C->getZExtValue() != 0)
14381     // Quit if the constant is neither 0 or 1.
14382     return SDValue();
14383
14384   // Skip 'zext' node.
14385   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14386     SetCC = SetCC.getOperand(0);
14387
14388   switch (SetCC.getOpcode()) {
14389   case X86ISD::SETCC:
14390     // Set the condition code or opposite one if necessary.
14391     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14392     if (needOppositeCond)
14393       CC = X86::GetOppositeBranchCondition(CC);
14394     return SetCC.getOperand(1);
14395   case X86ISD::CMOV: {
14396     // Check whether false/true value has canonical one, i.e. 0 or 1.
14397     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14398     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14399     // Quit if true value is not a constant.
14400     if (!TVal)
14401       return SDValue();
14402     // Quit if false value is not a constant.
14403     if (!FVal) {
14404       // A special case for rdrand, where 0 is set if false cond is found.
14405       SDValue Op = SetCC.getOperand(0);
14406       if (Op.getOpcode() != X86ISD::RDRAND)
14407         return SDValue();
14408     }
14409     // Quit if false value is not the constant 0 or 1.
14410     bool FValIsFalse = true;
14411     if (FVal && FVal->getZExtValue() != 0) {
14412       if (FVal->getZExtValue() != 1)
14413         return SDValue();
14414       // If FVal is 1, opposite cond is needed.
14415       needOppositeCond = !needOppositeCond;
14416       FValIsFalse = false;
14417     }
14418     // Quit if TVal is not the constant opposite of FVal.
14419     if (FValIsFalse && TVal->getZExtValue() != 1)
14420       return SDValue();
14421     if (!FValIsFalse && TVal->getZExtValue() != 0)
14422       return SDValue();
14423     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14424     if (needOppositeCond)
14425       CC = X86::GetOppositeBranchCondition(CC);
14426     return SetCC.getOperand(3);
14427   }
14428   }
14429
14430   return SDValue();
14431 }
14432
14433 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14434 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14435                                   TargetLowering::DAGCombinerInfo &DCI,
14436                                   const X86Subtarget *Subtarget) {
14437   DebugLoc DL = N->getDebugLoc();
14438
14439   // If the flag operand isn't dead, don't touch this CMOV.
14440   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14441     return SDValue();
14442
14443   SDValue FalseOp = N->getOperand(0);
14444   SDValue TrueOp = N->getOperand(1);
14445   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14446   SDValue Cond = N->getOperand(3);
14447
14448   if (CC == X86::COND_E || CC == X86::COND_NE) {
14449     switch (Cond.getOpcode()) {
14450     default: break;
14451     case X86ISD::BSR:
14452     case X86ISD::BSF:
14453       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14454       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14455         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14456     }
14457   }
14458
14459   SDValue Flags;
14460
14461   Flags = checkBoolTestSetCCCombine(Cond, CC);
14462   if (Flags.getNode() &&
14463       // Extra check as FCMOV only supports a subset of X86 cond.
14464       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14465     SDValue Ops[] = { FalseOp, TrueOp,
14466                       DAG.getConstant(CC, MVT::i8), Flags };
14467     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14468                        Ops, array_lengthof(Ops));
14469   }
14470
14471   // If this is a select between two integer constants, try to do some
14472   // optimizations.  Note that the operands are ordered the opposite of SELECT
14473   // operands.
14474   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14475     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14476       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14477       // larger than FalseC (the false value).
14478       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14479         CC = X86::GetOppositeBranchCondition(CC);
14480         std::swap(TrueC, FalseC);
14481       }
14482
14483       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14484       // This is efficient for any integer data type (including i8/i16) and
14485       // shift amount.
14486       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14487         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14488                            DAG.getConstant(CC, MVT::i8), Cond);
14489
14490         // Zero extend the condition if needed.
14491         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14492
14493         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14494         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14495                            DAG.getConstant(ShAmt, MVT::i8));
14496         if (N->getNumValues() == 2)  // Dead flag value?
14497           return DCI.CombineTo(N, Cond, SDValue());
14498         return Cond;
14499       }
14500
14501       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14502       // for any integer data type, including i8/i16.
14503       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14504         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14505                            DAG.getConstant(CC, MVT::i8), Cond);
14506
14507         // Zero extend the condition if needed.
14508         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14509                            FalseC->getValueType(0), Cond);
14510         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14511                            SDValue(FalseC, 0));
14512
14513         if (N->getNumValues() == 2)  // Dead flag value?
14514           return DCI.CombineTo(N, Cond, SDValue());
14515         return Cond;
14516       }
14517
14518       // Optimize cases that will turn into an LEA instruction.  This requires
14519       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14520       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14521         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14522         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14523
14524         bool isFastMultiplier = false;
14525         if (Diff < 10) {
14526           switch ((unsigned char)Diff) {
14527           default: break;
14528           case 1:  // result = add base, cond
14529           case 2:  // result = lea base(    , cond*2)
14530           case 3:  // result = lea base(cond, cond*2)
14531           case 4:  // result = lea base(    , cond*4)
14532           case 5:  // result = lea base(cond, cond*4)
14533           case 8:  // result = lea base(    , cond*8)
14534           case 9:  // result = lea base(cond, cond*8)
14535             isFastMultiplier = true;
14536             break;
14537           }
14538         }
14539
14540         if (isFastMultiplier) {
14541           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14542           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14543                              DAG.getConstant(CC, MVT::i8), Cond);
14544           // Zero extend the condition if needed.
14545           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14546                              Cond);
14547           // Scale the condition by the difference.
14548           if (Diff != 1)
14549             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14550                                DAG.getConstant(Diff, Cond.getValueType()));
14551
14552           // Add the base if non-zero.
14553           if (FalseC->getAPIntValue() != 0)
14554             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14555                                SDValue(FalseC, 0));
14556           if (N->getNumValues() == 2)  // Dead flag value?
14557             return DCI.CombineTo(N, Cond, SDValue());
14558           return Cond;
14559         }
14560       }
14561     }
14562   }
14563   return SDValue();
14564 }
14565
14566
14567 /// PerformMulCombine - Optimize a single multiply with constant into two
14568 /// in order to implement it with two cheaper instructions, e.g.
14569 /// LEA + SHL, LEA + LEA.
14570 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14571                                  TargetLowering::DAGCombinerInfo &DCI) {
14572   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14573     return SDValue();
14574
14575   EVT VT = N->getValueType(0);
14576   if (VT != MVT::i64)
14577     return SDValue();
14578
14579   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14580   if (!C)
14581     return SDValue();
14582   uint64_t MulAmt = C->getZExtValue();
14583   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14584     return SDValue();
14585
14586   uint64_t MulAmt1 = 0;
14587   uint64_t MulAmt2 = 0;
14588   if ((MulAmt % 9) == 0) {
14589     MulAmt1 = 9;
14590     MulAmt2 = MulAmt / 9;
14591   } else if ((MulAmt % 5) == 0) {
14592     MulAmt1 = 5;
14593     MulAmt2 = MulAmt / 5;
14594   } else if ((MulAmt % 3) == 0) {
14595     MulAmt1 = 3;
14596     MulAmt2 = MulAmt / 3;
14597   }
14598   if (MulAmt2 &&
14599       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14600     DebugLoc DL = N->getDebugLoc();
14601
14602     if (isPowerOf2_64(MulAmt2) &&
14603         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14604       // If second multiplifer is pow2, issue it first. We want the multiply by
14605       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14606       // is an add.
14607       std::swap(MulAmt1, MulAmt2);
14608
14609     SDValue NewMul;
14610     if (isPowerOf2_64(MulAmt1))
14611       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14612                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14613     else
14614       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14615                            DAG.getConstant(MulAmt1, VT));
14616
14617     if (isPowerOf2_64(MulAmt2))
14618       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14619                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14620     else
14621       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14622                            DAG.getConstant(MulAmt2, VT));
14623
14624     // Do not add new nodes to DAG combiner worklist.
14625     DCI.CombineTo(N, NewMul, false);
14626   }
14627   return SDValue();
14628 }
14629
14630 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14631   SDValue N0 = N->getOperand(0);
14632   SDValue N1 = N->getOperand(1);
14633   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14634   EVT VT = N0.getValueType();
14635
14636   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14637   // since the result of setcc_c is all zero's or all ones.
14638   if (VT.isInteger() && !VT.isVector() &&
14639       N1C && N0.getOpcode() == ISD::AND &&
14640       N0.getOperand(1).getOpcode() == ISD::Constant) {
14641     SDValue N00 = N0.getOperand(0);
14642     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14643         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14644           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14645          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14646       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14647       APInt ShAmt = N1C->getAPIntValue();
14648       Mask = Mask.shl(ShAmt);
14649       if (Mask != 0)
14650         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14651                            N00, DAG.getConstant(Mask, VT));
14652     }
14653   }
14654
14655
14656   // Hardware support for vector shifts is sparse which makes us scalarize the
14657   // vector operations in many cases. Also, on sandybridge ADD is faster than
14658   // shl.
14659   // (shl V, 1) -> add V,V
14660   if (isSplatVector(N1.getNode())) {
14661     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14662     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14663     // We shift all of the values by one. In many cases we do not have
14664     // hardware support for this operation. This is better expressed as an ADD
14665     // of two values.
14666     if (N1C && (1 == N1C->getZExtValue())) {
14667       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14668     }
14669   }
14670
14671   return SDValue();
14672 }
14673
14674 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14675 ///                       when possible.
14676 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14677                                    TargetLowering::DAGCombinerInfo &DCI,
14678                                    const X86Subtarget *Subtarget) {
14679   EVT VT = N->getValueType(0);
14680   if (N->getOpcode() == ISD::SHL) {
14681     SDValue V = PerformSHLCombine(N, DAG);
14682     if (V.getNode()) return V;
14683   }
14684
14685   // On X86 with SSE2 support, we can transform this to a vector shift if
14686   // all elements are shifted by the same amount.  We can't do this in legalize
14687   // because the a constant vector is typically transformed to a constant pool
14688   // so we have no knowledge of the shift amount.
14689   if (!Subtarget->hasSSE2())
14690     return SDValue();
14691
14692   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14693       (!Subtarget->hasAVX2() ||
14694        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14695     return SDValue();
14696
14697   SDValue ShAmtOp = N->getOperand(1);
14698   EVT EltVT = VT.getVectorElementType();
14699   DebugLoc DL = N->getDebugLoc();
14700   SDValue BaseShAmt = SDValue();
14701   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14702     unsigned NumElts = VT.getVectorNumElements();
14703     unsigned i = 0;
14704     for (; i != NumElts; ++i) {
14705       SDValue Arg = ShAmtOp.getOperand(i);
14706       if (Arg.getOpcode() == ISD::UNDEF) continue;
14707       BaseShAmt = Arg;
14708       break;
14709     }
14710     // Handle the case where the build_vector is all undef
14711     // FIXME: Should DAG allow this?
14712     if (i == NumElts)
14713       return SDValue();
14714
14715     for (; i != NumElts; ++i) {
14716       SDValue Arg = ShAmtOp.getOperand(i);
14717       if (Arg.getOpcode() == ISD::UNDEF) continue;
14718       if (Arg != BaseShAmt) {
14719         return SDValue();
14720       }
14721     }
14722   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14723              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14724     SDValue InVec = ShAmtOp.getOperand(0);
14725     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14726       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14727       unsigned i = 0;
14728       for (; i != NumElts; ++i) {
14729         SDValue Arg = InVec.getOperand(i);
14730         if (Arg.getOpcode() == ISD::UNDEF) continue;
14731         BaseShAmt = Arg;
14732         break;
14733       }
14734     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14735        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14736          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14737          if (C->getZExtValue() == SplatIdx)
14738            BaseShAmt = InVec.getOperand(1);
14739        }
14740     }
14741     if (BaseShAmt.getNode() == 0) {
14742       // Don't create instructions with illegal types after legalize
14743       // types has run.
14744       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14745           !DCI.isBeforeLegalize())
14746         return SDValue();
14747
14748       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14749                               DAG.getIntPtrConstant(0));
14750     }
14751   } else
14752     return SDValue();
14753
14754   // The shift amount is an i32.
14755   if (EltVT.bitsGT(MVT::i32))
14756     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14757   else if (EltVT.bitsLT(MVT::i32))
14758     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14759
14760   // The shift amount is identical so we can do a vector shift.
14761   SDValue  ValOp = N->getOperand(0);
14762   switch (N->getOpcode()) {
14763   default:
14764     llvm_unreachable("Unknown shift opcode!");
14765   case ISD::SHL:
14766     switch (VT.getSimpleVT().SimpleTy) {
14767     default: return SDValue();
14768     case MVT::v2i64:
14769     case MVT::v4i32:
14770     case MVT::v8i16:
14771     case MVT::v4i64:
14772     case MVT::v8i32:
14773     case MVT::v16i16:
14774       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14775     }
14776   case ISD::SRA:
14777     switch (VT.getSimpleVT().SimpleTy) {
14778     default: return SDValue();
14779     case MVT::v4i32:
14780     case MVT::v8i16:
14781     case MVT::v8i32:
14782     case MVT::v16i16:
14783       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14784     }
14785   case ISD::SRL:
14786     switch (VT.getSimpleVT().SimpleTy) {
14787     default: return SDValue();
14788     case MVT::v2i64:
14789     case MVT::v4i32:
14790     case MVT::v8i16:
14791     case MVT::v4i64:
14792     case MVT::v8i32:
14793     case MVT::v16i16:
14794       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14795     }
14796   }
14797 }
14798
14799
14800 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14801 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14802 // and friends.  Likewise for OR -> CMPNEQSS.
14803 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14804                             TargetLowering::DAGCombinerInfo &DCI,
14805                             const X86Subtarget *Subtarget) {
14806   unsigned opcode;
14807
14808   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14809   // we're requiring SSE2 for both.
14810   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14811     SDValue N0 = N->getOperand(0);
14812     SDValue N1 = N->getOperand(1);
14813     SDValue CMP0 = N0->getOperand(1);
14814     SDValue CMP1 = N1->getOperand(1);
14815     DebugLoc DL = N->getDebugLoc();
14816
14817     // The SETCCs should both refer to the same CMP.
14818     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14819       return SDValue();
14820
14821     SDValue CMP00 = CMP0->getOperand(0);
14822     SDValue CMP01 = CMP0->getOperand(1);
14823     EVT     VT    = CMP00.getValueType();
14824
14825     if (VT == MVT::f32 || VT == MVT::f64) {
14826       bool ExpectingFlags = false;
14827       // Check for any users that want flags:
14828       for (SDNode::use_iterator UI = N->use_begin(),
14829              UE = N->use_end();
14830            !ExpectingFlags && UI != UE; ++UI)
14831         switch (UI->getOpcode()) {
14832         default:
14833         case ISD::BR_CC:
14834         case ISD::BRCOND:
14835         case ISD::SELECT:
14836           ExpectingFlags = true;
14837           break;
14838         case ISD::CopyToReg:
14839         case ISD::SIGN_EXTEND:
14840         case ISD::ZERO_EXTEND:
14841         case ISD::ANY_EXTEND:
14842           break;
14843         }
14844
14845       if (!ExpectingFlags) {
14846         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14847         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14848
14849         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14850           X86::CondCode tmp = cc0;
14851           cc0 = cc1;
14852           cc1 = tmp;
14853         }
14854
14855         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14856             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14857           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14858           X86ISD::NodeType NTOperator = is64BitFP ?
14859             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14860           // FIXME: need symbolic constants for these magic numbers.
14861           // See X86ATTInstPrinter.cpp:printSSECC().
14862           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14863           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14864                                               DAG.getConstant(x86cc, MVT::i8));
14865           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14866                                               OnesOrZeroesF);
14867           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14868                                       DAG.getConstant(1, MVT::i32));
14869           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14870           return OneBitOfTruth;
14871         }
14872       }
14873     }
14874   }
14875   return SDValue();
14876 }
14877
14878 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14879 /// so it can be folded inside ANDNP.
14880 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14881   EVT VT = N->getValueType(0);
14882
14883   // Match direct AllOnes for 128 and 256-bit vectors
14884   if (ISD::isBuildVectorAllOnes(N))
14885     return true;
14886
14887   // Look through a bit convert.
14888   if (N->getOpcode() == ISD::BITCAST)
14889     N = N->getOperand(0).getNode();
14890
14891   // Sometimes the operand may come from a insert_subvector building a 256-bit
14892   // allones vector
14893   if (VT.is256BitVector() &&
14894       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14895     SDValue V1 = N->getOperand(0);
14896     SDValue V2 = N->getOperand(1);
14897
14898     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14899         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14900         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14901         ISD::isBuildVectorAllOnes(V2.getNode()))
14902       return true;
14903   }
14904
14905   return false;
14906 }
14907
14908 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14909                                  TargetLowering::DAGCombinerInfo &DCI,
14910                                  const X86Subtarget *Subtarget) {
14911   if (DCI.isBeforeLegalizeOps())
14912     return SDValue();
14913
14914   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14915   if (R.getNode())
14916     return R;
14917
14918   EVT VT = N->getValueType(0);
14919
14920   // Create ANDN, BLSI, and BLSR instructions
14921   // BLSI is X & (-X)
14922   // BLSR is X & (X-1)
14923   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14924     SDValue N0 = N->getOperand(0);
14925     SDValue N1 = N->getOperand(1);
14926     DebugLoc DL = N->getDebugLoc();
14927
14928     // Check LHS for not
14929     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14930       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14931     // Check RHS for not
14932     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14933       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14934
14935     // Check LHS for neg
14936     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14937         isZero(N0.getOperand(0)))
14938       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14939
14940     // Check RHS for neg
14941     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14942         isZero(N1.getOperand(0)))
14943       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14944
14945     // Check LHS for X-1
14946     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14947         isAllOnes(N0.getOperand(1)))
14948       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14949
14950     // Check RHS for X-1
14951     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14952         isAllOnes(N1.getOperand(1)))
14953       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14954
14955     return SDValue();
14956   }
14957
14958   // Want to form ANDNP nodes:
14959   // 1) In the hopes of then easily combining them with OR and AND nodes
14960   //    to form PBLEND/PSIGN.
14961   // 2) To match ANDN packed intrinsics
14962   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14963     return SDValue();
14964
14965   SDValue N0 = N->getOperand(0);
14966   SDValue N1 = N->getOperand(1);
14967   DebugLoc DL = N->getDebugLoc();
14968
14969   // Check LHS for vnot
14970   if (N0.getOpcode() == ISD::XOR &&
14971       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14972       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14973     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14974
14975   // Check RHS for vnot
14976   if (N1.getOpcode() == ISD::XOR &&
14977       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14978       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14979     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14980
14981   return SDValue();
14982 }
14983
14984 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14985                                 TargetLowering::DAGCombinerInfo &DCI,
14986                                 const X86Subtarget *Subtarget) {
14987   if (DCI.isBeforeLegalizeOps())
14988     return SDValue();
14989
14990   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14991   if (R.getNode())
14992     return R;
14993
14994   EVT VT = N->getValueType(0);
14995
14996   SDValue N0 = N->getOperand(0);
14997   SDValue N1 = N->getOperand(1);
14998
14999   // look for psign/blend
15000   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15001     if (!Subtarget->hasSSSE3() ||
15002         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15003       return SDValue();
15004
15005     // Canonicalize pandn to RHS
15006     if (N0.getOpcode() == X86ISD::ANDNP)
15007       std::swap(N0, N1);
15008     // or (and (m, y), (pandn m, x))
15009     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15010       SDValue Mask = N1.getOperand(0);
15011       SDValue X    = N1.getOperand(1);
15012       SDValue Y;
15013       if (N0.getOperand(0) == Mask)
15014         Y = N0.getOperand(1);
15015       if (N0.getOperand(1) == Mask)
15016         Y = N0.getOperand(0);
15017
15018       // Check to see if the mask appeared in both the AND and ANDNP and
15019       if (!Y.getNode())
15020         return SDValue();
15021
15022       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15023       // Look through mask bitcast.
15024       if (Mask.getOpcode() == ISD::BITCAST)
15025         Mask = Mask.getOperand(0);
15026       if (X.getOpcode() == ISD::BITCAST)
15027         X = X.getOperand(0);
15028       if (Y.getOpcode() == ISD::BITCAST)
15029         Y = Y.getOperand(0);
15030
15031       EVT MaskVT = Mask.getValueType();
15032
15033       // Validate that the Mask operand is a vector sra node.
15034       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15035       // there is no psrai.b
15036       if (Mask.getOpcode() != X86ISD::VSRAI)
15037         return SDValue();
15038
15039       // Check that the SRA is all signbits.
15040       SDValue SraC = Mask.getOperand(1);
15041       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
15042       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15043       if ((SraAmt + 1) != EltBits)
15044         return SDValue();
15045
15046       DebugLoc DL = N->getDebugLoc();
15047
15048       // Now we know we at least have a plendvb with the mask val.  See if
15049       // we can form a psignb/w/d.
15050       // psign = x.type == y.type == mask.type && y = sub(0, x);
15051       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15052           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15053           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15054         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15055                "Unsupported VT for PSIGN");
15056         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15057         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15058       }
15059       // PBLENDVB only available on SSE 4.1
15060       if (!Subtarget->hasSSE41())
15061         return SDValue();
15062
15063       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15064
15065       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15066       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15067       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15068       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15069       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15070     }
15071   }
15072
15073   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15074     return SDValue();
15075
15076   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15077   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15078     std::swap(N0, N1);
15079   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15080     return SDValue();
15081   if (!N0.hasOneUse() || !N1.hasOneUse())
15082     return SDValue();
15083
15084   SDValue ShAmt0 = N0.getOperand(1);
15085   if (ShAmt0.getValueType() != MVT::i8)
15086     return SDValue();
15087   SDValue ShAmt1 = N1.getOperand(1);
15088   if (ShAmt1.getValueType() != MVT::i8)
15089     return SDValue();
15090   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15091     ShAmt0 = ShAmt0.getOperand(0);
15092   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15093     ShAmt1 = ShAmt1.getOperand(0);
15094
15095   DebugLoc DL = N->getDebugLoc();
15096   unsigned Opc = X86ISD::SHLD;
15097   SDValue Op0 = N0.getOperand(0);
15098   SDValue Op1 = N1.getOperand(0);
15099   if (ShAmt0.getOpcode() == ISD::SUB) {
15100     Opc = X86ISD::SHRD;
15101     std::swap(Op0, Op1);
15102     std::swap(ShAmt0, ShAmt1);
15103   }
15104
15105   unsigned Bits = VT.getSizeInBits();
15106   if (ShAmt1.getOpcode() == ISD::SUB) {
15107     SDValue Sum = ShAmt1.getOperand(0);
15108     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15109       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15110       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15111         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15112       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15113         return DAG.getNode(Opc, DL, VT,
15114                            Op0, Op1,
15115                            DAG.getNode(ISD::TRUNCATE, DL,
15116                                        MVT::i8, ShAmt0));
15117     }
15118   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15119     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15120     if (ShAmt0C &&
15121         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15122       return DAG.getNode(Opc, DL, VT,
15123                          N0.getOperand(0), N1.getOperand(0),
15124                          DAG.getNode(ISD::TRUNCATE, DL,
15125                                        MVT::i8, ShAmt0));
15126   }
15127
15128   return SDValue();
15129 }
15130
15131 // Generate NEG and CMOV for integer abs.
15132 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15133   EVT VT = N->getValueType(0);
15134
15135   // Since X86 does not have CMOV for 8-bit integer, we don't convert
15136   // 8-bit integer abs to NEG and CMOV.
15137   if (VT.isInteger() && VT.getSizeInBits() == 8)
15138     return SDValue();
15139
15140   SDValue N0 = N->getOperand(0);
15141   SDValue N1 = N->getOperand(1);
15142   DebugLoc DL = N->getDebugLoc();
15143
15144   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15145   // and change it to SUB and CMOV.
15146   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15147       N0.getOpcode() == ISD::ADD &&
15148       N0.getOperand(1) == N1 &&
15149       N1.getOpcode() == ISD::SRA &&
15150       N1.getOperand(0) == N0.getOperand(0))
15151     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15152       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15153         // Generate SUB & CMOV.
15154         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15155                                   DAG.getConstant(0, VT), N0.getOperand(0));
15156
15157         SDValue Ops[] = { N0.getOperand(0), Neg,
15158                           DAG.getConstant(X86::COND_GE, MVT::i8),
15159                           SDValue(Neg.getNode(), 1) };
15160         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15161                            Ops, array_lengthof(Ops));
15162       }
15163   return SDValue();
15164 }
15165
15166 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15167 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15168                                  TargetLowering::DAGCombinerInfo &DCI,
15169                                  const X86Subtarget *Subtarget) {
15170   if (DCI.isBeforeLegalizeOps())
15171     return SDValue();
15172
15173   if (Subtarget->hasCMov()) {
15174     SDValue RV = performIntegerAbsCombine(N, DAG);
15175     if (RV.getNode())
15176       return RV;
15177   }
15178
15179   // Try forming BMI if it is available.
15180   if (!Subtarget->hasBMI())
15181     return SDValue();
15182
15183   EVT VT = N->getValueType(0);
15184
15185   if (VT != MVT::i32 && VT != MVT::i64)
15186     return SDValue();
15187
15188   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15189
15190   // Create BLSMSK instructions by finding X ^ (X-1)
15191   SDValue N0 = N->getOperand(0);
15192   SDValue N1 = N->getOperand(1);
15193   DebugLoc DL = N->getDebugLoc();
15194
15195   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15196       isAllOnes(N0.getOperand(1)))
15197     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15198
15199   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15200       isAllOnes(N1.getOperand(1)))
15201     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15202
15203   return SDValue();
15204 }
15205
15206 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15207 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15208                                   TargetLowering::DAGCombinerInfo &DCI,
15209                                   const X86Subtarget *Subtarget) {
15210   LoadSDNode *Ld = cast<LoadSDNode>(N);
15211   EVT RegVT = Ld->getValueType(0);
15212   EVT MemVT = Ld->getMemoryVT();
15213   DebugLoc dl = Ld->getDebugLoc();
15214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15215
15216   ISD::LoadExtType Ext = Ld->getExtensionType();
15217
15218   // If this is a vector EXT Load then attempt to optimize it using a
15219   // shuffle. We need SSE4 for the shuffles.
15220   // TODO: It is possible to support ZExt by zeroing the undef values
15221   // during the shuffle phase or after the shuffle.
15222   if (RegVT.isVector() && RegVT.isInteger() &&
15223       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
15224     assert(MemVT != RegVT && "Cannot extend to the same type");
15225     assert(MemVT.isVector() && "Must load a vector from memory");
15226
15227     unsigned NumElems = RegVT.getVectorNumElements();
15228     unsigned RegSz = RegVT.getSizeInBits();
15229     unsigned MemSz = MemVT.getSizeInBits();
15230     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15231
15232     // All sizes must be a power of two.
15233     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15234       return SDValue();
15235
15236     // Attempt to load the original value using scalar loads.
15237     // Find the largest scalar type that divides the total loaded size.
15238     MVT SclrLoadTy = MVT::i8;
15239     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15240          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15241       MVT Tp = (MVT::SimpleValueType)tp;
15242       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15243         SclrLoadTy = Tp;
15244       }
15245     }
15246
15247     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15248     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15249         (64 <= MemSz))
15250       SclrLoadTy = MVT::f64;
15251
15252     // Calculate the number of scalar loads that we need to perform
15253     // in order to load our vector from memory.
15254     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15255
15256     // Represent our vector as a sequence of elements which are the
15257     // largest scalar that we can load.
15258     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15259       RegSz/SclrLoadTy.getSizeInBits());
15260
15261     // Represent the data using the same element type that is stored in
15262     // memory. In practice, we ''widen'' MemVT.
15263     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15264                                   RegSz/MemVT.getScalarType().getSizeInBits());
15265
15266     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15267       "Invalid vector type");
15268
15269     // We can't shuffle using an illegal type.
15270     if (!TLI.isTypeLegal(WideVecVT))
15271       return SDValue();
15272
15273     SmallVector<SDValue, 8> Chains;
15274     SDValue Ptr = Ld->getBasePtr();
15275     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15276                                         TLI.getPointerTy());
15277     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15278
15279     for (unsigned i = 0; i < NumLoads; ++i) {
15280       // Perform a single load.
15281       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15282                                        Ptr, Ld->getPointerInfo(),
15283                                        Ld->isVolatile(), Ld->isNonTemporal(),
15284                                        Ld->isInvariant(), Ld->getAlignment());
15285       Chains.push_back(ScalarLoad.getValue(1));
15286       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15287       // another round of DAGCombining.
15288       if (i == 0)
15289         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15290       else
15291         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15292                           ScalarLoad, DAG.getIntPtrConstant(i));
15293
15294       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15295     }
15296
15297     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15298                                Chains.size());
15299
15300     // Bitcast the loaded value to a vector of the original element type, in
15301     // the size of the target vector type.
15302     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15303     unsigned SizeRatio = RegSz/MemSz;
15304
15305     // Redistribute the loaded elements into the different locations.
15306     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15307     for (unsigned i = 0; i != NumElems; ++i)
15308       ShuffleVec[i*SizeRatio] = i;
15309
15310     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15311                                          DAG.getUNDEF(WideVecVT),
15312                                          &ShuffleVec[0]);
15313
15314     // Bitcast to the requested type.
15315     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15316     // Replace the original load with the new sequence
15317     // and return the new chain.
15318     return DCI.CombineTo(N, Shuff, TF, true);
15319   }
15320
15321   return SDValue();
15322 }
15323
15324 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15325 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15326                                    const X86Subtarget *Subtarget) {
15327   StoreSDNode *St = cast<StoreSDNode>(N);
15328   EVT VT = St->getValue().getValueType();
15329   EVT StVT = St->getMemoryVT();
15330   DebugLoc dl = St->getDebugLoc();
15331   SDValue StoredVal = St->getOperand(1);
15332   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15333
15334   // If we are saving a concatenation of two XMM registers, perform two stores.
15335   // On Sandy Bridge, 256-bit memory operations are executed by two
15336   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15337   // memory  operation.
15338   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15339       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15340       StoredVal.getNumOperands() == 2) {
15341     SDValue Value0 = StoredVal.getOperand(0);
15342     SDValue Value1 = StoredVal.getOperand(1);
15343
15344     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15345     SDValue Ptr0 = St->getBasePtr();
15346     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15347
15348     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15349                                 St->getPointerInfo(), St->isVolatile(),
15350                                 St->isNonTemporal(), St->getAlignment());
15351     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15352                                 St->getPointerInfo(), St->isVolatile(),
15353                                 St->isNonTemporal(), St->getAlignment());
15354     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15355   }
15356
15357   // Optimize trunc store (of multiple scalars) to shuffle and store.
15358   // First, pack all of the elements in one place. Next, store to memory
15359   // in fewer chunks.
15360   if (St->isTruncatingStore() && VT.isVector()) {
15361     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15362     unsigned NumElems = VT.getVectorNumElements();
15363     assert(StVT != VT && "Cannot truncate to the same type");
15364     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15365     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15366
15367     // From, To sizes and ElemCount must be pow of two
15368     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15369     // We are going to use the original vector elt for storing.
15370     // Accumulated smaller vector elements must be a multiple of the store size.
15371     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15372
15373     unsigned SizeRatio  = FromSz / ToSz;
15374
15375     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15376
15377     // Create a type on which we perform the shuffle
15378     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15379             StVT.getScalarType(), NumElems*SizeRatio);
15380
15381     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15382
15383     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15384     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15385     for (unsigned i = 0; i != NumElems; ++i)
15386       ShuffleVec[i] = i * SizeRatio;
15387
15388     // Can't shuffle using an illegal type.
15389     if (!TLI.isTypeLegal(WideVecVT))
15390       return SDValue();
15391
15392     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15393                                          DAG.getUNDEF(WideVecVT),
15394                                          &ShuffleVec[0]);
15395     // At this point all of the data is stored at the bottom of the
15396     // register. We now need to save it to mem.
15397
15398     // Find the largest store unit
15399     MVT StoreType = MVT::i8;
15400     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15401          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15402       MVT Tp = (MVT::SimpleValueType)tp;
15403       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15404         StoreType = Tp;
15405     }
15406
15407     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15408     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15409         (64 <= NumElems * ToSz))
15410       StoreType = MVT::f64;
15411
15412     // Bitcast the original vector into a vector of store-size units
15413     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15414             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15415     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15416     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15417     SmallVector<SDValue, 8> Chains;
15418     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15419                                         TLI.getPointerTy());
15420     SDValue Ptr = St->getBasePtr();
15421
15422     // Perform one or more big stores into memory.
15423     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15424       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15425                                    StoreType, ShuffWide,
15426                                    DAG.getIntPtrConstant(i));
15427       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15428                                 St->getPointerInfo(), St->isVolatile(),
15429                                 St->isNonTemporal(), St->getAlignment());
15430       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15431       Chains.push_back(Ch);
15432     }
15433
15434     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15435                                Chains.size());
15436   }
15437
15438
15439   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15440   // the FP state in cases where an emms may be missing.
15441   // A preferable solution to the general problem is to figure out the right
15442   // places to insert EMMS.  This qualifies as a quick hack.
15443
15444   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15445   if (VT.getSizeInBits() != 64)
15446     return SDValue();
15447
15448   const Function *F = DAG.getMachineFunction().getFunction();
15449   bool NoImplicitFloatOps = F->getFnAttributes().
15450     hasAttribute(Attributes::NoImplicitFloat);
15451   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15452                      && Subtarget->hasSSE2();
15453   if ((VT.isVector() ||
15454        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15455       isa<LoadSDNode>(St->getValue()) &&
15456       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15457       St->getChain().hasOneUse() && !St->isVolatile()) {
15458     SDNode* LdVal = St->getValue().getNode();
15459     LoadSDNode *Ld = 0;
15460     int TokenFactorIndex = -1;
15461     SmallVector<SDValue, 8> Ops;
15462     SDNode* ChainVal = St->getChain().getNode();
15463     // Must be a store of a load.  We currently handle two cases:  the load
15464     // is a direct child, and it's under an intervening TokenFactor.  It is
15465     // possible to dig deeper under nested TokenFactors.
15466     if (ChainVal == LdVal)
15467       Ld = cast<LoadSDNode>(St->getChain());
15468     else if (St->getValue().hasOneUse() &&
15469              ChainVal->getOpcode() == ISD::TokenFactor) {
15470       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15471         if (ChainVal->getOperand(i).getNode() == LdVal) {
15472           TokenFactorIndex = i;
15473           Ld = cast<LoadSDNode>(St->getValue());
15474         } else
15475           Ops.push_back(ChainVal->getOperand(i));
15476       }
15477     }
15478
15479     if (!Ld || !ISD::isNormalLoad(Ld))
15480       return SDValue();
15481
15482     // If this is not the MMX case, i.e. we are just turning i64 load/store
15483     // into f64 load/store, avoid the transformation if there are multiple
15484     // uses of the loaded value.
15485     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15486       return SDValue();
15487
15488     DebugLoc LdDL = Ld->getDebugLoc();
15489     DebugLoc StDL = N->getDebugLoc();
15490     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15491     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15492     // pair instead.
15493     if (Subtarget->is64Bit() || F64IsLegal) {
15494       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15495       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15496                                   Ld->getPointerInfo(), Ld->isVolatile(),
15497                                   Ld->isNonTemporal(), Ld->isInvariant(),
15498                                   Ld->getAlignment());
15499       SDValue NewChain = NewLd.getValue(1);
15500       if (TokenFactorIndex != -1) {
15501         Ops.push_back(NewChain);
15502         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15503                                Ops.size());
15504       }
15505       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15506                           St->getPointerInfo(),
15507                           St->isVolatile(), St->isNonTemporal(),
15508                           St->getAlignment());
15509     }
15510
15511     // Otherwise, lower to two pairs of 32-bit loads / stores.
15512     SDValue LoAddr = Ld->getBasePtr();
15513     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15514                                  DAG.getConstant(4, MVT::i32));
15515
15516     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15517                                Ld->getPointerInfo(),
15518                                Ld->isVolatile(), Ld->isNonTemporal(),
15519                                Ld->isInvariant(), Ld->getAlignment());
15520     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15521                                Ld->getPointerInfo().getWithOffset(4),
15522                                Ld->isVolatile(), Ld->isNonTemporal(),
15523                                Ld->isInvariant(),
15524                                MinAlign(Ld->getAlignment(), 4));
15525
15526     SDValue NewChain = LoLd.getValue(1);
15527     if (TokenFactorIndex != -1) {
15528       Ops.push_back(LoLd);
15529       Ops.push_back(HiLd);
15530       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15531                              Ops.size());
15532     }
15533
15534     LoAddr = St->getBasePtr();
15535     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15536                          DAG.getConstant(4, MVT::i32));
15537
15538     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15539                                 St->getPointerInfo(),
15540                                 St->isVolatile(), St->isNonTemporal(),
15541                                 St->getAlignment());
15542     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15543                                 St->getPointerInfo().getWithOffset(4),
15544                                 St->isVolatile(),
15545                                 St->isNonTemporal(),
15546                                 MinAlign(St->getAlignment(), 4));
15547     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15548   }
15549   return SDValue();
15550 }
15551
15552 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15553 /// and return the operands for the horizontal operation in LHS and RHS.  A
15554 /// horizontal operation performs the binary operation on successive elements
15555 /// of its first operand, then on successive elements of its second operand,
15556 /// returning the resulting values in a vector.  For example, if
15557 ///   A = < float a0, float a1, float a2, float a3 >
15558 /// and
15559 ///   B = < float b0, float b1, float b2, float b3 >
15560 /// then the result of doing a horizontal operation on A and B is
15561 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15562 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15563 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15564 /// set to A, RHS to B, and the routine returns 'true'.
15565 /// Note that the binary operation should have the property that if one of the
15566 /// operands is UNDEF then the result is UNDEF.
15567 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15568   // Look for the following pattern: if
15569   //   A = < float a0, float a1, float a2, float a3 >
15570   //   B = < float b0, float b1, float b2, float b3 >
15571   // and
15572   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15573   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15574   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15575   // which is A horizontal-op B.
15576
15577   // At least one of the operands should be a vector shuffle.
15578   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15579       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15580     return false;
15581
15582   EVT VT = LHS.getValueType();
15583
15584   assert((VT.is128BitVector() || VT.is256BitVector()) &&
15585          "Unsupported vector type for horizontal add/sub");
15586
15587   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15588   // operate independently on 128-bit lanes.
15589   unsigned NumElts = VT.getVectorNumElements();
15590   unsigned NumLanes = VT.getSizeInBits()/128;
15591   unsigned NumLaneElts = NumElts / NumLanes;
15592   assert((NumLaneElts % 2 == 0) &&
15593          "Vector type should have an even number of elements in each lane");
15594   unsigned HalfLaneElts = NumLaneElts/2;
15595
15596   // View LHS in the form
15597   //   LHS = VECTOR_SHUFFLE A, B, LMask
15598   // If LHS is not a shuffle then pretend it is the shuffle
15599   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15600   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15601   // type VT.
15602   SDValue A, B;
15603   SmallVector<int, 16> LMask(NumElts);
15604   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15605     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15606       A = LHS.getOperand(0);
15607     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15608       B = LHS.getOperand(1);
15609     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15610     std::copy(Mask.begin(), Mask.end(), LMask.begin());
15611   } else {
15612     if (LHS.getOpcode() != ISD::UNDEF)
15613       A = LHS;
15614     for (unsigned i = 0; i != NumElts; ++i)
15615       LMask[i] = i;
15616   }
15617
15618   // Likewise, view RHS in the form
15619   //   RHS = VECTOR_SHUFFLE C, D, RMask
15620   SDValue C, D;
15621   SmallVector<int, 16> RMask(NumElts);
15622   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15623     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15624       C = RHS.getOperand(0);
15625     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15626       D = RHS.getOperand(1);
15627     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15628     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15629   } else {
15630     if (RHS.getOpcode() != ISD::UNDEF)
15631       C = RHS;
15632     for (unsigned i = 0; i != NumElts; ++i)
15633       RMask[i] = i;
15634   }
15635
15636   // Check that the shuffles are both shuffling the same vectors.
15637   if (!(A == C && B == D) && !(A == D && B == C))
15638     return false;
15639
15640   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15641   if (!A.getNode() && !B.getNode())
15642     return false;
15643
15644   // If A and B occur in reverse order in RHS, then "swap" them (which means
15645   // rewriting the mask).
15646   if (A != C)
15647     CommuteVectorShuffleMask(RMask, NumElts);
15648
15649   // At this point LHS and RHS are equivalent to
15650   //   LHS = VECTOR_SHUFFLE A, B, LMask
15651   //   RHS = VECTOR_SHUFFLE A, B, RMask
15652   // Check that the masks correspond to performing a horizontal operation.
15653   for (unsigned i = 0; i != NumElts; ++i) {
15654     int LIdx = LMask[i], RIdx = RMask[i];
15655
15656     // Ignore any UNDEF components.
15657     if (LIdx < 0 || RIdx < 0 ||
15658         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15659         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15660       continue;
15661
15662     // Check that successive elements are being operated on.  If not, this is
15663     // not a horizontal operation.
15664     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15665     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15666     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15667     if (!(LIdx == Index && RIdx == Index + 1) &&
15668         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15669       return false;
15670   }
15671
15672   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15673   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15674   return true;
15675 }
15676
15677 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15678 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15679                                   const X86Subtarget *Subtarget) {
15680   EVT VT = N->getValueType(0);
15681   SDValue LHS = N->getOperand(0);
15682   SDValue RHS = N->getOperand(1);
15683
15684   // Try to synthesize horizontal adds from adds of shuffles.
15685   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15686        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15687       isHorizontalBinOp(LHS, RHS, true))
15688     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15689   return SDValue();
15690 }
15691
15692 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15693 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15694                                   const X86Subtarget *Subtarget) {
15695   EVT VT = N->getValueType(0);
15696   SDValue LHS = N->getOperand(0);
15697   SDValue RHS = N->getOperand(1);
15698
15699   // Try to synthesize horizontal subs from subs of shuffles.
15700   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15701        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15702       isHorizontalBinOp(LHS, RHS, false))
15703     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15704   return SDValue();
15705 }
15706
15707 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15708 /// X86ISD::FXOR nodes.
15709 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15710   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15711   // F[X]OR(0.0, x) -> x
15712   // F[X]OR(x, 0.0) -> x
15713   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15714     if (C->getValueAPF().isPosZero())
15715       return N->getOperand(1);
15716   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15717     if (C->getValueAPF().isPosZero())
15718       return N->getOperand(0);
15719   return SDValue();
15720 }
15721
15722 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15723 /// X86ISD::FMAX nodes.
15724 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15725   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15726
15727   // Only perform optimizations if UnsafeMath is used.
15728   if (!DAG.getTarget().Options.UnsafeFPMath)
15729     return SDValue();
15730
15731   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15732   // into FMINC and FMAXC, which are Commutative operations.
15733   unsigned NewOp = 0;
15734   switch (N->getOpcode()) {
15735     default: llvm_unreachable("unknown opcode");
15736     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
15737     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
15738   }
15739
15740   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15741                      N->getOperand(0), N->getOperand(1));
15742 }
15743
15744
15745 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15746 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15747   // FAND(0.0, x) -> 0.0
15748   // FAND(x, 0.0) -> 0.0
15749   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15750     if (C->getValueAPF().isPosZero())
15751       return N->getOperand(0);
15752   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15753     if (C->getValueAPF().isPosZero())
15754       return N->getOperand(1);
15755   return SDValue();
15756 }
15757
15758 static SDValue PerformBTCombine(SDNode *N,
15759                                 SelectionDAG &DAG,
15760                                 TargetLowering::DAGCombinerInfo &DCI) {
15761   // BT ignores high bits in the bit index operand.
15762   SDValue Op1 = N->getOperand(1);
15763   if (Op1.hasOneUse()) {
15764     unsigned BitWidth = Op1.getValueSizeInBits();
15765     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15766     APInt KnownZero, KnownOne;
15767     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15768                                           !DCI.isBeforeLegalizeOps());
15769     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15770     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15771         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15772       DCI.CommitTargetLoweringOpt(TLO);
15773   }
15774   return SDValue();
15775 }
15776
15777 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15778   SDValue Op = N->getOperand(0);
15779   if (Op.getOpcode() == ISD::BITCAST)
15780     Op = Op.getOperand(0);
15781   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15782   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15783       VT.getVectorElementType().getSizeInBits() ==
15784       OpVT.getVectorElementType().getSizeInBits()) {
15785     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15786   }
15787   return SDValue();
15788 }
15789
15790 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15791                                   TargetLowering::DAGCombinerInfo &DCI,
15792                                   const X86Subtarget *Subtarget) {
15793   if (!DCI.isBeforeLegalizeOps())
15794     return SDValue();
15795
15796   if (!Subtarget->hasAVX())
15797     return SDValue();
15798
15799   EVT VT = N->getValueType(0);
15800   SDValue Op = N->getOperand(0);
15801   EVT OpVT = Op.getValueType();
15802   DebugLoc dl = N->getDebugLoc();
15803
15804   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15805       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15806
15807     if (Subtarget->hasAVX2())
15808       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15809
15810     // Optimize vectors in AVX mode
15811     // Sign extend  v8i16 to v8i32 and
15812     //              v4i32 to v4i64
15813     //
15814     // Divide input vector into two parts
15815     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15816     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15817     // concat the vectors to original VT
15818
15819     unsigned NumElems = OpVT.getVectorNumElements();
15820     SDValue Undef = DAG.getUNDEF(OpVT);
15821
15822     SmallVector<int,8> ShufMask1(NumElems, -1);
15823     for (unsigned i = 0; i != NumElems/2; ++i)
15824       ShufMask1[i] = i;
15825
15826     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15827
15828     SmallVector<int,8> ShufMask2(NumElems, -1);
15829     for (unsigned i = 0; i != NumElems/2; ++i)
15830       ShufMask2[i] = i + NumElems/2;
15831
15832     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15833
15834     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15835                                   VT.getVectorNumElements()/2);
15836
15837     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15838     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15839
15840     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15841   }
15842   return SDValue();
15843 }
15844
15845 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15846                                  const X86Subtarget* Subtarget) {
15847   DebugLoc dl = N->getDebugLoc();
15848   EVT VT = N->getValueType(0);
15849
15850   // Let legalize expand this if it isn't a legal type yet.
15851   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15852     return SDValue();
15853
15854   EVT ScalarVT = VT.getScalarType();
15855   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15856       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15857     return SDValue();
15858
15859   SDValue A = N->getOperand(0);
15860   SDValue B = N->getOperand(1);
15861   SDValue C = N->getOperand(2);
15862
15863   bool NegA = (A.getOpcode() == ISD::FNEG);
15864   bool NegB = (B.getOpcode() == ISD::FNEG);
15865   bool NegC = (C.getOpcode() == ISD::FNEG);
15866
15867   // Negative multiplication when NegA xor NegB
15868   bool NegMul = (NegA != NegB);
15869   if (NegA)
15870     A = A.getOperand(0);
15871   if (NegB)
15872     B = B.getOperand(0);
15873   if (NegC)
15874     C = C.getOperand(0);
15875
15876   unsigned Opcode;
15877   if (!NegMul)
15878     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15879   else
15880     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15881
15882   return DAG.getNode(Opcode, dl, VT, A, B, C);
15883 }
15884
15885 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15886                                   TargetLowering::DAGCombinerInfo &DCI,
15887                                   const X86Subtarget *Subtarget) {
15888   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15889   //           (and (i32 x86isd::setcc_carry), 1)
15890   // This eliminates the zext. This transformation is necessary because
15891   // ISD::SETCC is always legalized to i8.
15892   DebugLoc dl = N->getDebugLoc();
15893   SDValue N0 = N->getOperand(0);
15894   EVT VT = N->getValueType(0);
15895   EVT OpVT = N0.getValueType();
15896
15897   if (N0.getOpcode() == ISD::AND &&
15898       N0.hasOneUse() &&
15899       N0.getOperand(0).hasOneUse()) {
15900     SDValue N00 = N0.getOperand(0);
15901     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15902       return SDValue();
15903     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15904     if (!C || C->getZExtValue() != 1)
15905       return SDValue();
15906     return DAG.getNode(ISD::AND, dl, VT,
15907                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15908                                    N00.getOperand(0), N00.getOperand(1)),
15909                        DAG.getConstant(1, VT));
15910   }
15911
15912   // Optimize vectors in AVX mode:
15913   //
15914   //   v8i16 -> v8i32
15915   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15916   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15917   //   Concat upper and lower parts.
15918   //
15919   //   v4i32 -> v4i64
15920   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15921   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15922   //   Concat upper and lower parts.
15923   //
15924   if (!DCI.isBeforeLegalizeOps())
15925     return SDValue();
15926
15927   if (!Subtarget->hasAVX())
15928     return SDValue();
15929
15930   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15931       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15932
15933     if (Subtarget->hasAVX2())
15934       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15935
15936     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15937     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15938     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15939
15940     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15941                                VT.getVectorNumElements()/2);
15942
15943     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15944     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15945
15946     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15947   }
15948
15949   return SDValue();
15950 }
15951
15952 // Optimize x == -y --> x+y == 0
15953 //          x != -y --> x+y != 0
15954 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15955   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15956   SDValue LHS = N->getOperand(0);
15957   SDValue RHS = N->getOperand(1);
15958
15959   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15960     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15961       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15962         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15963                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15964         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15965                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15966       }
15967   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15968     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15969       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15970         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15971                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15972         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15973                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15974       }
15975   return SDValue();
15976 }
15977
15978 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15979 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15980                                    TargetLowering::DAGCombinerInfo &DCI,
15981                                    const X86Subtarget *Subtarget) {
15982   DebugLoc DL = N->getDebugLoc();
15983   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15984   SDValue EFLAGS = N->getOperand(1);
15985
15986   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15987   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15988   // cases.
15989   if (CC == X86::COND_B)
15990     return DAG.getNode(ISD::AND, DL, MVT::i8,
15991                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15992                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
15993                        DAG.getConstant(1, MVT::i8));
15994
15995   SDValue Flags;
15996
15997   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15998   if (Flags.getNode()) {
15999     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16000     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16001   }
16002
16003   return SDValue();
16004 }
16005
16006 // Optimize branch condition evaluation.
16007 //
16008 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16009                                     TargetLowering::DAGCombinerInfo &DCI,
16010                                     const X86Subtarget *Subtarget) {
16011   DebugLoc DL = N->getDebugLoc();
16012   SDValue Chain = N->getOperand(0);
16013   SDValue Dest = N->getOperand(1);
16014   SDValue EFLAGS = N->getOperand(3);
16015   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16016
16017   SDValue Flags;
16018
16019   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16020   if (Flags.getNode()) {
16021     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16022     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16023                        Flags);
16024   }
16025
16026   return SDValue();
16027 }
16028
16029 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
16030   SDValue Op0 = N->getOperand(0);
16031   EVT InVT = Op0->getValueType(0);
16032
16033   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
16034   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16035     DebugLoc dl = N->getDebugLoc();
16036     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16037     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
16038     // Notice that we use SINT_TO_FP because we know that the high bits
16039     // are zero and SINT_TO_FP is better supported by the hardware.
16040     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16041   }
16042
16043   return SDValue();
16044 }
16045
16046 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16047                                         const X86TargetLowering *XTLI) {
16048   SDValue Op0 = N->getOperand(0);
16049   EVT InVT = Op0->getValueType(0);
16050
16051   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16052   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16053     DebugLoc dl = N->getDebugLoc();
16054     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16055     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16056     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16057   }
16058
16059   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16060   // a 32-bit target where SSE doesn't support i64->FP operations.
16061   if (Op0.getOpcode() == ISD::LOAD) {
16062     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16063     EVT VT = Ld->getValueType(0);
16064     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16065         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16066         !XTLI->getSubtarget()->is64Bit() &&
16067         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16068       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16069                                           Ld->getChain(), Op0, DAG);
16070       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16071       return FILDChain;
16072     }
16073   }
16074   return SDValue();
16075 }
16076
16077 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
16078   EVT VT = N->getValueType(0);
16079
16080   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
16081   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
16082     DebugLoc dl = N->getDebugLoc();
16083     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16084     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
16085     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
16086   }
16087
16088   return SDValue();
16089 }
16090
16091 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16092 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16093                                  X86TargetLowering::DAGCombinerInfo &DCI) {
16094   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16095   // the result is either zero or one (depending on the input carry bit).
16096   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16097   if (X86::isZeroNode(N->getOperand(0)) &&
16098       X86::isZeroNode(N->getOperand(1)) &&
16099       // We don't have a good way to replace an EFLAGS use, so only do this when
16100       // dead right now.
16101       SDValue(N, 1).use_empty()) {
16102     DebugLoc DL = N->getDebugLoc();
16103     EVT VT = N->getValueType(0);
16104     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16105     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16106                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16107                                            DAG.getConstant(X86::COND_B,MVT::i8),
16108                                            N->getOperand(2)),
16109                                DAG.getConstant(1, VT));
16110     return DCI.CombineTo(N, Res1, CarryOut);
16111   }
16112
16113   return SDValue();
16114 }
16115
16116 // fold (add Y, (sete  X, 0)) -> adc  0, Y
16117 //      (add Y, (setne X, 0)) -> sbb -1, Y
16118 //      (sub (sete  X, 0), Y) -> sbb  0, Y
16119 //      (sub (setne X, 0), Y) -> adc -1, Y
16120 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16121   DebugLoc DL = N->getDebugLoc();
16122
16123   // Look through ZExts.
16124   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16125   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16126     return SDValue();
16127
16128   SDValue SetCC = Ext.getOperand(0);
16129   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16130     return SDValue();
16131
16132   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16133   if (CC != X86::COND_E && CC != X86::COND_NE)
16134     return SDValue();
16135
16136   SDValue Cmp = SetCC.getOperand(1);
16137   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16138       !X86::isZeroNode(Cmp.getOperand(1)) ||
16139       !Cmp.getOperand(0).getValueType().isInteger())
16140     return SDValue();
16141
16142   SDValue CmpOp0 = Cmp.getOperand(0);
16143   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16144                                DAG.getConstant(1, CmpOp0.getValueType()));
16145
16146   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16147   if (CC == X86::COND_NE)
16148     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16149                        DL, OtherVal.getValueType(), OtherVal,
16150                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16151   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16152                      DL, OtherVal.getValueType(), OtherVal,
16153                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16154 }
16155
16156 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16157 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16158                                  const X86Subtarget *Subtarget) {
16159   EVT VT = N->getValueType(0);
16160   SDValue Op0 = N->getOperand(0);
16161   SDValue Op1 = N->getOperand(1);
16162
16163   // Try to synthesize horizontal adds from adds of shuffles.
16164   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16165        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16166       isHorizontalBinOp(Op0, Op1, true))
16167     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16168
16169   return OptimizeConditionalInDecrement(N, DAG);
16170 }
16171
16172 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16173                                  const X86Subtarget *Subtarget) {
16174   SDValue Op0 = N->getOperand(0);
16175   SDValue Op1 = N->getOperand(1);
16176
16177   // X86 can't encode an immediate LHS of a sub. See if we can push the
16178   // negation into a preceding instruction.
16179   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16180     // If the RHS of the sub is a XOR with one use and a constant, invert the
16181     // immediate. Then add one to the LHS of the sub so we can turn
16182     // X-Y -> X+~Y+1, saving one register.
16183     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16184         isa<ConstantSDNode>(Op1.getOperand(1))) {
16185       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16186       EVT VT = Op0.getValueType();
16187       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16188                                    Op1.getOperand(0),
16189                                    DAG.getConstant(~XorC, VT));
16190       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16191                          DAG.getConstant(C->getAPIntValue()+1, VT));
16192     }
16193   }
16194
16195   // Try to synthesize horizontal adds from adds of shuffles.
16196   EVT VT = N->getValueType(0);
16197   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16198        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16199       isHorizontalBinOp(Op0, Op1, true))
16200     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16201
16202   return OptimizeConditionalInDecrement(N, DAG);
16203 }
16204
16205 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16206                                              DAGCombinerInfo &DCI) const {
16207   SelectionDAG &DAG = DCI.DAG;
16208   switch (N->getOpcode()) {
16209   default: break;
16210   case ISD::EXTRACT_VECTOR_ELT:
16211     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16212   case ISD::VSELECT:
16213   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16214   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16215   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16216   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16217   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16218   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16219   case ISD::SHL:
16220   case ISD::SRA:
16221   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16222   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16223   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16224   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16225   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16226   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16227   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16228   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16229   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
16230   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16231   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16232   case X86ISD::FXOR:
16233   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16234   case X86ISD::FMIN:
16235   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16236   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16237   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16238   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16239   case ISD::ANY_EXTEND:
16240   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16241   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16242   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16243   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16244   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16245   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16246   case X86ISD::SHUFP:       // Handle all target specific shuffles
16247   case X86ISD::PALIGN:
16248   case X86ISD::UNPCKH:
16249   case X86ISD::UNPCKL:
16250   case X86ISD::MOVHLPS:
16251   case X86ISD::MOVLHPS:
16252   case X86ISD::PSHUFD:
16253   case X86ISD::PSHUFHW:
16254   case X86ISD::PSHUFLW:
16255   case X86ISD::MOVSS:
16256   case X86ISD::MOVSD:
16257   case X86ISD::VPERMILP:
16258   case X86ISD::VPERM2X128:
16259   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16260   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16261   }
16262
16263   return SDValue();
16264 }
16265
16266 /// isTypeDesirableForOp - Return true if the target has native support for
16267 /// the specified value type and it is 'desirable' to use the type for the
16268 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16269 /// instruction encodings are longer and some i16 instructions are slow.
16270 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16271   if (!isTypeLegal(VT))
16272     return false;
16273   if (VT != MVT::i16)
16274     return true;
16275
16276   switch (Opc) {
16277   default:
16278     return true;
16279   case ISD::LOAD:
16280   case ISD::SIGN_EXTEND:
16281   case ISD::ZERO_EXTEND:
16282   case ISD::ANY_EXTEND:
16283   case ISD::SHL:
16284   case ISD::SRL:
16285   case ISD::SUB:
16286   case ISD::ADD:
16287   case ISD::MUL:
16288   case ISD::AND:
16289   case ISD::OR:
16290   case ISD::XOR:
16291     return false;
16292   }
16293 }
16294
16295 /// IsDesirableToPromoteOp - This method query the target whether it is
16296 /// beneficial for dag combiner to promote the specified node. If true, it
16297 /// should return the desired promotion type by reference.
16298 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16299   EVT VT = Op.getValueType();
16300   if (VT != MVT::i16)
16301     return false;
16302
16303   bool Promote = false;
16304   bool Commute = false;
16305   switch (Op.getOpcode()) {
16306   default: break;
16307   case ISD::LOAD: {
16308     LoadSDNode *LD = cast<LoadSDNode>(Op);
16309     // If the non-extending load has a single use and it's not live out, then it
16310     // might be folded.
16311     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16312                                                      Op.hasOneUse()*/) {
16313       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16314              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16315         // The only case where we'd want to promote LOAD (rather then it being
16316         // promoted as an operand is when it's only use is liveout.
16317         if (UI->getOpcode() != ISD::CopyToReg)
16318           return false;
16319       }
16320     }
16321     Promote = true;
16322     break;
16323   }
16324   case ISD::SIGN_EXTEND:
16325   case ISD::ZERO_EXTEND:
16326   case ISD::ANY_EXTEND:
16327     Promote = true;
16328     break;
16329   case ISD::SHL:
16330   case ISD::SRL: {
16331     SDValue N0 = Op.getOperand(0);
16332     // Look out for (store (shl (load), x)).
16333     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16334       return false;
16335     Promote = true;
16336     break;
16337   }
16338   case ISD::ADD:
16339   case ISD::MUL:
16340   case ISD::AND:
16341   case ISD::OR:
16342   case ISD::XOR:
16343     Commute = true;
16344     // fallthrough
16345   case ISD::SUB: {
16346     SDValue N0 = Op.getOperand(0);
16347     SDValue N1 = Op.getOperand(1);
16348     if (!Commute && MayFoldLoad(N1))
16349       return false;
16350     // Avoid disabling potential load folding opportunities.
16351     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16352       return false;
16353     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16354       return false;
16355     Promote = true;
16356   }
16357   }
16358
16359   PVT = MVT::i32;
16360   return Promote;
16361 }
16362
16363 //===----------------------------------------------------------------------===//
16364 //                           X86 Inline Assembly Support
16365 //===----------------------------------------------------------------------===//
16366
16367 namespace {
16368   // Helper to match a string separated by whitespace.
16369   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16370     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16371
16372     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16373       StringRef piece(*args[i]);
16374       if (!s.startswith(piece)) // Check if the piece matches.
16375         return false;
16376
16377       s = s.substr(piece.size());
16378       StringRef::size_type pos = s.find_first_not_of(" \t");
16379       if (pos == 0) // We matched a prefix.
16380         return false;
16381
16382       s = s.substr(pos);
16383     }
16384
16385     return s.empty();
16386   }
16387   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16388 }
16389
16390 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16391   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16392
16393   std::string AsmStr = IA->getAsmString();
16394
16395   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16396   if (!Ty || Ty->getBitWidth() % 16 != 0)
16397     return false;
16398
16399   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16400   SmallVector<StringRef, 4> AsmPieces;
16401   SplitString(AsmStr, AsmPieces, ";\n");
16402
16403   switch (AsmPieces.size()) {
16404   default: return false;
16405   case 1:
16406     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16407     // we will turn this bswap into something that will be lowered to logical
16408     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16409     // lower so don't worry about this.
16410     // bswap $0
16411     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16412         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16413         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16414         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16415         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16416         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16417       // No need to check constraints, nothing other than the equivalent of
16418       // "=r,0" would be valid here.
16419       return IntrinsicLowering::LowerToByteSwap(CI);
16420     }
16421
16422     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16423     if (CI->getType()->isIntegerTy(16) &&
16424         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16425         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16426          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16427       AsmPieces.clear();
16428       const std::string &ConstraintsStr = IA->getConstraintString();
16429       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16430       std::sort(AsmPieces.begin(), AsmPieces.end());
16431       if (AsmPieces.size() == 4 &&
16432           AsmPieces[0] == "~{cc}" &&
16433           AsmPieces[1] == "~{dirflag}" &&
16434           AsmPieces[2] == "~{flags}" &&
16435           AsmPieces[3] == "~{fpsr}")
16436       return IntrinsicLowering::LowerToByteSwap(CI);
16437     }
16438     break;
16439   case 3:
16440     if (CI->getType()->isIntegerTy(32) &&
16441         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16442         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16443         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16444         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16445       AsmPieces.clear();
16446       const std::string &ConstraintsStr = IA->getConstraintString();
16447       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16448       std::sort(AsmPieces.begin(), AsmPieces.end());
16449       if (AsmPieces.size() == 4 &&
16450           AsmPieces[0] == "~{cc}" &&
16451           AsmPieces[1] == "~{dirflag}" &&
16452           AsmPieces[2] == "~{flags}" &&
16453           AsmPieces[3] == "~{fpsr}")
16454         return IntrinsicLowering::LowerToByteSwap(CI);
16455     }
16456
16457     if (CI->getType()->isIntegerTy(64)) {
16458       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16459       if (Constraints.size() >= 2 &&
16460           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16461           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16462         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16463         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16464             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16465             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16466           return IntrinsicLowering::LowerToByteSwap(CI);
16467       }
16468     }
16469     break;
16470   }
16471   return false;
16472 }
16473
16474
16475
16476 /// getConstraintType - Given a constraint letter, return the type of
16477 /// constraint it is for this target.
16478 X86TargetLowering::ConstraintType
16479 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16480   if (Constraint.size() == 1) {
16481     switch (Constraint[0]) {
16482     case 'R':
16483     case 'q':
16484     case 'Q':
16485     case 'f':
16486     case 't':
16487     case 'u':
16488     case 'y':
16489     case 'x':
16490     case 'Y':
16491     case 'l':
16492       return C_RegisterClass;
16493     case 'a':
16494     case 'b':
16495     case 'c':
16496     case 'd':
16497     case 'S':
16498     case 'D':
16499     case 'A':
16500       return C_Register;
16501     case 'I':
16502     case 'J':
16503     case 'K':
16504     case 'L':
16505     case 'M':
16506     case 'N':
16507     case 'G':
16508     case 'C':
16509     case 'e':
16510     case 'Z':
16511       return C_Other;
16512     default:
16513       break;
16514     }
16515   }
16516   return TargetLowering::getConstraintType(Constraint);
16517 }
16518
16519 /// Examine constraint type and operand type and determine a weight value.
16520 /// This object must already have been set up with the operand type
16521 /// and the current alternative constraint selected.
16522 TargetLowering::ConstraintWeight
16523   X86TargetLowering::getSingleConstraintMatchWeight(
16524     AsmOperandInfo &info, const char *constraint) const {
16525   ConstraintWeight weight = CW_Invalid;
16526   Value *CallOperandVal = info.CallOperandVal;
16527     // If we don't have a value, we can't do a match,
16528     // but allow it at the lowest weight.
16529   if (CallOperandVal == NULL)
16530     return CW_Default;
16531   Type *type = CallOperandVal->getType();
16532   // Look at the constraint type.
16533   switch (*constraint) {
16534   default:
16535     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16536   case 'R':
16537   case 'q':
16538   case 'Q':
16539   case 'a':
16540   case 'b':
16541   case 'c':
16542   case 'd':
16543   case 'S':
16544   case 'D':
16545   case 'A':
16546     if (CallOperandVal->getType()->isIntegerTy())
16547       weight = CW_SpecificReg;
16548     break;
16549   case 'f':
16550   case 't':
16551   case 'u':
16552       if (type->isFloatingPointTy())
16553         weight = CW_SpecificReg;
16554       break;
16555   case 'y':
16556       if (type->isX86_MMXTy() && Subtarget->hasMMX())
16557         weight = CW_SpecificReg;
16558       break;
16559   case 'x':
16560   case 'Y':
16561     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16562         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16563       weight = CW_Register;
16564     break;
16565   case 'I':
16566     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16567       if (C->getZExtValue() <= 31)
16568         weight = CW_Constant;
16569     }
16570     break;
16571   case 'J':
16572     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16573       if (C->getZExtValue() <= 63)
16574         weight = CW_Constant;
16575     }
16576     break;
16577   case 'K':
16578     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16579       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16580         weight = CW_Constant;
16581     }
16582     break;
16583   case 'L':
16584     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16585       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16586         weight = CW_Constant;
16587     }
16588     break;
16589   case 'M':
16590     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16591       if (C->getZExtValue() <= 3)
16592         weight = CW_Constant;
16593     }
16594     break;
16595   case 'N':
16596     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16597       if (C->getZExtValue() <= 0xff)
16598         weight = CW_Constant;
16599     }
16600     break;
16601   case 'G':
16602   case 'C':
16603     if (dyn_cast<ConstantFP>(CallOperandVal)) {
16604       weight = CW_Constant;
16605     }
16606     break;
16607   case 'e':
16608     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16609       if ((C->getSExtValue() >= -0x80000000LL) &&
16610           (C->getSExtValue() <= 0x7fffffffLL))
16611         weight = CW_Constant;
16612     }
16613     break;
16614   case 'Z':
16615     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16616       if (C->getZExtValue() <= 0xffffffff)
16617         weight = CW_Constant;
16618     }
16619     break;
16620   }
16621   return weight;
16622 }
16623
16624 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16625 /// with another that has more specific requirements based on the type of the
16626 /// corresponding operand.
16627 const char *X86TargetLowering::
16628 LowerXConstraint(EVT ConstraintVT) const {
16629   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16630   // 'f' like normal targets.
16631   if (ConstraintVT.isFloatingPoint()) {
16632     if (Subtarget->hasSSE2())
16633       return "Y";
16634     if (Subtarget->hasSSE1())
16635       return "x";
16636   }
16637
16638   return TargetLowering::LowerXConstraint(ConstraintVT);
16639 }
16640
16641 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16642 /// vector.  If it is invalid, don't add anything to Ops.
16643 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16644                                                      std::string &Constraint,
16645                                                      std::vector<SDValue>&Ops,
16646                                                      SelectionDAG &DAG) const {
16647   SDValue Result(0, 0);
16648
16649   // Only support length 1 constraints for now.
16650   if (Constraint.length() > 1) return;
16651
16652   char ConstraintLetter = Constraint[0];
16653   switch (ConstraintLetter) {
16654   default: break;
16655   case 'I':
16656     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16657       if (C->getZExtValue() <= 31) {
16658         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16659         break;
16660       }
16661     }
16662     return;
16663   case 'J':
16664     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16665       if (C->getZExtValue() <= 63) {
16666         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16667         break;
16668       }
16669     }
16670     return;
16671   case 'K':
16672     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16673       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16674         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16675         break;
16676       }
16677     }
16678     return;
16679   case 'N':
16680     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16681       if (C->getZExtValue() <= 255) {
16682         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16683         break;
16684       }
16685     }
16686     return;
16687   case 'e': {
16688     // 32-bit signed value
16689     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16690       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16691                                            C->getSExtValue())) {
16692         // Widen to 64 bits here to get it sign extended.
16693         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16694         break;
16695       }
16696     // FIXME gcc accepts some relocatable values here too, but only in certain
16697     // memory models; it's complicated.
16698     }
16699     return;
16700   }
16701   case 'Z': {
16702     // 32-bit unsigned value
16703     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16704       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16705                                            C->getZExtValue())) {
16706         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16707         break;
16708       }
16709     }
16710     // FIXME gcc accepts some relocatable values here too, but only in certain
16711     // memory models; it's complicated.
16712     return;
16713   }
16714   case 'i': {
16715     // Literal immediates are always ok.
16716     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16717       // Widen to 64 bits here to get it sign extended.
16718       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16719       break;
16720     }
16721
16722     // In any sort of PIC mode addresses need to be computed at runtime by
16723     // adding in a register or some sort of table lookup.  These can't
16724     // be used as immediates.
16725     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16726       return;
16727
16728     // If we are in non-pic codegen mode, we allow the address of a global (with
16729     // an optional displacement) to be used with 'i'.
16730     GlobalAddressSDNode *GA = 0;
16731     int64_t Offset = 0;
16732
16733     // Match either (GA), (GA+C), (GA+C1+C2), etc.
16734     while (1) {
16735       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16736         Offset += GA->getOffset();
16737         break;
16738       } else if (Op.getOpcode() == ISD::ADD) {
16739         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16740           Offset += C->getZExtValue();
16741           Op = Op.getOperand(0);
16742           continue;
16743         }
16744       } else if (Op.getOpcode() == ISD::SUB) {
16745         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16746           Offset += -C->getZExtValue();
16747           Op = Op.getOperand(0);
16748           continue;
16749         }
16750       }
16751
16752       // Otherwise, this isn't something we can handle, reject it.
16753       return;
16754     }
16755
16756     const GlobalValue *GV = GA->getGlobal();
16757     // If we require an extra load to get this address, as in PIC mode, we
16758     // can't accept it.
16759     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16760                                                         getTargetMachine())))
16761       return;
16762
16763     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16764                                         GA->getValueType(0), Offset);
16765     break;
16766   }
16767   }
16768
16769   if (Result.getNode()) {
16770     Ops.push_back(Result);
16771     return;
16772   }
16773   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16774 }
16775
16776 std::pair<unsigned, const TargetRegisterClass*>
16777 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16778                                                 EVT VT) const {
16779   // First, see if this is a constraint that directly corresponds to an LLVM
16780   // register class.
16781   if (Constraint.size() == 1) {
16782     // GCC Constraint Letters
16783     switch (Constraint[0]) {
16784     default: break;
16785       // TODO: Slight differences here in allocation order and leaving
16786       // RIP in the class. Do they matter any more here than they do
16787       // in the normal allocation?
16788     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16789       if (Subtarget->is64Bit()) {
16790         if (VT == MVT::i32 || VT == MVT::f32)
16791           return std::make_pair(0U, &X86::GR32RegClass);
16792         if (VT == MVT::i16)
16793           return std::make_pair(0U, &X86::GR16RegClass);
16794         if (VT == MVT::i8 || VT == MVT::i1)
16795           return std::make_pair(0U, &X86::GR8RegClass);
16796         if (VT == MVT::i64 || VT == MVT::f64)
16797           return std::make_pair(0U, &X86::GR64RegClass);
16798         break;
16799       }
16800       // 32-bit fallthrough
16801     case 'Q':   // Q_REGS
16802       if (VT == MVT::i32 || VT == MVT::f32)
16803         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16804       if (VT == MVT::i16)
16805         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16806       if (VT == MVT::i8 || VT == MVT::i1)
16807         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16808       if (VT == MVT::i64)
16809         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16810       break;
16811     case 'r':   // GENERAL_REGS
16812     case 'l':   // INDEX_REGS
16813       if (VT == MVT::i8 || VT == MVT::i1)
16814         return std::make_pair(0U, &X86::GR8RegClass);
16815       if (VT == MVT::i16)
16816         return std::make_pair(0U, &X86::GR16RegClass);
16817       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16818         return std::make_pair(0U, &X86::GR32RegClass);
16819       return std::make_pair(0U, &X86::GR64RegClass);
16820     case 'R':   // LEGACY_REGS
16821       if (VT == MVT::i8 || VT == MVT::i1)
16822         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16823       if (VT == MVT::i16)
16824         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16825       if (VT == MVT::i32 || !Subtarget->is64Bit())
16826         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16827       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16828     case 'f':  // FP Stack registers.
16829       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16830       // value to the correct fpstack register class.
16831       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16832         return std::make_pair(0U, &X86::RFP32RegClass);
16833       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16834         return std::make_pair(0U, &X86::RFP64RegClass);
16835       return std::make_pair(0U, &X86::RFP80RegClass);
16836     case 'y':   // MMX_REGS if MMX allowed.
16837       if (!Subtarget->hasMMX()) break;
16838       return std::make_pair(0U, &X86::VR64RegClass);
16839     case 'Y':   // SSE_REGS if SSE2 allowed
16840       if (!Subtarget->hasSSE2()) break;
16841       // FALL THROUGH.
16842     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16843       if (!Subtarget->hasSSE1()) break;
16844
16845       switch (VT.getSimpleVT().SimpleTy) {
16846       default: break;
16847       // Scalar SSE types.
16848       case MVT::f32:
16849       case MVT::i32:
16850         return std::make_pair(0U, &X86::FR32RegClass);
16851       case MVT::f64:
16852       case MVT::i64:
16853         return std::make_pair(0U, &X86::FR64RegClass);
16854       // Vector types.
16855       case MVT::v16i8:
16856       case MVT::v8i16:
16857       case MVT::v4i32:
16858       case MVT::v2i64:
16859       case MVT::v4f32:
16860       case MVT::v2f64:
16861         return std::make_pair(0U, &X86::VR128RegClass);
16862       // AVX types.
16863       case MVT::v32i8:
16864       case MVT::v16i16:
16865       case MVT::v8i32:
16866       case MVT::v4i64:
16867       case MVT::v8f32:
16868       case MVT::v4f64:
16869         return std::make_pair(0U, &X86::VR256RegClass);
16870       }
16871       break;
16872     }
16873   }
16874
16875   // Use the default implementation in TargetLowering to convert the register
16876   // constraint into a member of a register class.
16877   std::pair<unsigned, const TargetRegisterClass*> Res;
16878   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16879
16880   // Not found as a standard register?
16881   if (Res.second == 0) {
16882     // Map st(0) -> st(7) -> ST0
16883     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16884         tolower(Constraint[1]) == 's' &&
16885         tolower(Constraint[2]) == 't' &&
16886         Constraint[3] == '(' &&
16887         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16888         Constraint[5] == ')' &&
16889         Constraint[6] == '}') {
16890
16891       Res.first = X86::ST0+Constraint[4]-'0';
16892       Res.second = &X86::RFP80RegClass;
16893       return Res;
16894     }
16895
16896     // GCC allows "st(0)" to be called just plain "st".
16897     if (StringRef("{st}").equals_lower(Constraint)) {
16898       Res.first = X86::ST0;
16899       Res.second = &X86::RFP80RegClass;
16900       return Res;
16901     }
16902
16903     // flags -> EFLAGS
16904     if (StringRef("{flags}").equals_lower(Constraint)) {
16905       Res.first = X86::EFLAGS;
16906       Res.second = &X86::CCRRegClass;
16907       return Res;
16908     }
16909
16910     // 'A' means EAX + EDX.
16911     if (Constraint == "A") {
16912       Res.first = X86::EAX;
16913       Res.second = &X86::GR32_ADRegClass;
16914       return Res;
16915     }
16916     return Res;
16917   }
16918
16919   // Otherwise, check to see if this is a register class of the wrong value
16920   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16921   // turn into {ax},{dx}.
16922   if (Res.second->hasType(VT))
16923     return Res;   // Correct type already, nothing to do.
16924
16925   // All of the single-register GCC register classes map their values onto
16926   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16927   // really want an 8-bit or 32-bit register, map to the appropriate register
16928   // class and return the appropriate register.
16929   if (Res.second == &X86::GR16RegClass) {
16930     if (VT == MVT::i8) {
16931       unsigned DestReg = 0;
16932       switch (Res.first) {
16933       default: break;
16934       case X86::AX: DestReg = X86::AL; break;
16935       case X86::DX: DestReg = X86::DL; break;
16936       case X86::CX: DestReg = X86::CL; break;
16937       case X86::BX: DestReg = X86::BL; break;
16938       }
16939       if (DestReg) {
16940         Res.first = DestReg;
16941         Res.second = &X86::GR8RegClass;
16942       }
16943     } else if (VT == MVT::i32) {
16944       unsigned DestReg = 0;
16945       switch (Res.first) {
16946       default: break;
16947       case X86::AX: DestReg = X86::EAX; break;
16948       case X86::DX: DestReg = X86::EDX; break;
16949       case X86::CX: DestReg = X86::ECX; break;
16950       case X86::BX: DestReg = X86::EBX; break;
16951       case X86::SI: DestReg = X86::ESI; break;
16952       case X86::DI: DestReg = X86::EDI; break;
16953       case X86::BP: DestReg = X86::EBP; break;
16954       case X86::SP: DestReg = X86::ESP; break;
16955       }
16956       if (DestReg) {
16957         Res.first = DestReg;
16958         Res.second = &X86::GR32RegClass;
16959       }
16960     } else if (VT == MVT::i64) {
16961       unsigned DestReg = 0;
16962       switch (Res.first) {
16963       default: break;
16964       case X86::AX: DestReg = X86::RAX; break;
16965       case X86::DX: DestReg = X86::RDX; break;
16966       case X86::CX: DestReg = X86::RCX; break;
16967       case X86::BX: DestReg = X86::RBX; break;
16968       case X86::SI: DestReg = X86::RSI; break;
16969       case X86::DI: DestReg = X86::RDI; break;
16970       case X86::BP: DestReg = X86::RBP; break;
16971       case X86::SP: DestReg = X86::RSP; break;
16972       }
16973       if (DestReg) {
16974         Res.first = DestReg;
16975         Res.second = &X86::GR64RegClass;
16976       }
16977     }
16978   } else if (Res.second == &X86::FR32RegClass ||
16979              Res.second == &X86::FR64RegClass ||
16980              Res.second == &X86::VR128RegClass) {
16981     // Handle references to XMM physical registers that got mapped into the
16982     // wrong class.  This can happen with constraints like {xmm0} where the
16983     // target independent register mapper will just pick the first match it can
16984     // find, ignoring the required type.
16985
16986     if (VT == MVT::f32 || VT == MVT::i32)
16987       Res.second = &X86::FR32RegClass;
16988     else if (VT == MVT::f64 || VT == MVT::i64)
16989       Res.second = &X86::FR64RegClass;
16990     else if (X86::VR128RegClass.hasType(VT))
16991       Res.second = &X86::VR128RegClass;
16992     else if (X86::VR256RegClass.hasType(VT))
16993       Res.second = &X86::VR256RegClass;
16994   }
16995
16996   return Res;
16997 }