e84ec2959cf1ff88835fc6441b7dc17e266f220b
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "X86.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 using namespace llvm;
53
54 STATISTIC(NumTailCalls, "Number of tail calls");
55
56 // Forward declarations.
57 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
58                        SDValue V2);
59
60 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
61 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
62 /// simple subregister reference.  Idx is an index in the 128 bits we
63 /// want.  It need not be aligned to a 128-bit bounday.  That makes
64 /// lowering EXTRACT_VECTOR_ELT operations easier.
65 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
66                                    SelectionDAG &DAG, DebugLoc dl) {
67   EVT VT = Vec.getValueType();
68   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
69   EVT ElVT = VT.getVectorElementType();
70   unsigned Factor = VT.getSizeInBits()/128;
71   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72                                   VT.getVectorNumElements()/Factor);
73
74   // Extract from UNDEF is UNDEF.
75   if (Vec.getOpcode() == ISD::UNDEF)
76     return DAG.getUNDEF(ResultVT);
77
78   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
79   // we can match to VEXTRACTF128.
80   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
81
82   // This is the index of the first element of the 128-bit chunk
83   // we want.
84   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
85                                * ElemsPerChunk);
86
87   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
88   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
89                                VecIdx);
90
91   return Result;
92 }
93
94 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
95 /// sets things up to match to an AVX VINSERTF128 instruction or a
96 /// simple superregister reference.  Idx is an index in the 128 bits
97 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
98 /// lowering INSERT_VECTOR_ELT operations easier.
99 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
100                                   unsigned IdxVal, SelectionDAG &DAG,
101                                   DebugLoc dl) {
102   // Inserting UNDEF is Result
103   if (Vec.getOpcode() == ISD::UNDEF)
104     return Result;
105
106   EVT VT = Vec.getValueType();
107   assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
108
109   EVT ElVT = VT.getVectorElementType();
110   EVT ResultVT = Result.getValueType();
111
112   // Insert the relevant 128 bits.
113   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
114
115   // This is the index of the first element of the 128-bit chunk
116   // we want.
117   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
118                                * ElemsPerChunk);
119
120   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
121   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
122                      VecIdx);
123 }
124
125 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
126 /// instructions. This is used because creating CONCAT_VECTOR nodes of
127 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
128 /// large BUILD_VECTORS.
129 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
130                                    unsigned NumElems, SelectionDAG &DAG,
131                                    DebugLoc dl) {
132   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
133   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
134 }
135
136 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
137   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
138   bool is64Bit = Subtarget->is64Bit();
139
140   if (Subtarget->isTargetEnvMacho()) {
141     if (is64Bit)
142       return new X8664_MachoTargetObjectFile();
143     return new TargetLoweringObjectFileMachO();
144   }
145
146   if (Subtarget->isTargetLinux())
147     return new X86LinuxTargetObjectFile();
148   if (Subtarget->isTargetELF())
149     return new TargetLoweringObjectFileELF();
150   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
151     return new TargetLoweringObjectFileCOFF();
152   llvm_unreachable("unknown subtarget type");
153 }
154
155 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
156   : TargetLowering(TM, createTLOF(TM)) {
157   Subtarget = &TM.getSubtarget<X86Subtarget>();
158   X86ScalarSSEf64 = Subtarget->hasSSE2();
159   X86ScalarSSEf32 = Subtarget->hasSSE1();
160   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
161
162   RegInfo = TM.getRegisterInfo();
163   TD = getTargetData();
164
165   // Set up the TargetLowering object.
166   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
167
168   // X86 is weird, it always uses i8 for shift amounts and setcc results.
169   setBooleanContents(ZeroOrOneBooleanContent);
170   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
172
173   // For 64-bit since we have so many registers use the ILP scheduler, for
174   // 32-bit code use the register pressure specific scheduling.
175   // For Atom, always use ILP scheduling.
176   if (Subtarget->isAtom()) 
177     setSchedulingPreference(Sched::ILP);
178   else if (Subtarget->is64Bit())
179     setSchedulingPreference(Sched::ILP);
180   else
181     setSchedulingPreference(Sched::RegPressure);
182   setStackPointerRegisterToSaveRestore(X86StackPtr);
183
184   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
185     // Setup Windows compiler runtime calls.
186     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
187     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
188     setLibcallName(RTLIB::SREM_I64, "_allrem");
189     setLibcallName(RTLIB::UREM_I64, "_aullrem");
190     setLibcallName(RTLIB::MUL_I64, "_allmul");
191     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
192     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
193     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
194     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
195     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
196
197     // The _ftol2 runtime function has an unusual calling conv, which
198     // is modeled by a special pseudo-instruction.
199     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
200     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
201     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
202     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
203   }
204
205   if (Subtarget->isTargetDarwin()) {
206     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
207     setUseUnderscoreSetJmp(false);
208     setUseUnderscoreLongJmp(false);
209   } else if (Subtarget->isTargetMingw()) {
210     // MS runtime is weird: it exports _setjmp, but longjmp!
211     setUseUnderscoreSetJmp(true);
212     setUseUnderscoreLongJmp(false);
213   } else {
214     setUseUnderscoreSetJmp(true);
215     setUseUnderscoreLongJmp(true);
216   }
217
218   // Set up the register classes.
219   addRegisterClass(MVT::i8, &X86::GR8RegClass);
220   addRegisterClass(MVT::i16, &X86::GR16RegClass);
221   addRegisterClass(MVT::i32, &X86::GR32RegClass);
222   if (Subtarget->is64Bit())
223     addRegisterClass(MVT::i64, &X86::GR64RegClass);
224
225   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
226
227   // We don't accept any truncstore of integer registers.
228   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
229   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
230   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
231   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
232   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
233   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
234
235   // SETOEQ and SETUNE require checking two conditions.
236   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
237   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
238   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
239   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
240   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
241   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
242
243   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
244   // operation.
245   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
246   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
247   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
248
249   if (Subtarget->is64Bit()) {
250     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
251     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
252   } else if (!TM.Options.UseSoftFloat) {
253     // We have an algorithm for SSE2->double, and we turn this into a
254     // 64-bit FILD followed by conditional FADD for other targets.
255     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
256     // We have an algorithm for SSE2, and we turn this into a 64-bit
257     // FILD for other targets.
258     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
259   }
260
261   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
262   // this operation.
263   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
264   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
265
266   if (!TM.Options.UseSoftFloat) {
267     // SSE has no i16 to fp conversion, only i32
268     if (X86ScalarSSEf32) {
269       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
270       // f32 and f64 cases are Legal, f80 case is not
271       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
272     } else {
273       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
274       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
275     }
276   } else {
277     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
278     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
279   }
280
281   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
282   // are Legal, f80 is custom lowered.
283   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
284   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
285
286   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
287   // this operation.
288   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
289   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
290
291   if (X86ScalarSSEf32) {
292     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
293     // f32 and f64 cases are Legal, f80 case is not
294     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
295   } else {
296     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
297     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
298   }
299
300   // Handle FP_TO_UINT by promoting the destination to a larger signed
301   // conversion.
302   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
303   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
304   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
305
306   if (Subtarget->is64Bit()) {
307     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
308     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
309   } else if (!TM.Options.UseSoftFloat) {
310     // Since AVX is a superset of SSE3, only check for SSE here.
311     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
312       // Expand FP_TO_UINT into a select.
313       // FIXME: We would like to use a Custom expander here eventually to do
314       // the optimal thing for SSE vs. the default expansion in the legalizer.
315       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
316     else
317       // With SSE3 we can use fisttpll to convert to a signed i64; without
318       // SSE, we're stuck with a fistpll.
319       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
320   }
321
322   if (isTargetFTOL()) {
323     // Use the _ftol2 runtime function, which has a pseudo-instruction
324     // to handle its weird calling convention.
325     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
326   }
327
328   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
329   if (!X86ScalarSSEf64) {
330     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
331     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
332     if (Subtarget->is64Bit()) {
333       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
334       // Without SSE, i64->f64 goes through memory.
335       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
336     }
337   }
338
339   // Scalar integer divide and remainder are lowered to use operations that
340   // produce two results, to match the available instructions. This exposes
341   // the two-result form to trivial CSE, which is able to combine x/y and x%y
342   // into a single instruction.
343   //
344   // Scalar integer multiply-high is also lowered to use two-result
345   // operations, to match the available instructions. However, plain multiply
346   // (low) operations are left as Legal, as there are single-result
347   // instructions for this in x86. Using the two-result multiply instructions
348   // when both high and low results are needed must be arranged by dagcombine.
349   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
350     MVT VT = IntVTs[i];
351     setOperationAction(ISD::MULHS, VT, Expand);
352     setOperationAction(ISD::MULHU, VT, Expand);
353     setOperationAction(ISD::SDIV, VT, Expand);
354     setOperationAction(ISD::UDIV, VT, Expand);
355     setOperationAction(ISD::SREM, VT, Expand);
356     setOperationAction(ISD::UREM, VT, Expand);
357
358     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
359     setOperationAction(ISD::ADDC, VT, Custom);
360     setOperationAction(ISD::ADDE, VT, Custom);
361     setOperationAction(ISD::SUBC, VT, Custom);
362     setOperationAction(ISD::SUBE, VT, Custom);
363   }
364
365   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
366   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
367   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
368   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
369   if (Subtarget->is64Bit())
370     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
371   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
372   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
374   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
375   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
376   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
378   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
379
380   // Promote the i8 variants and force them on up to i32 which has a shorter
381   // encoding.
382   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
383   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
384   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
385   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
386   if (Subtarget->hasBMI()) {
387     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
388     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
391   } else {
392     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
393     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
394     if (Subtarget->is64Bit())
395       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
396   }
397
398   if (Subtarget->hasLZCNT()) {
399     // When promoting the i8 variants, force them to i32 for a shorter
400     // encoding.
401     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
402     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
403     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
404     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
405     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
406     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
407     if (Subtarget->is64Bit())
408       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
409   } else {
410     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
411     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
412     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
413     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
414     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
415     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
418       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
419     }
420   }
421
422   if (Subtarget->hasPOPCNT()) {
423     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
424   } else {
425     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
426     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
427     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
428     if (Subtarget->is64Bit())
429       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
430   }
431
432   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
433   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
434
435   // These should be promoted to a larger select which is supported.
436   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
437   // X86 wants to expand cmov itself.
438   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
439   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
440   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
441   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
442   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
443   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
444   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
445   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
446   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
447   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
448   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
450   if (Subtarget->is64Bit()) {
451     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
452     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
453   }
454   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
455
456   // Darwin ABI issue.
457   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
458   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
459   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
460   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
461   if (Subtarget->is64Bit())
462     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
463   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
464   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
465   if (Subtarget->is64Bit()) {
466     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
467     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
468     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
469     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
470     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
471   }
472   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
473   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
474   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
475   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
476   if (Subtarget->is64Bit()) {
477     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
478     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
479     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
480   }
481
482   if (Subtarget->hasSSE1())
483     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
484
485   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
486   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
487
488   // On X86 and X86-64, atomic operations are lowered to locked instructions.
489   // Locked instructions, in turn, have implicit fence semantics (all memory
490   // operations are flushed before issuing the locked instruction, and they
491   // are not buffered), so we can fold away the common pattern of
492   // fence-atomic-fence.
493   setShouldFoldAtomicFences(true);
494
495   // Expand certain atomics
496   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
497     MVT VT = IntVTs[i];
498     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
499     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
500     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
501   }
502
503   if (!Subtarget->is64Bit()) {
504     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
505     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
512   }
513
514   if (Subtarget->hasCmpxchg16b()) {
515     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
516   }
517
518   // FIXME - use subtarget debug flags
519   if (!Subtarget->isTargetDarwin() &&
520       !Subtarget->isTargetELF() &&
521       !Subtarget->isTargetCygMing()) {
522     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
523   }
524
525   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
526   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
527   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
528   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
529   if (Subtarget->is64Bit()) {
530     setExceptionPointerRegister(X86::RAX);
531     setExceptionSelectorRegister(X86::RDX);
532   } else {
533     setExceptionPointerRegister(X86::EAX);
534     setExceptionSelectorRegister(X86::EDX);
535   }
536   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
537   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
538
539   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
540   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
541
542   setOperationAction(ISD::TRAP, MVT::Other, Legal);
543
544   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
545   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
546   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
547   if (Subtarget->is64Bit()) {
548     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
549     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
550   } else {
551     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
552     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
553   }
554
555   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
556   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
557
558   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
559     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
560                        MVT::i64 : MVT::i32, Custom);
561   else if (TM.Options.EnableSegmentedStacks)
562     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
563                        MVT::i64 : MVT::i32, Custom);
564   else
565     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
566                        MVT::i64 : MVT::i32, Expand);
567
568   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
569     // f32 and f64 use SSE.
570     // Set up the FP register classes.
571     addRegisterClass(MVT::f32, &X86::FR32RegClass);
572     addRegisterClass(MVT::f64, &X86::FR64RegClass);
573
574     // Use ANDPD to simulate FABS.
575     setOperationAction(ISD::FABS , MVT::f64, Custom);
576     setOperationAction(ISD::FABS , MVT::f32, Custom);
577
578     // Use XORP to simulate FNEG.
579     setOperationAction(ISD::FNEG , MVT::f64, Custom);
580     setOperationAction(ISD::FNEG , MVT::f32, Custom);
581
582     // Use ANDPD and ORPD to simulate FCOPYSIGN.
583     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
584     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
585
586     // Lower this to FGETSIGNx86 plus an AND.
587     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
588     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
589
590     // We don't support sin/cos/fmod
591     setOperationAction(ISD::FSIN , MVT::f64, Expand);
592     setOperationAction(ISD::FCOS , MVT::f64, Expand);
593     setOperationAction(ISD::FSIN , MVT::f32, Expand);
594     setOperationAction(ISD::FCOS , MVT::f32, Expand);
595
596     // Expand FP immediates into loads from the stack, except for the special
597     // cases we handle.
598     addLegalFPImmediate(APFloat(+0.0)); // xorpd
599     addLegalFPImmediate(APFloat(+0.0f)); // xorps
600   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
601     // Use SSE for f32, x87 for f64.
602     // Set up the FP register classes.
603     addRegisterClass(MVT::f32, &X86::FR32RegClass);
604     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
605
606     // Use ANDPS to simulate FABS.
607     setOperationAction(ISD::FABS , MVT::f32, Custom);
608
609     // Use XORP to simulate FNEG.
610     setOperationAction(ISD::FNEG , MVT::f32, Custom);
611
612     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
613
614     // Use ANDPS and ORPS to simulate FCOPYSIGN.
615     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
616     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
617
618     // We don't support sin/cos/fmod
619     setOperationAction(ISD::FSIN , MVT::f32, Expand);
620     setOperationAction(ISD::FCOS , MVT::f32, Expand);
621
622     // Special cases we handle for FP constants.
623     addLegalFPImmediate(APFloat(+0.0f)); // xorps
624     addLegalFPImmediate(APFloat(+0.0)); // FLD0
625     addLegalFPImmediate(APFloat(+1.0)); // FLD1
626     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
627     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
628
629     if (!TM.Options.UnsafeFPMath) {
630       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
631       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
632     }
633   } else if (!TM.Options.UseSoftFloat) {
634     // f32 and f64 in x87.
635     // Set up the FP register classes.
636     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
637     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
638
639     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
640     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
641     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
642     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
643
644     if (!TM.Options.UnsafeFPMath) {
645       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
646       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
647     }
648     addLegalFPImmediate(APFloat(+0.0)); // FLD0
649     addLegalFPImmediate(APFloat(+1.0)); // FLD1
650     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
651     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
652     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
653     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
654     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
655     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
656   }
657
658   // We don't support FMA.
659   setOperationAction(ISD::FMA, MVT::f64, Expand);
660   setOperationAction(ISD::FMA, MVT::f32, Expand);
661
662   // Long double always uses X87.
663   if (!TM.Options.UseSoftFloat) {
664     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
665     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
666     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
667     {
668       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
669       addLegalFPImmediate(TmpFlt);  // FLD0
670       TmpFlt.changeSign();
671       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
672
673       bool ignored;
674       APFloat TmpFlt2(+1.0);
675       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
676                       &ignored);
677       addLegalFPImmediate(TmpFlt2);  // FLD1
678       TmpFlt2.changeSign();
679       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
680     }
681
682     if (!TM.Options.UnsafeFPMath) {
683       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
684       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
685     }
686
687     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
688     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
689     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
690     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
691     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
692     setOperationAction(ISD::FMA, MVT::f80, Expand);
693   }
694
695   // Always use a library call for pow.
696   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
697   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
698   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
699
700   setOperationAction(ISD::FLOG, MVT::f80, Expand);
701   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
702   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
703   setOperationAction(ISD::FEXP, MVT::f80, Expand);
704   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
705
706   // First set operation action for all vector types to either promote
707   // (for widening) or expand (for scalarization). Then we will selectively
708   // turn on ones that can be effectively codegen'd.
709   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
710            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
711     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
726     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
728     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
729     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
763     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
768     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
769              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
770       setTruncStoreAction((MVT::SimpleValueType)VT,
771                           (MVT::SimpleValueType)InnerVT, Expand);
772     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
773     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
774     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
775   }
776
777   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
778   // with -msoft-float, disable use of MMX as well.
779   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
780     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
781     // No operations on x86mmx supported, everything uses intrinsics.
782   }
783
784   // MMX-sized vectors (other than x86mmx) are expected to be expanded
785   // into smaller operations.
786   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
787   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
788   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
789   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
790   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
791   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
792   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
793   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
794   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
795   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
796   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
797   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
798   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
799   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
800   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
801   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
802   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
803   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
804   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
805   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
806   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
807   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
808   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
809   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
810   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
811   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
812   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
813   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
814   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
815
816   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
817     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
818
819     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
820     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
821     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
822     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
823     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
824     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
825     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
826     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
827     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
828     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
829     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
830     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
831   }
832
833   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
834     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
835
836     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
837     // registers cannot be used even for integer operations.
838     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
839     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
840     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
841     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
842
843     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
844     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
845     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
846     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
847     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
848     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
849     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
850     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
851     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
852     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
853     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
854     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
855     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
856     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
857     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
858     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
859
860     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
861     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
862     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
863     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
864
865     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
866     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
867     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
868     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
869     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
870
871     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
872     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
873     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
874     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
875     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
876
877     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
878     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
879       EVT VT = (MVT::SimpleValueType)i;
880       // Do not attempt to custom lower non-power-of-2 vectors
881       if (!isPowerOf2_32(VT.getVectorNumElements()))
882         continue;
883       // Do not attempt to custom lower non-128-bit vectors
884       if (!VT.is128BitVector())
885         continue;
886       setOperationAction(ISD::BUILD_VECTOR,
887                          VT.getSimpleVT().SimpleTy, Custom);
888       setOperationAction(ISD::VECTOR_SHUFFLE,
889                          VT.getSimpleVT().SimpleTy, Custom);
890       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
891                          VT.getSimpleVT().SimpleTy, Custom);
892     }
893
894     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
895     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
896     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
897     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
898     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
899     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
900
901     if (Subtarget->is64Bit()) {
902       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
903       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
904     }
905
906     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
907     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
908       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
909       EVT VT = SVT;
910
911       // Do not attempt to promote non-128-bit vectors
912       if (!VT.is128BitVector())
913         continue;
914
915       setOperationAction(ISD::AND,    SVT, Promote);
916       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
917       setOperationAction(ISD::OR,     SVT, Promote);
918       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
919       setOperationAction(ISD::XOR,    SVT, Promote);
920       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
921       setOperationAction(ISD::LOAD,   SVT, Promote);
922       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
923       setOperationAction(ISD::SELECT, SVT, Promote);
924       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
925     }
926
927     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
928
929     // Custom lower v2i64 and v2f64 selects.
930     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
931     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
932     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
933     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
934
935     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
936     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
937   }
938
939   if (Subtarget->hasSSE41()) {
940     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
941     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
942     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
943     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
944     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
945     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
946     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
947     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
948     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
949     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
950
951     // FIXME: Do we need to handle scalar-to-vector here?
952     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
953
954     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
955     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
956     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
957     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
958     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
959
960     // i8 and i16 vectors are custom , because the source register and source
961     // source memory operand types are not the same width.  f32 vectors are
962     // custom since the immediate controlling the insert encodes additional
963     // information.
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
966     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
967     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
968
969     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
970     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
971     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
972     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
973
974     // FIXME: these should be Legal but thats only for the case where
975     // the index is constant.  For now custom expand to deal with that.
976     if (Subtarget->is64Bit()) {
977       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
978       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
979     }
980   }
981
982   if (Subtarget->hasSSE2()) {
983     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
984     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
985
986     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
987     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
988
989     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
990     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
991
992     if (Subtarget->hasAVX2()) {
993       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
994       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
995
996       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
997       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
998
999       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1000     } else {
1001       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1002       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1003
1004       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1005       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1006
1007       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1008     }
1009   }
1010
1011   if (Subtarget->hasSSE42())
1012     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
1013
1014   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1015     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1016     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1017     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1018     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1019     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1020     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1021
1022     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1023     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1024     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1025
1026     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1027     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1028     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1029     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1030     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1031     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1032
1033     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1034     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1035     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1036     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1037     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1038     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1039
1040     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1041     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1042     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1043
1044     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1045     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1046     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1047     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1048     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1049     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1050
1051     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1052     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1053
1054     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1055     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1056
1057     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1058     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1059
1060     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1061     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1062     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1063     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1064
1065     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1066     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1067     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1068
1069     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1070     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1071     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1072     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1073
1074     if (Subtarget->hasAVX2()) {
1075       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1076       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1077       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1078       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1079
1080       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1081       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1082       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1083       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1084
1085       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1086       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1087       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1088       // Don't lower v32i8 because there is no 128-bit byte mul
1089
1090       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1091
1092       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1093       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1094
1095       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1096       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1097
1098       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1099     } else {
1100       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1101       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1102       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1103       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1104
1105       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1106       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1107       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1108       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1109
1110       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1111       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1112       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1113       // Don't lower v32i8 because there is no 128-bit byte mul
1114
1115       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1116       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1117
1118       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1119       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1120
1121       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1122     }
1123
1124     // Custom lower several nodes for 256-bit types.
1125     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1126              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1127       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1128       EVT VT = SVT;
1129
1130       // Extract subvector is special because the value type
1131       // (result) is 128-bit but the source is 256-bit wide.
1132       if (VT.is128BitVector())
1133         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1134
1135       // Do not attempt to custom lower other non-256-bit vectors
1136       if (!VT.is256BitVector())
1137         continue;
1138
1139       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1140       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1141       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1142       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1143       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1144       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1145     }
1146
1147     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1148     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1149       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1150       EVT VT = SVT;
1151
1152       // Do not attempt to promote non-256-bit vectors
1153       if (!VT.is256BitVector())
1154         continue;
1155
1156       setOperationAction(ISD::AND,    SVT, Promote);
1157       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1158       setOperationAction(ISD::OR,     SVT, Promote);
1159       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1160       setOperationAction(ISD::XOR,    SVT, Promote);
1161       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1162       setOperationAction(ISD::LOAD,   SVT, Promote);
1163       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1164       setOperationAction(ISD::SELECT, SVT, Promote);
1165       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1166     }
1167   }
1168
1169   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1170   // of this type with custom code.
1171   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1172            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1173     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1174                        Custom);
1175   }
1176
1177   // We want to custom lower some of our intrinsics.
1178   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1179
1180
1181   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1182   // handle type legalization for these operations here.
1183   //
1184   // FIXME: We really should do custom legalization for addition and
1185   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1186   // than generic legalization for 64-bit multiplication-with-overflow, though.
1187   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1188     // Add/Sub/Mul with overflow operations are custom lowered.
1189     MVT VT = IntVTs[i];
1190     setOperationAction(ISD::SADDO, VT, Custom);
1191     setOperationAction(ISD::UADDO, VT, Custom);
1192     setOperationAction(ISD::SSUBO, VT, Custom);
1193     setOperationAction(ISD::USUBO, VT, Custom);
1194     setOperationAction(ISD::SMULO, VT, Custom);
1195     setOperationAction(ISD::UMULO, VT, Custom);
1196   }
1197
1198   // There are no 8-bit 3-address imul/mul instructions
1199   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1200   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1201
1202   if (!Subtarget->is64Bit()) {
1203     // These libcalls are not available in 32-bit.
1204     setLibcallName(RTLIB::SHL_I128, 0);
1205     setLibcallName(RTLIB::SRL_I128, 0);
1206     setLibcallName(RTLIB::SRA_I128, 0);
1207   }
1208
1209   // We have target-specific dag combine patterns for the following nodes:
1210   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1211   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1212   setTargetDAGCombine(ISD::VSELECT);
1213   setTargetDAGCombine(ISD::SELECT);
1214   setTargetDAGCombine(ISD::SHL);
1215   setTargetDAGCombine(ISD::SRA);
1216   setTargetDAGCombine(ISD::SRL);
1217   setTargetDAGCombine(ISD::OR);
1218   setTargetDAGCombine(ISD::AND);
1219   setTargetDAGCombine(ISD::ADD);
1220   setTargetDAGCombine(ISD::FADD);
1221   setTargetDAGCombine(ISD::FSUB);
1222   setTargetDAGCombine(ISD::SUB);
1223   setTargetDAGCombine(ISD::LOAD);
1224   setTargetDAGCombine(ISD::STORE);
1225   setTargetDAGCombine(ISD::ZERO_EXTEND);
1226   setTargetDAGCombine(ISD::ANY_EXTEND);
1227   setTargetDAGCombine(ISD::SIGN_EXTEND);
1228   setTargetDAGCombine(ISD::TRUNCATE);
1229   setTargetDAGCombine(ISD::UINT_TO_FP);
1230   setTargetDAGCombine(ISD::SINT_TO_FP);
1231   setTargetDAGCombine(ISD::SETCC);
1232   setTargetDAGCombine(ISD::FP_TO_SINT);
1233   if (Subtarget->is64Bit())
1234     setTargetDAGCombine(ISD::MUL);
1235   setTargetDAGCombine(ISD::XOR);
1236
1237   computeRegisterProperties();
1238
1239   // On Darwin, -Os means optimize for size without hurting performance,
1240   // do not reduce the limit.
1241   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1242   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1243   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1244   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1245   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1246   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1247   setPrefLoopAlignment(4); // 2^4 bytes.
1248   benefitFromCodePlacementOpt = true;
1249
1250   // Predictable cmov don't hurt on atom because it's in-order.
1251   predictableSelectIsExpensive = !Subtarget->isAtom();
1252
1253   setPrefFunctionAlignment(4); // 2^4 bytes.
1254 }
1255
1256
1257 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1258   if (!VT.isVector()) return MVT::i8;
1259   return VT.changeVectorElementTypeToInteger();
1260 }
1261
1262
1263 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1264 /// the desired ByVal argument alignment.
1265 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1266   if (MaxAlign == 16)
1267     return;
1268   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1269     if (VTy->getBitWidth() == 128)
1270       MaxAlign = 16;
1271   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1272     unsigned EltAlign = 0;
1273     getMaxByValAlign(ATy->getElementType(), EltAlign);
1274     if (EltAlign > MaxAlign)
1275       MaxAlign = EltAlign;
1276   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1277     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1278       unsigned EltAlign = 0;
1279       getMaxByValAlign(STy->getElementType(i), EltAlign);
1280       if (EltAlign > MaxAlign)
1281         MaxAlign = EltAlign;
1282       if (MaxAlign == 16)
1283         break;
1284     }
1285   }
1286 }
1287
1288 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1289 /// function arguments in the caller parameter area. For X86, aggregates
1290 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1291 /// are at 4-byte boundaries.
1292 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1293   if (Subtarget->is64Bit()) {
1294     // Max of 8 and alignment of type.
1295     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1296     if (TyAlign > 8)
1297       return TyAlign;
1298     return 8;
1299   }
1300
1301   unsigned Align = 4;
1302   if (Subtarget->hasSSE1())
1303     getMaxByValAlign(Ty, Align);
1304   return Align;
1305 }
1306
1307 /// getOptimalMemOpType - Returns the target specific optimal type for load
1308 /// and store operations as a result of memset, memcpy, and memmove
1309 /// lowering. If DstAlign is zero that means it's safe to destination
1310 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1311 /// means there isn't a need to check it against alignment requirement,
1312 /// probably because the source does not need to be loaded. If
1313 /// 'IsZeroVal' is true, that means it's safe to return a
1314 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1315 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1316 /// constant so it does not need to be loaded.
1317 /// It returns EVT::Other if the type should be determined using generic
1318 /// target-independent logic.
1319 EVT
1320 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1321                                        unsigned DstAlign, unsigned SrcAlign,
1322                                        bool IsZeroVal,
1323                                        bool MemcpyStrSrc,
1324                                        MachineFunction &MF) const {
1325   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1326   // linux.  This is because the stack realignment code can't handle certain
1327   // cases like PR2962.  This should be removed when PR2962 is fixed.
1328   const Function *F = MF.getFunction();
1329   if (IsZeroVal &&
1330       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1331     if (Size >= 16 &&
1332         (Subtarget->isUnalignedMemAccessFast() ||
1333          ((DstAlign == 0 || DstAlign >= 16) &&
1334           (SrcAlign == 0 || SrcAlign >= 16))) &&
1335         Subtarget->getStackAlignment() >= 16) {
1336       if (Subtarget->getStackAlignment() >= 32) {
1337         if (Subtarget->hasAVX2())
1338           return MVT::v8i32;
1339         if (Subtarget->hasAVX())
1340           return MVT::v8f32;
1341       }
1342       if (Subtarget->hasSSE2())
1343         return MVT::v4i32;
1344       if (Subtarget->hasSSE1())
1345         return MVT::v4f32;
1346     } else if (!MemcpyStrSrc && Size >= 8 &&
1347                !Subtarget->is64Bit() &&
1348                Subtarget->getStackAlignment() >= 8 &&
1349                Subtarget->hasSSE2()) {
1350       // Do not use f64 to lower memcpy if source is string constant. It's
1351       // better to use i32 to avoid the loads.
1352       return MVT::f64;
1353     }
1354   }
1355   if (Subtarget->is64Bit() && Size >= 8)
1356     return MVT::i64;
1357   return MVT::i32;
1358 }
1359
1360 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1361 /// current function.  The returned value is a member of the
1362 /// MachineJumpTableInfo::JTEntryKind enum.
1363 unsigned X86TargetLowering::getJumpTableEncoding() const {
1364   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1365   // symbol.
1366   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1367       Subtarget->isPICStyleGOT())
1368     return MachineJumpTableInfo::EK_Custom32;
1369
1370   // Otherwise, use the normal jump table encoding heuristics.
1371   return TargetLowering::getJumpTableEncoding();
1372 }
1373
1374 const MCExpr *
1375 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1376                                              const MachineBasicBlock *MBB,
1377                                              unsigned uid,MCContext &Ctx) const{
1378   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1379          Subtarget->isPICStyleGOT());
1380   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1381   // entries.
1382   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1383                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1384 }
1385
1386 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1387 /// jumptable.
1388 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1389                                                     SelectionDAG &DAG) const {
1390   if (!Subtarget->is64Bit())
1391     // This doesn't have DebugLoc associated with it, but is not really the
1392     // same as a Register.
1393     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1394   return Table;
1395 }
1396
1397 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1398 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1399 /// MCExpr.
1400 const MCExpr *X86TargetLowering::
1401 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1402                              MCContext &Ctx) const {
1403   // X86-64 uses RIP relative addressing based on the jump table label.
1404   if (Subtarget->isPICStyleRIPRel())
1405     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1406
1407   // Otherwise, the reference is relative to the PIC base.
1408   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1409 }
1410
1411 // FIXME: Why this routine is here? Move to RegInfo!
1412 std::pair<const TargetRegisterClass*, uint8_t>
1413 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1414   const TargetRegisterClass *RRC = 0;
1415   uint8_t Cost = 1;
1416   switch (VT.getSimpleVT().SimpleTy) {
1417   default:
1418     return TargetLowering::findRepresentativeClass(VT);
1419   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1420     RRC = Subtarget->is64Bit() ?
1421       (const TargetRegisterClass*)&X86::GR64RegClass :
1422       (const TargetRegisterClass*)&X86::GR32RegClass;
1423     break;
1424   case MVT::x86mmx:
1425     RRC = &X86::VR64RegClass;
1426     break;
1427   case MVT::f32: case MVT::f64:
1428   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1429   case MVT::v4f32: case MVT::v2f64:
1430   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1431   case MVT::v4f64:
1432     RRC = &X86::VR128RegClass;
1433     break;
1434   }
1435   return std::make_pair(RRC, Cost);
1436 }
1437
1438 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1439                                                unsigned &Offset) const {
1440   if (!Subtarget->isTargetLinux())
1441     return false;
1442
1443   if (Subtarget->is64Bit()) {
1444     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1445     Offset = 0x28;
1446     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1447       AddressSpace = 256;
1448     else
1449       AddressSpace = 257;
1450   } else {
1451     // %gs:0x14 on i386
1452     Offset = 0x14;
1453     AddressSpace = 256;
1454   }
1455   return true;
1456 }
1457
1458
1459 //===----------------------------------------------------------------------===//
1460 //               Return Value Calling Convention Implementation
1461 //===----------------------------------------------------------------------===//
1462
1463 #include "X86GenCallingConv.inc"
1464
1465 bool
1466 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1467                                   MachineFunction &MF, bool isVarArg,
1468                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1469                         LLVMContext &Context) const {
1470   SmallVector<CCValAssign, 16> RVLocs;
1471   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1472                  RVLocs, Context);
1473   return CCInfo.CheckReturn(Outs, RetCC_X86);
1474 }
1475
1476 SDValue
1477 X86TargetLowering::LowerReturn(SDValue Chain,
1478                                CallingConv::ID CallConv, bool isVarArg,
1479                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1480                                const SmallVectorImpl<SDValue> &OutVals,
1481                                DebugLoc dl, SelectionDAG &DAG) const {
1482   MachineFunction &MF = DAG.getMachineFunction();
1483   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1484
1485   SmallVector<CCValAssign, 16> RVLocs;
1486   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1487                  RVLocs, *DAG.getContext());
1488   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1489
1490   // Add the regs to the liveout set for the function.
1491   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1492   for (unsigned i = 0; i != RVLocs.size(); ++i)
1493     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1494       MRI.addLiveOut(RVLocs[i].getLocReg());
1495
1496   SDValue Flag;
1497
1498   SmallVector<SDValue, 6> RetOps;
1499   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1500   // Operand #1 = Bytes To Pop
1501   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1502                    MVT::i16));
1503
1504   // Copy the result values into the output registers.
1505   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1506     CCValAssign &VA = RVLocs[i];
1507     assert(VA.isRegLoc() && "Can only return in registers!");
1508     SDValue ValToCopy = OutVals[i];
1509     EVT ValVT = ValToCopy.getValueType();
1510
1511     // Promote values to the appropriate types
1512     if (VA.getLocInfo() == CCValAssign::SExt)
1513       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1514     else if (VA.getLocInfo() == CCValAssign::ZExt)
1515       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1516     else if (VA.getLocInfo() == CCValAssign::AExt)
1517       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1518     else if (VA.getLocInfo() == CCValAssign::BCvt)
1519       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1520
1521     // If this is x86-64, and we disabled SSE, we can't return FP values,
1522     // or SSE or MMX vectors.
1523     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1524          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1525           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1526       report_fatal_error("SSE register return with SSE disabled");
1527     }
1528     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1529     // llvm-gcc has never done it right and no one has noticed, so this
1530     // should be OK for now.
1531     if (ValVT == MVT::f64 &&
1532         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1533       report_fatal_error("SSE2 register return with SSE2 disabled");
1534
1535     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1536     // the RET instruction and handled by the FP Stackifier.
1537     if (VA.getLocReg() == X86::ST0 ||
1538         VA.getLocReg() == X86::ST1) {
1539       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1540       // change the value to the FP stack register class.
1541       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1542         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1543       RetOps.push_back(ValToCopy);
1544       // Don't emit a copytoreg.
1545       continue;
1546     }
1547
1548     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1549     // which is returned in RAX / RDX.
1550     if (Subtarget->is64Bit()) {
1551       if (ValVT == MVT::x86mmx) {
1552         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1553           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1554           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1555                                   ValToCopy);
1556           // If we don't have SSE2 available, convert to v4f32 so the generated
1557           // register is legal.
1558           if (!Subtarget->hasSSE2())
1559             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1560         }
1561       }
1562     }
1563
1564     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1565     Flag = Chain.getValue(1);
1566   }
1567
1568   // The x86-64 ABI for returning structs by value requires that we copy
1569   // the sret argument into %rax for the return. We saved the argument into
1570   // a virtual register in the entry block, so now we copy the value out
1571   // and into %rax.
1572   if (Subtarget->is64Bit() &&
1573       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1574     MachineFunction &MF = DAG.getMachineFunction();
1575     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1576     unsigned Reg = FuncInfo->getSRetReturnReg();
1577     assert(Reg &&
1578            "SRetReturnReg should have been set in LowerFormalArguments().");
1579     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1580
1581     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1582     Flag = Chain.getValue(1);
1583
1584     // RAX now acts like a return value.
1585     MRI.addLiveOut(X86::RAX);
1586   }
1587
1588   RetOps[0] = Chain;  // Update chain.
1589
1590   // Add the flag if we have it.
1591   if (Flag.getNode())
1592     RetOps.push_back(Flag);
1593
1594   return DAG.getNode(X86ISD::RET_FLAG, dl,
1595                      MVT::Other, &RetOps[0], RetOps.size());
1596 }
1597
1598 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1599   if (N->getNumValues() != 1)
1600     return false;
1601   if (!N->hasNUsesOfValue(1, 0))
1602     return false;
1603
1604   SDValue TCChain = Chain;
1605   SDNode *Copy = *N->use_begin();
1606   if (Copy->getOpcode() == ISD::CopyToReg) {
1607     // If the copy has a glue operand, we conservatively assume it isn't safe to
1608     // perform a tail call.
1609     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1610       return false;
1611     TCChain = Copy->getOperand(0);
1612   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1613     return false;
1614
1615   bool HasRet = false;
1616   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1617        UI != UE; ++UI) {
1618     if (UI->getOpcode() != X86ISD::RET_FLAG)
1619       return false;
1620     HasRet = true;
1621   }
1622
1623   if (!HasRet)
1624     return false;
1625
1626   Chain = TCChain;
1627   return true;
1628 }
1629
1630 EVT
1631 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1632                                             ISD::NodeType ExtendKind) const {
1633   MVT ReturnMVT;
1634   // TODO: Is this also valid on 32-bit?
1635   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1636     ReturnMVT = MVT::i8;
1637   else
1638     ReturnMVT = MVT::i32;
1639
1640   EVT MinVT = getRegisterType(Context, ReturnMVT);
1641   return VT.bitsLT(MinVT) ? MinVT : VT;
1642 }
1643
1644 /// LowerCallResult - Lower the result values of a call into the
1645 /// appropriate copies out of appropriate physical registers.
1646 ///
1647 SDValue
1648 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1649                                    CallingConv::ID CallConv, bool isVarArg,
1650                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1651                                    DebugLoc dl, SelectionDAG &DAG,
1652                                    SmallVectorImpl<SDValue> &InVals) const {
1653
1654   // Assign locations to each value returned by this call.
1655   SmallVector<CCValAssign, 16> RVLocs;
1656   bool Is64Bit = Subtarget->is64Bit();
1657   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1658                  getTargetMachine(), RVLocs, *DAG.getContext());
1659   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1660
1661   // Copy all of the result registers out of their specified physreg.
1662   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1663     CCValAssign &VA = RVLocs[i];
1664     EVT CopyVT = VA.getValVT();
1665
1666     // If this is x86-64, and we disabled SSE, we can't return FP values
1667     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1668         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1669       report_fatal_error("SSE register return with SSE disabled");
1670     }
1671
1672     SDValue Val;
1673
1674     // If this is a call to a function that returns an fp value on the floating
1675     // point stack, we must guarantee the the value is popped from the stack, so
1676     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1677     // if the return value is not used. We use the FpPOP_RETVAL instruction
1678     // instead.
1679     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1680       // If we prefer to use the value in xmm registers, copy it out as f80 and
1681       // use a truncate to move it from fp stack reg to xmm reg.
1682       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1683       SDValue Ops[] = { Chain, InFlag };
1684       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1685                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1686       Val = Chain.getValue(0);
1687
1688       // Round the f80 to the right size, which also moves it to the appropriate
1689       // xmm register.
1690       if (CopyVT != VA.getValVT())
1691         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1692                           // This truncation won't change the value.
1693                           DAG.getIntPtrConstant(1));
1694     } else {
1695       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1696                                  CopyVT, InFlag).getValue(1);
1697       Val = Chain.getValue(0);
1698     }
1699     InFlag = Chain.getValue(2);
1700     InVals.push_back(Val);
1701   }
1702
1703   return Chain;
1704 }
1705
1706
1707 //===----------------------------------------------------------------------===//
1708 //                C & StdCall & Fast Calling Convention implementation
1709 //===----------------------------------------------------------------------===//
1710 //  StdCall calling convention seems to be standard for many Windows' API
1711 //  routines and around. It differs from C calling convention just a little:
1712 //  callee should clean up the stack, not caller. Symbols should be also
1713 //  decorated in some fancy way :) It doesn't support any vector arguments.
1714 //  For info on fast calling convention see Fast Calling Convention (tail call)
1715 //  implementation LowerX86_32FastCCCallTo.
1716
1717 /// CallIsStructReturn - Determines whether a call uses struct return
1718 /// semantics.
1719 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1720   if (Outs.empty())
1721     return false;
1722
1723   return Outs[0].Flags.isSRet();
1724 }
1725
1726 /// ArgsAreStructReturn - Determines whether a function uses struct
1727 /// return semantics.
1728 static bool
1729 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1730   if (Ins.empty())
1731     return false;
1732
1733   return Ins[0].Flags.isSRet();
1734 }
1735
1736 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1737 /// by "Src" to address "Dst" with size and alignment information specified by
1738 /// the specific parameter attribute. The copy will be passed as a byval
1739 /// function parameter.
1740 static SDValue
1741 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1742                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1743                           DebugLoc dl) {
1744   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1745
1746   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1747                        /*isVolatile*/false, /*AlwaysInline=*/true,
1748                        MachinePointerInfo(), MachinePointerInfo());
1749 }
1750
1751 /// IsTailCallConvention - Return true if the calling convention is one that
1752 /// supports tail call optimization.
1753 static bool IsTailCallConvention(CallingConv::ID CC) {
1754   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1755 }
1756
1757 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1758   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1759     return false;
1760
1761   CallSite CS(CI);
1762   CallingConv::ID CalleeCC = CS.getCallingConv();
1763   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1764     return false;
1765
1766   return true;
1767 }
1768
1769 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1770 /// a tailcall target by changing its ABI.
1771 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1772                                    bool GuaranteedTailCallOpt) {
1773   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1774 }
1775
1776 SDValue
1777 X86TargetLowering::LowerMemArgument(SDValue Chain,
1778                                     CallingConv::ID CallConv,
1779                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1780                                     DebugLoc dl, SelectionDAG &DAG,
1781                                     const CCValAssign &VA,
1782                                     MachineFrameInfo *MFI,
1783                                     unsigned i) const {
1784   // Create the nodes corresponding to a load from this parameter slot.
1785   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1786   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1787                               getTargetMachine().Options.GuaranteedTailCallOpt);
1788   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1789   EVT ValVT;
1790
1791   // If value is passed by pointer we have address passed instead of the value
1792   // itself.
1793   if (VA.getLocInfo() == CCValAssign::Indirect)
1794     ValVT = VA.getLocVT();
1795   else
1796     ValVT = VA.getValVT();
1797
1798   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1799   // changed with more analysis.
1800   // In case of tail call optimization mark all arguments mutable. Since they
1801   // could be overwritten by lowering of arguments in case of a tail call.
1802   if (Flags.isByVal()) {
1803     unsigned Bytes = Flags.getByValSize();
1804     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1805     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1806     return DAG.getFrameIndex(FI, getPointerTy());
1807   } else {
1808     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1809                                     VA.getLocMemOffset(), isImmutable);
1810     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1811     return DAG.getLoad(ValVT, dl, Chain, FIN,
1812                        MachinePointerInfo::getFixedStack(FI),
1813                        false, false, false, 0);
1814   }
1815 }
1816
1817 SDValue
1818 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1819                                         CallingConv::ID CallConv,
1820                                         bool isVarArg,
1821                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1822                                         DebugLoc dl,
1823                                         SelectionDAG &DAG,
1824                                         SmallVectorImpl<SDValue> &InVals)
1825                                           const {
1826   MachineFunction &MF = DAG.getMachineFunction();
1827   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1828
1829   const Function* Fn = MF.getFunction();
1830   if (Fn->hasExternalLinkage() &&
1831       Subtarget->isTargetCygMing() &&
1832       Fn->getName() == "main")
1833     FuncInfo->setForceFramePointer(true);
1834
1835   MachineFrameInfo *MFI = MF.getFrameInfo();
1836   bool Is64Bit = Subtarget->is64Bit();
1837   bool IsWindows = Subtarget->isTargetWindows();
1838   bool IsWin64 = Subtarget->isTargetWin64();
1839
1840   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1841          "Var args not supported with calling convention fastcc or ghc");
1842
1843   // Assign locations to all of the incoming arguments.
1844   SmallVector<CCValAssign, 16> ArgLocs;
1845   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1846                  ArgLocs, *DAG.getContext());
1847
1848   // Allocate shadow area for Win64
1849   if (IsWin64) {
1850     CCInfo.AllocateStack(32, 8);
1851   }
1852
1853   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1854
1855   unsigned LastVal = ~0U;
1856   SDValue ArgValue;
1857   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1858     CCValAssign &VA = ArgLocs[i];
1859     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1860     // places.
1861     assert(VA.getValNo() != LastVal &&
1862            "Don't support value assigned to multiple locs yet");
1863     (void)LastVal;
1864     LastVal = VA.getValNo();
1865
1866     if (VA.isRegLoc()) {
1867       EVT RegVT = VA.getLocVT();
1868       const TargetRegisterClass *RC;
1869       if (RegVT == MVT::i32)
1870         RC = &X86::GR32RegClass;
1871       else if (Is64Bit && RegVT == MVT::i64)
1872         RC = &X86::GR64RegClass;
1873       else if (RegVT == MVT::f32)
1874         RC = &X86::FR32RegClass;
1875       else if (RegVT == MVT::f64)
1876         RC = &X86::FR64RegClass;
1877       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1878         RC = &X86::VR256RegClass;
1879       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1880         RC = &X86::VR128RegClass;
1881       else if (RegVT == MVT::x86mmx)
1882         RC = &X86::VR64RegClass;
1883       else
1884         llvm_unreachable("Unknown argument type!");
1885
1886       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1887       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1888
1889       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1890       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1891       // right size.
1892       if (VA.getLocInfo() == CCValAssign::SExt)
1893         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1894                                DAG.getValueType(VA.getValVT()));
1895       else if (VA.getLocInfo() == CCValAssign::ZExt)
1896         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1897                                DAG.getValueType(VA.getValVT()));
1898       else if (VA.getLocInfo() == CCValAssign::BCvt)
1899         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1900
1901       if (VA.isExtInLoc()) {
1902         // Handle MMX values passed in XMM regs.
1903         if (RegVT.isVector()) {
1904           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1905                                  ArgValue);
1906         } else
1907           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1908       }
1909     } else {
1910       assert(VA.isMemLoc());
1911       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1912     }
1913
1914     // If value is passed via pointer - do a load.
1915     if (VA.getLocInfo() == CCValAssign::Indirect)
1916       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1917                              MachinePointerInfo(), false, false, false, 0);
1918
1919     InVals.push_back(ArgValue);
1920   }
1921
1922   // The x86-64 ABI for returning structs by value requires that we copy
1923   // the sret argument into %rax for the return. Save the argument into
1924   // a virtual register so that we can access it from the return points.
1925   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1926     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1927     unsigned Reg = FuncInfo->getSRetReturnReg();
1928     if (!Reg) {
1929       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1930       FuncInfo->setSRetReturnReg(Reg);
1931     }
1932     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1933     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1934   }
1935
1936   unsigned StackSize = CCInfo.getNextStackOffset();
1937   // Align stack specially for tail calls.
1938   if (FuncIsMadeTailCallSafe(CallConv,
1939                              MF.getTarget().Options.GuaranteedTailCallOpt))
1940     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1941
1942   // If the function takes variable number of arguments, make a frame index for
1943   // the start of the first vararg value... for expansion of llvm.va_start.
1944   if (isVarArg) {
1945     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1946                     CallConv != CallingConv::X86_ThisCall)) {
1947       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1948     }
1949     if (Is64Bit) {
1950       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1951
1952       // FIXME: We should really autogenerate these arrays
1953       static const uint16_t GPR64ArgRegsWin64[] = {
1954         X86::RCX, X86::RDX, X86::R8,  X86::R9
1955       };
1956       static const uint16_t GPR64ArgRegs64Bit[] = {
1957         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1958       };
1959       static const uint16_t XMMArgRegs64Bit[] = {
1960         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1961         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1962       };
1963       const uint16_t *GPR64ArgRegs;
1964       unsigned NumXMMRegs = 0;
1965
1966       if (IsWin64) {
1967         // The XMM registers which might contain var arg parameters are shadowed
1968         // in their paired GPR.  So we only need to save the GPR to their home
1969         // slots.
1970         TotalNumIntRegs = 4;
1971         GPR64ArgRegs = GPR64ArgRegsWin64;
1972       } else {
1973         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1974         GPR64ArgRegs = GPR64ArgRegs64Bit;
1975
1976         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1977                                                 TotalNumXMMRegs);
1978       }
1979       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1980                                                        TotalNumIntRegs);
1981
1982       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1983       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1984              "SSE register cannot be used when SSE is disabled!");
1985       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1986                NoImplicitFloatOps) &&
1987              "SSE register cannot be used when SSE is disabled!");
1988       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1989           !Subtarget->hasSSE1())
1990         // Kernel mode asks for SSE to be disabled, so don't push them
1991         // on the stack.
1992         TotalNumXMMRegs = 0;
1993
1994       if (IsWin64) {
1995         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1996         // Get to the caller-allocated home save location.  Add 8 to account
1997         // for the return address.
1998         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1999         FuncInfo->setRegSaveFrameIndex(
2000           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2001         // Fixup to set vararg frame on shadow area (4 x i64).
2002         if (NumIntRegs < 4)
2003           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2004       } else {
2005         // For X86-64, if there are vararg parameters that are passed via
2006         // registers, then we must store them to their spots on the stack so
2007         // they may be loaded by deferencing the result of va_next.
2008         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2009         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2010         FuncInfo->setRegSaveFrameIndex(
2011           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2012                                false));
2013       }
2014
2015       // Store the integer parameter registers.
2016       SmallVector<SDValue, 8> MemOps;
2017       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2018                                         getPointerTy());
2019       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2020       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2021         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2022                                   DAG.getIntPtrConstant(Offset));
2023         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2024                                      &X86::GR64RegClass);
2025         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2026         SDValue Store =
2027           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2028                        MachinePointerInfo::getFixedStack(
2029                          FuncInfo->getRegSaveFrameIndex(), Offset),
2030                        false, false, 0);
2031         MemOps.push_back(Store);
2032         Offset += 8;
2033       }
2034
2035       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2036         // Now store the XMM (fp + vector) parameter registers.
2037         SmallVector<SDValue, 11> SaveXMMOps;
2038         SaveXMMOps.push_back(Chain);
2039
2040         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2041         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2042         SaveXMMOps.push_back(ALVal);
2043
2044         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2045                                FuncInfo->getRegSaveFrameIndex()));
2046         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2047                                FuncInfo->getVarArgsFPOffset()));
2048
2049         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2050           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2051                                        &X86::VR128RegClass);
2052           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2053           SaveXMMOps.push_back(Val);
2054         }
2055         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2056                                      MVT::Other,
2057                                      &SaveXMMOps[0], SaveXMMOps.size()));
2058       }
2059
2060       if (!MemOps.empty())
2061         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2062                             &MemOps[0], MemOps.size());
2063     }
2064   }
2065
2066   // Some CCs need callee pop.
2067   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2068                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2069     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2070   } else {
2071     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2072     // If this is an sret function, the return should pop the hidden pointer.
2073     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2074         ArgsAreStructReturn(Ins))
2075       FuncInfo->setBytesToPopOnReturn(4);
2076   }
2077
2078   if (!Is64Bit) {
2079     // RegSaveFrameIndex is X86-64 only.
2080     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2081     if (CallConv == CallingConv::X86_FastCall ||
2082         CallConv == CallingConv::X86_ThisCall)
2083       // fastcc functions can't have varargs.
2084       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2085   }
2086
2087   FuncInfo->setArgumentStackSize(StackSize);
2088
2089   return Chain;
2090 }
2091
2092 SDValue
2093 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2094                                     SDValue StackPtr, SDValue Arg,
2095                                     DebugLoc dl, SelectionDAG &DAG,
2096                                     const CCValAssign &VA,
2097                                     ISD::ArgFlagsTy Flags) const {
2098   unsigned LocMemOffset = VA.getLocMemOffset();
2099   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2100   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2101   if (Flags.isByVal())
2102     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2103
2104   return DAG.getStore(Chain, dl, Arg, PtrOff,
2105                       MachinePointerInfo::getStack(LocMemOffset),
2106                       false, false, 0);
2107 }
2108
2109 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2110 /// optimization is performed and it is required.
2111 SDValue
2112 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2113                                            SDValue &OutRetAddr, SDValue Chain,
2114                                            bool IsTailCall, bool Is64Bit,
2115                                            int FPDiff, DebugLoc dl) const {
2116   // Adjust the Return address stack slot.
2117   EVT VT = getPointerTy();
2118   OutRetAddr = getReturnAddressFrameIndex(DAG);
2119
2120   // Load the "old" Return address.
2121   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2122                            false, false, false, 0);
2123   return SDValue(OutRetAddr.getNode(), 1);
2124 }
2125
2126 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2127 /// optimization is performed and it is required (FPDiff!=0).
2128 static SDValue
2129 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2130                          SDValue Chain, SDValue RetAddrFrIdx,
2131                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2132   // Store the return address to the appropriate stack slot.
2133   if (!FPDiff) return Chain;
2134   // Calculate the new stack slot for the return address.
2135   int SlotSize = Is64Bit ? 8 : 4;
2136   int NewReturnAddrFI =
2137     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2138   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2139   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2140   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2141                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2142                        false, false, 0);
2143   return Chain;
2144 }
2145
2146 SDValue
2147 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2148                              SmallVectorImpl<SDValue> &InVals) const {
2149   SelectionDAG &DAG                     = CLI.DAG;
2150   DebugLoc &dl                          = CLI.DL;
2151   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2152   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2153   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2154   SDValue Chain                         = CLI.Chain;
2155   SDValue Callee                        = CLI.Callee;
2156   CallingConv::ID CallConv              = CLI.CallConv;
2157   bool &isTailCall                      = CLI.IsTailCall;
2158   bool isVarArg                         = CLI.IsVarArg;
2159
2160   MachineFunction &MF = DAG.getMachineFunction();
2161   bool Is64Bit        = Subtarget->is64Bit();
2162   bool IsWin64        = Subtarget->isTargetWin64();
2163   bool IsWindows      = Subtarget->isTargetWindows();
2164   bool IsStructRet    = CallIsStructReturn(Outs);
2165   bool IsSibcall      = false;
2166
2167   if (MF.getTarget().Options.DisableTailCalls)
2168     isTailCall = false;
2169
2170   if (isTailCall) {
2171     // Check if it's really possible to do a tail call.
2172     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2173                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2174                                                    Outs, OutVals, Ins, DAG);
2175
2176     // Sibcalls are automatically detected tailcalls which do not require
2177     // ABI changes.
2178     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2179       IsSibcall = true;
2180
2181     if (isTailCall)
2182       ++NumTailCalls;
2183   }
2184
2185   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2186          "Var args not supported with calling convention fastcc or ghc");
2187
2188   // Analyze operands of the call, assigning locations to each operand.
2189   SmallVector<CCValAssign, 16> ArgLocs;
2190   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2191                  ArgLocs, *DAG.getContext());
2192
2193   // Allocate shadow area for Win64
2194   if (IsWin64) {
2195     CCInfo.AllocateStack(32, 8);
2196   }
2197
2198   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2199
2200   // Get a count of how many bytes are to be pushed on the stack.
2201   unsigned NumBytes = CCInfo.getNextStackOffset();
2202   if (IsSibcall)
2203     // This is a sibcall. The memory operands are available in caller's
2204     // own caller's stack.
2205     NumBytes = 0;
2206   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2207            IsTailCallConvention(CallConv))
2208     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2209
2210   int FPDiff = 0;
2211   if (isTailCall && !IsSibcall) {
2212     // Lower arguments at fp - stackoffset + fpdiff.
2213     unsigned NumBytesCallerPushed =
2214       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2215     FPDiff = NumBytesCallerPushed - NumBytes;
2216
2217     // Set the delta of movement of the returnaddr stackslot.
2218     // But only set if delta is greater than previous delta.
2219     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2220       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2221   }
2222
2223   if (!IsSibcall)
2224     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2225
2226   SDValue RetAddrFrIdx;
2227   // Load return address for tail calls.
2228   if (isTailCall && FPDiff)
2229     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2230                                     Is64Bit, FPDiff, dl);
2231
2232   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2233   SmallVector<SDValue, 8> MemOpChains;
2234   SDValue StackPtr;
2235
2236   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2237   // of tail call optimization arguments are handle later.
2238   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2239     CCValAssign &VA = ArgLocs[i];
2240     EVT RegVT = VA.getLocVT();
2241     SDValue Arg = OutVals[i];
2242     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2243     bool isByVal = Flags.isByVal();
2244
2245     // Promote the value if needed.
2246     switch (VA.getLocInfo()) {
2247     default: llvm_unreachable("Unknown loc info!");
2248     case CCValAssign::Full: break;
2249     case CCValAssign::SExt:
2250       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2251       break;
2252     case CCValAssign::ZExt:
2253       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2254       break;
2255     case CCValAssign::AExt:
2256       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2257         // Special case: passing MMX values in XMM registers.
2258         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2259         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2260         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2261       } else
2262         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2263       break;
2264     case CCValAssign::BCvt:
2265       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2266       break;
2267     case CCValAssign::Indirect: {
2268       // Store the argument.
2269       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2270       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2271       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2272                            MachinePointerInfo::getFixedStack(FI),
2273                            false, false, 0);
2274       Arg = SpillSlot;
2275       break;
2276     }
2277     }
2278
2279     if (VA.isRegLoc()) {
2280       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2281       if (isVarArg && IsWin64) {
2282         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2283         // shadow reg if callee is a varargs function.
2284         unsigned ShadowReg = 0;
2285         switch (VA.getLocReg()) {
2286         case X86::XMM0: ShadowReg = X86::RCX; break;
2287         case X86::XMM1: ShadowReg = X86::RDX; break;
2288         case X86::XMM2: ShadowReg = X86::R8; break;
2289         case X86::XMM3: ShadowReg = X86::R9; break;
2290         }
2291         if (ShadowReg)
2292           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2293       }
2294     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2295       assert(VA.isMemLoc());
2296       if (StackPtr.getNode() == 0)
2297         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2298       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2299                                              dl, DAG, VA, Flags));
2300     }
2301   }
2302
2303   if (!MemOpChains.empty())
2304     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2305                         &MemOpChains[0], MemOpChains.size());
2306
2307   // Build a sequence of copy-to-reg nodes chained together with token chain
2308   // and flag operands which copy the outgoing args into registers.
2309   SDValue InFlag;
2310   // Tail call byval lowering might overwrite argument registers so in case of
2311   // tail call optimization the copies to registers are lowered later.
2312   if (!isTailCall)
2313     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2314       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2315                                RegsToPass[i].second, InFlag);
2316       InFlag = Chain.getValue(1);
2317     }
2318
2319   if (Subtarget->isPICStyleGOT()) {
2320     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2321     // GOT pointer.
2322     if (!isTailCall) {
2323       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2324                                DAG.getNode(X86ISD::GlobalBaseReg,
2325                                            DebugLoc(), getPointerTy()),
2326                                InFlag);
2327       InFlag = Chain.getValue(1);
2328     } else {
2329       // If we are tail calling and generating PIC/GOT style code load the
2330       // address of the callee into ECX. The value in ecx is used as target of
2331       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2332       // for tail calls on PIC/GOT architectures. Normally we would just put the
2333       // address of GOT into ebx and then call target@PLT. But for tail calls
2334       // ebx would be restored (since ebx is callee saved) before jumping to the
2335       // target@PLT.
2336
2337       // Note: The actual moving to ECX is done further down.
2338       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2339       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2340           !G->getGlobal()->hasProtectedVisibility())
2341         Callee = LowerGlobalAddress(Callee, DAG);
2342       else if (isa<ExternalSymbolSDNode>(Callee))
2343         Callee = LowerExternalSymbol(Callee, DAG);
2344     }
2345   }
2346
2347   if (Is64Bit && isVarArg && !IsWin64) {
2348     // From AMD64 ABI document:
2349     // For calls that may call functions that use varargs or stdargs
2350     // (prototype-less calls or calls to functions containing ellipsis (...) in
2351     // the declaration) %al is used as hidden argument to specify the number
2352     // of SSE registers used. The contents of %al do not need to match exactly
2353     // the number of registers, but must be an ubound on the number of SSE
2354     // registers used and is in the range 0 - 8 inclusive.
2355
2356     // Count the number of XMM registers allocated.
2357     static const uint16_t XMMArgRegs[] = {
2358       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2359       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2360     };
2361     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2362     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2363            && "SSE registers cannot be used when SSE is disabled");
2364
2365     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2366                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2367     InFlag = Chain.getValue(1);
2368   }
2369
2370
2371   // For tail calls lower the arguments to the 'real' stack slot.
2372   if (isTailCall) {
2373     // Force all the incoming stack arguments to be loaded from the stack
2374     // before any new outgoing arguments are stored to the stack, because the
2375     // outgoing stack slots may alias the incoming argument stack slots, and
2376     // the alias isn't otherwise explicit. This is slightly more conservative
2377     // than necessary, because it means that each store effectively depends
2378     // on every argument instead of just those arguments it would clobber.
2379     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2380
2381     SmallVector<SDValue, 8> MemOpChains2;
2382     SDValue FIN;
2383     int FI = 0;
2384     // Do not flag preceding copytoreg stuff together with the following stuff.
2385     InFlag = SDValue();
2386     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2387       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2388         CCValAssign &VA = ArgLocs[i];
2389         if (VA.isRegLoc())
2390           continue;
2391         assert(VA.isMemLoc());
2392         SDValue Arg = OutVals[i];
2393         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2394         // Create frame index.
2395         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2396         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2397         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2398         FIN = DAG.getFrameIndex(FI, getPointerTy());
2399
2400         if (Flags.isByVal()) {
2401           // Copy relative to framepointer.
2402           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2403           if (StackPtr.getNode() == 0)
2404             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2405                                           getPointerTy());
2406           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2407
2408           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2409                                                            ArgChain,
2410                                                            Flags, DAG, dl));
2411         } else {
2412           // Store relative to framepointer.
2413           MemOpChains2.push_back(
2414             DAG.getStore(ArgChain, dl, Arg, FIN,
2415                          MachinePointerInfo::getFixedStack(FI),
2416                          false, false, 0));
2417         }
2418       }
2419     }
2420
2421     if (!MemOpChains2.empty())
2422       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2423                           &MemOpChains2[0], MemOpChains2.size());
2424
2425     // Copy arguments to their registers.
2426     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2427       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2428                                RegsToPass[i].second, InFlag);
2429       InFlag = Chain.getValue(1);
2430     }
2431     InFlag =SDValue();
2432
2433     // Store the return address to the appropriate stack slot.
2434     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2435                                      FPDiff, dl);
2436   }
2437
2438   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2439     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2440     // In the 64-bit large code model, we have to make all calls
2441     // through a register, since the call instruction's 32-bit
2442     // pc-relative offset may not be large enough to hold the whole
2443     // address.
2444   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2445     // If the callee is a GlobalAddress node (quite common, every direct call
2446     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2447     // it.
2448
2449     // We should use extra load for direct calls to dllimported functions in
2450     // non-JIT mode.
2451     const GlobalValue *GV = G->getGlobal();
2452     if (!GV->hasDLLImportLinkage()) {
2453       unsigned char OpFlags = 0;
2454       bool ExtraLoad = false;
2455       unsigned WrapperKind = ISD::DELETED_NODE;
2456
2457       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2458       // external symbols most go through the PLT in PIC mode.  If the symbol
2459       // has hidden or protected visibility, or if it is static or local, then
2460       // we don't need to use the PLT - we can directly call it.
2461       if (Subtarget->isTargetELF() &&
2462           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2463           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2464         OpFlags = X86II::MO_PLT;
2465       } else if (Subtarget->isPICStyleStubAny() &&
2466                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2467                  (!Subtarget->getTargetTriple().isMacOSX() ||
2468                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2469         // PC-relative references to external symbols should go through $stub,
2470         // unless we're building with the leopard linker or later, which
2471         // automatically synthesizes these stubs.
2472         OpFlags = X86II::MO_DARWIN_STUB;
2473       } else if (Subtarget->isPICStyleRIPRel() &&
2474                  isa<Function>(GV) &&
2475                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2476         // If the function is marked as non-lazy, generate an indirect call
2477         // which loads from the GOT directly. This avoids runtime overhead
2478         // at the cost of eager binding (and one extra byte of encoding).
2479         OpFlags = X86II::MO_GOTPCREL;
2480         WrapperKind = X86ISD::WrapperRIP;
2481         ExtraLoad = true;
2482       }
2483
2484       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2485                                           G->getOffset(), OpFlags);
2486
2487       // Add a wrapper if needed.
2488       if (WrapperKind != ISD::DELETED_NODE)
2489         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2490       // Add extra indirection if needed.
2491       if (ExtraLoad)
2492         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2493                              MachinePointerInfo::getGOT(),
2494                              false, false, false, 0);
2495     }
2496   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2497     unsigned char OpFlags = 0;
2498
2499     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2500     // external symbols should go through the PLT.
2501     if (Subtarget->isTargetELF() &&
2502         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2503       OpFlags = X86II::MO_PLT;
2504     } else if (Subtarget->isPICStyleStubAny() &&
2505                (!Subtarget->getTargetTriple().isMacOSX() ||
2506                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2507       // PC-relative references to external symbols should go through $stub,
2508       // unless we're building with the leopard linker or later, which
2509       // automatically synthesizes these stubs.
2510       OpFlags = X86II::MO_DARWIN_STUB;
2511     }
2512
2513     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2514                                          OpFlags);
2515   }
2516
2517   // Returns a chain & a flag for retval copy to use.
2518   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2519   SmallVector<SDValue, 8> Ops;
2520
2521   if (!IsSibcall && isTailCall) {
2522     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2523                            DAG.getIntPtrConstant(0, true), InFlag);
2524     InFlag = Chain.getValue(1);
2525   }
2526
2527   Ops.push_back(Chain);
2528   Ops.push_back(Callee);
2529
2530   if (isTailCall)
2531     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2532
2533   // Add argument registers to the end of the list so that they are known live
2534   // into the call.
2535   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2536     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2537                                   RegsToPass[i].second.getValueType()));
2538
2539   // Add an implicit use GOT pointer in EBX.
2540   if (!isTailCall && Subtarget->isPICStyleGOT())
2541     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2542
2543   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2544   if (Is64Bit && isVarArg && !IsWin64)
2545     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2546
2547   // Add a register mask operand representing the call-preserved registers.
2548   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2549   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2550   assert(Mask && "Missing call preserved mask for calling convention");
2551   Ops.push_back(DAG.getRegisterMask(Mask));
2552
2553   if (InFlag.getNode())
2554     Ops.push_back(InFlag);
2555
2556   if (isTailCall) {
2557     // We used to do:
2558     //// If this is the first return lowered for this function, add the regs
2559     //// to the liveout set for the function.
2560     // This isn't right, although it's probably harmless on x86; liveouts
2561     // should be computed from returns not tail calls.  Consider a void
2562     // function making a tail call to a function returning int.
2563     return DAG.getNode(X86ISD::TC_RETURN, dl,
2564                        NodeTys, &Ops[0], Ops.size());
2565   }
2566
2567   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2568   InFlag = Chain.getValue(1);
2569
2570   // Create the CALLSEQ_END node.
2571   unsigned NumBytesForCalleeToPush;
2572   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2573                        getTargetMachine().Options.GuaranteedTailCallOpt))
2574     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2575   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2576            IsStructRet)
2577     // If this is a call to a struct-return function, the callee
2578     // pops the hidden struct pointer, so we have to push it back.
2579     // This is common for Darwin/X86, Linux & Mingw32 targets.
2580     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2581     NumBytesForCalleeToPush = 4;
2582   else
2583     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2584
2585   // Returns a flag for retval copy to use.
2586   if (!IsSibcall) {
2587     Chain = DAG.getCALLSEQ_END(Chain,
2588                                DAG.getIntPtrConstant(NumBytes, true),
2589                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2590                                                      true),
2591                                InFlag);
2592     InFlag = Chain.getValue(1);
2593   }
2594
2595   // Handle result values, copying them out of physregs into vregs that we
2596   // return.
2597   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2598                          Ins, dl, DAG, InVals);
2599 }
2600
2601
2602 //===----------------------------------------------------------------------===//
2603 //                Fast Calling Convention (tail call) implementation
2604 //===----------------------------------------------------------------------===//
2605
2606 //  Like std call, callee cleans arguments, convention except that ECX is
2607 //  reserved for storing the tail called function address. Only 2 registers are
2608 //  free for argument passing (inreg). Tail call optimization is performed
2609 //  provided:
2610 //                * tailcallopt is enabled
2611 //                * caller/callee are fastcc
2612 //  On X86_64 architecture with GOT-style position independent code only local
2613 //  (within module) calls are supported at the moment.
2614 //  To keep the stack aligned according to platform abi the function
2615 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2616 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2617 //  If a tail called function callee has more arguments than the caller the
2618 //  caller needs to make sure that there is room to move the RETADDR to. This is
2619 //  achieved by reserving an area the size of the argument delta right after the
2620 //  original REtADDR, but before the saved framepointer or the spilled registers
2621 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2622 //  stack layout:
2623 //    arg1
2624 //    arg2
2625 //    RETADDR
2626 //    [ new RETADDR
2627 //      move area ]
2628 //    (possible EBP)
2629 //    ESI
2630 //    EDI
2631 //    local1 ..
2632
2633 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2634 /// for a 16 byte align requirement.
2635 unsigned
2636 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2637                                                SelectionDAG& DAG) const {
2638   MachineFunction &MF = DAG.getMachineFunction();
2639   const TargetMachine &TM = MF.getTarget();
2640   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2641   unsigned StackAlignment = TFI.getStackAlignment();
2642   uint64_t AlignMask = StackAlignment - 1;
2643   int64_t Offset = StackSize;
2644   uint64_t SlotSize = TD->getPointerSize();
2645   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2646     // Number smaller than 12 so just add the difference.
2647     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2648   } else {
2649     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2650     Offset = ((~AlignMask) & Offset) + StackAlignment +
2651       (StackAlignment-SlotSize);
2652   }
2653   return Offset;
2654 }
2655
2656 /// MatchingStackOffset - Return true if the given stack call argument is
2657 /// already available in the same position (relatively) of the caller's
2658 /// incoming argument stack.
2659 static
2660 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2661                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2662                          const X86InstrInfo *TII) {
2663   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2664   int FI = INT_MAX;
2665   if (Arg.getOpcode() == ISD::CopyFromReg) {
2666     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2667     if (!TargetRegisterInfo::isVirtualRegister(VR))
2668       return false;
2669     MachineInstr *Def = MRI->getVRegDef(VR);
2670     if (!Def)
2671       return false;
2672     if (!Flags.isByVal()) {
2673       if (!TII->isLoadFromStackSlot(Def, FI))
2674         return false;
2675     } else {
2676       unsigned Opcode = Def->getOpcode();
2677       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2678           Def->getOperand(1).isFI()) {
2679         FI = Def->getOperand(1).getIndex();
2680         Bytes = Flags.getByValSize();
2681       } else
2682         return false;
2683     }
2684   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2685     if (Flags.isByVal())
2686       // ByVal argument is passed in as a pointer but it's now being
2687       // dereferenced. e.g.
2688       // define @foo(%struct.X* %A) {
2689       //   tail call @bar(%struct.X* byval %A)
2690       // }
2691       return false;
2692     SDValue Ptr = Ld->getBasePtr();
2693     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2694     if (!FINode)
2695       return false;
2696     FI = FINode->getIndex();
2697   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2698     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2699     FI = FINode->getIndex();
2700     Bytes = Flags.getByValSize();
2701   } else
2702     return false;
2703
2704   assert(FI != INT_MAX);
2705   if (!MFI->isFixedObjectIndex(FI))
2706     return false;
2707   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2708 }
2709
2710 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2711 /// for tail call optimization. Targets which want to do tail call
2712 /// optimization should implement this function.
2713 bool
2714 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2715                                                      CallingConv::ID CalleeCC,
2716                                                      bool isVarArg,
2717                                                      bool isCalleeStructRet,
2718                                                      bool isCallerStructRet,
2719                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2720                                     const SmallVectorImpl<SDValue> &OutVals,
2721                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2722                                                      SelectionDAG& DAG) const {
2723   if (!IsTailCallConvention(CalleeCC) &&
2724       CalleeCC != CallingConv::C)
2725     return false;
2726
2727   // If -tailcallopt is specified, make fastcc functions tail-callable.
2728   const MachineFunction &MF = DAG.getMachineFunction();
2729   const Function *CallerF = DAG.getMachineFunction().getFunction();
2730   CallingConv::ID CallerCC = CallerF->getCallingConv();
2731   bool CCMatch = CallerCC == CalleeCC;
2732
2733   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2734     if (IsTailCallConvention(CalleeCC) && CCMatch)
2735       return true;
2736     return false;
2737   }
2738
2739   // Look for obvious safe cases to perform tail call optimization that do not
2740   // require ABI changes. This is what gcc calls sibcall.
2741
2742   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2743   // emit a special epilogue.
2744   if (RegInfo->needsStackRealignment(MF))
2745     return false;
2746
2747   // Also avoid sibcall optimization if either caller or callee uses struct
2748   // return semantics.
2749   if (isCalleeStructRet || isCallerStructRet)
2750     return false;
2751
2752   // An stdcall caller is expected to clean up its arguments; the callee
2753   // isn't going to do that.
2754   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2755     return false;
2756
2757   // Do not sibcall optimize vararg calls unless all arguments are passed via
2758   // registers.
2759   if (isVarArg && !Outs.empty()) {
2760
2761     // Optimizing for varargs on Win64 is unlikely to be safe without
2762     // additional testing.
2763     if (Subtarget->isTargetWin64())
2764       return false;
2765
2766     SmallVector<CCValAssign, 16> ArgLocs;
2767     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2768                    getTargetMachine(), ArgLocs, *DAG.getContext());
2769
2770     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2771     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2772       if (!ArgLocs[i].isRegLoc())
2773         return false;
2774   }
2775
2776   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2777   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2778   // this into a sibcall.
2779   bool Unused = false;
2780   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2781     if (!Ins[i].Used) {
2782       Unused = true;
2783       break;
2784     }
2785   }
2786   if (Unused) {
2787     SmallVector<CCValAssign, 16> RVLocs;
2788     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2789                    getTargetMachine(), RVLocs, *DAG.getContext());
2790     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2791     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2792       CCValAssign &VA = RVLocs[i];
2793       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2794         return false;
2795     }
2796   }
2797
2798   // If the calling conventions do not match, then we'd better make sure the
2799   // results are returned in the same way as what the caller expects.
2800   if (!CCMatch) {
2801     SmallVector<CCValAssign, 16> RVLocs1;
2802     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2803                     getTargetMachine(), RVLocs1, *DAG.getContext());
2804     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2805
2806     SmallVector<CCValAssign, 16> RVLocs2;
2807     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2808                     getTargetMachine(), RVLocs2, *DAG.getContext());
2809     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2810
2811     if (RVLocs1.size() != RVLocs2.size())
2812       return false;
2813     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2814       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2815         return false;
2816       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2817         return false;
2818       if (RVLocs1[i].isRegLoc()) {
2819         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2820           return false;
2821       } else {
2822         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2823           return false;
2824       }
2825     }
2826   }
2827
2828   // If the callee takes no arguments then go on to check the results of the
2829   // call.
2830   if (!Outs.empty()) {
2831     // Check if stack adjustment is needed. For now, do not do this if any
2832     // argument is passed on the stack.
2833     SmallVector<CCValAssign, 16> ArgLocs;
2834     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2835                    getTargetMachine(), ArgLocs, *DAG.getContext());
2836
2837     // Allocate shadow area for Win64
2838     if (Subtarget->isTargetWin64()) {
2839       CCInfo.AllocateStack(32, 8);
2840     }
2841
2842     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2843     if (CCInfo.getNextStackOffset()) {
2844       MachineFunction &MF = DAG.getMachineFunction();
2845       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2846         return false;
2847
2848       // Check if the arguments are already laid out in the right way as
2849       // the caller's fixed stack objects.
2850       MachineFrameInfo *MFI = MF.getFrameInfo();
2851       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2852       const X86InstrInfo *TII =
2853         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2854       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2855         CCValAssign &VA = ArgLocs[i];
2856         SDValue Arg = OutVals[i];
2857         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2858         if (VA.getLocInfo() == CCValAssign::Indirect)
2859           return false;
2860         if (!VA.isRegLoc()) {
2861           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2862                                    MFI, MRI, TII))
2863             return false;
2864         }
2865       }
2866     }
2867
2868     // If the tailcall address may be in a register, then make sure it's
2869     // possible to register allocate for it. In 32-bit, the call address can
2870     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2871     // callee-saved registers are restored. These happen to be the same
2872     // registers used to pass 'inreg' arguments so watch out for those.
2873     if (!Subtarget->is64Bit() &&
2874         !isa<GlobalAddressSDNode>(Callee) &&
2875         !isa<ExternalSymbolSDNode>(Callee)) {
2876       unsigned NumInRegs = 0;
2877       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2878         CCValAssign &VA = ArgLocs[i];
2879         if (!VA.isRegLoc())
2880           continue;
2881         unsigned Reg = VA.getLocReg();
2882         switch (Reg) {
2883         default: break;
2884         case X86::EAX: case X86::EDX: case X86::ECX:
2885           if (++NumInRegs == 3)
2886             return false;
2887           break;
2888         }
2889       }
2890     }
2891   }
2892
2893   return true;
2894 }
2895
2896 FastISel *
2897 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2898   return X86::createFastISel(funcInfo);
2899 }
2900
2901
2902 //===----------------------------------------------------------------------===//
2903 //                           Other Lowering Hooks
2904 //===----------------------------------------------------------------------===//
2905
2906 static bool MayFoldLoad(SDValue Op) {
2907   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2908 }
2909
2910 static bool MayFoldIntoStore(SDValue Op) {
2911   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2912 }
2913
2914 static bool isTargetShuffle(unsigned Opcode) {
2915   switch(Opcode) {
2916   default: return false;
2917   case X86ISD::PSHUFD:
2918   case X86ISD::PSHUFHW:
2919   case X86ISD::PSHUFLW:
2920   case X86ISD::SHUFP:
2921   case X86ISD::PALIGN:
2922   case X86ISD::MOVLHPS:
2923   case X86ISD::MOVLHPD:
2924   case X86ISD::MOVHLPS:
2925   case X86ISD::MOVLPS:
2926   case X86ISD::MOVLPD:
2927   case X86ISD::MOVSHDUP:
2928   case X86ISD::MOVSLDUP:
2929   case X86ISD::MOVDDUP:
2930   case X86ISD::MOVSS:
2931   case X86ISD::MOVSD:
2932   case X86ISD::UNPCKL:
2933   case X86ISD::UNPCKH:
2934   case X86ISD::VPERMILP:
2935   case X86ISD::VPERM2X128:
2936   case X86ISD::VPERMI:
2937     return true;
2938   }
2939 }
2940
2941 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2942                                     SDValue V1, SelectionDAG &DAG) {
2943   switch(Opc) {
2944   default: llvm_unreachable("Unknown x86 shuffle node");
2945   case X86ISD::MOVSHDUP:
2946   case X86ISD::MOVSLDUP:
2947   case X86ISD::MOVDDUP:
2948     return DAG.getNode(Opc, dl, VT, V1);
2949   }
2950 }
2951
2952 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2953                                     SDValue V1, unsigned TargetMask,
2954                                     SelectionDAG &DAG) {
2955   switch(Opc) {
2956   default: llvm_unreachable("Unknown x86 shuffle node");
2957   case X86ISD::PSHUFD:
2958   case X86ISD::PSHUFHW:
2959   case X86ISD::PSHUFLW:
2960   case X86ISD::VPERMILP:
2961   case X86ISD::VPERMI:
2962     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2963   }
2964 }
2965
2966 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2967                                     SDValue V1, SDValue V2, unsigned TargetMask,
2968                                     SelectionDAG &DAG) {
2969   switch(Opc) {
2970   default: llvm_unreachable("Unknown x86 shuffle node");
2971   case X86ISD::PALIGN:
2972   case X86ISD::SHUFP:
2973   case X86ISD::VPERM2X128:
2974     return DAG.getNode(Opc, dl, VT, V1, V2,
2975                        DAG.getConstant(TargetMask, MVT::i8));
2976   }
2977 }
2978
2979 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2980                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2981   switch(Opc) {
2982   default: llvm_unreachable("Unknown x86 shuffle node");
2983   case X86ISD::MOVLHPS:
2984   case X86ISD::MOVLHPD:
2985   case X86ISD::MOVHLPS:
2986   case X86ISD::MOVLPS:
2987   case X86ISD::MOVLPD:
2988   case X86ISD::MOVSS:
2989   case X86ISD::MOVSD:
2990   case X86ISD::UNPCKL:
2991   case X86ISD::UNPCKH:
2992     return DAG.getNode(Opc, dl, VT, V1, V2);
2993   }
2994 }
2995
2996 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2997   MachineFunction &MF = DAG.getMachineFunction();
2998   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2999   int ReturnAddrIndex = FuncInfo->getRAIndex();
3000
3001   if (ReturnAddrIndex == 0) {
3002     // Set up a frame object for the return address.
3003     uint64_t SlotSize = TD->getPointerSize();
3004     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3005                                                            false);
3006     FuncInfo->setRAIndex(ReturnAddrIndex);
3007   }
3008
3009   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3010 }
3011
3012
3013 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3014                                        bool hasSymbolicDisplacement) {
3015   // Offset should fit into 32 bit immediate field.
3016   if (!isInt<32>(Offset))
3017     return false;
3018
3019   // If we don't have a symbolic displacement - we don't have any extra
3020   // restrictions.
3021   if (!hasSymbolicDisplacement)
3022     return true;
3023
3024   // FIXME: Some tweaks might be needed for medium code model.
3025   if (M != CodeModel::Small && M != CodeModel::Kernel)
3026     return false;
3027
3028   // For small code model we assume that latest object is 16MB before end of 31
3029   // bits boundary. We may also accept pretty large negative constants knowing
3030   // that all objects are in the positive half of address space.
3031   if (M == CodeModel::Small && Offset < 16*1024*1024)
3032     return true;
3033
3034   // For kernel code model we know that all object resist in the negative half
3035   // of 32bits address space. We may not accept negative offsets, since they may
3036   // be just off and we may accept pretty large positive ones.
3037   if (M == CodeModel::Kernel && Offset > 0)
3038     return true;
3039
3040   return false;
3041 }
3042
3043 /// isCalleePop - Determines whether the callee is required to pop its
3044 /// own arguments. Callee pop is necessary to support tail calls.
3045 bool X86::isCalleePop(CallingConv::ID CallingConv,
3046                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3047   if (IsVarArg)
3048     return false;
3049
3050   switch (CallingConv) {
3051   default:
3052     return false;
3053   case CallingConv::X86_StdCall:
3054     return !is64Bit;
3055   case CallingConv::X86_FastCall:
3056     return !is64Bit;
3057   case CallingConv::X86_ThisCall:
3058     return !is64Bit;
3059   case CallingConv::Fast:
3060     return TailCallOpt;
3061   case CallingConv::GHC:
3062     return TailCallOpt;
3063   }
3064 }
3065
3066 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3067 /// specific condition code, returning the condition code and the LHS/RHS of the
3068 /// comparison to make.
3069 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3070                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3071   if (!isFP) {
3072     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3073       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3074         // X > -1   -> X == 0, jump !sign.
3075         RHS = DAG.getConstant(0, RHS.getValueType());
3076         return X86::COND_NS;
3077       }
3078       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3079         // X < 0   -> X == 0, jump on sign.
3080         return X86::COND_S;
3081       }
3082       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3083         // X < 1   -> X <= 0
3084         RHS = DAG.getConstant(0, RHS.getValueType());
3085         return X86::COND_LE;
3086       }
3087     }
3088
3089     switch (SetCCOpcode) {
3090     default: llvm_unreachable("Invalid integer condition!");
3091     case ISD::SETEQ:  return X86::COND_E;
3092     case ISD::SETGT:  return X86::COND_G;
3093     case ISD::SETGE:  return X86::COND_GE;
3094     case ISD::SETLT:  return X86::COND_L;
3095     case ISD::SETLE:  return X86::COND_LE;
3096     case ISD::SETNE:  return X86::COND_NE;
3097     case ISD::SETULT: return X86::COND_B;
3098     case ISD::SETUGT: return X86::COND_A;
3099     case ISD::SETULE: return X86::COND_BE;
3100     case ISD::SETUGE: return X86::COND_AE;
3101     }
3102   }
3103
3104   // First determine if it is required or is profitable to flip the operands.
3105
3106   // If LHS is a foldable load, but RHS is not, flip the condition.
3107   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3108       !ISD::isNON_EXTLoad(RHS.getNode())) {
3109     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3110     std::swap(LHS, RHS);
3111   }
3112
3113   switch (SetCCOpcode) {
3114   default: break;
3115   case ISD::SETOLT:
3116   case ISD::SETOLE:
3117   case ISD::SETUGT:
3118   case ISD::SETUGE:
3119     std::swap(LHS, RHS);
3120     break;
3121   }
3122
3123   // On a floating point condition, the flags are set as follows:
3124   // ZF  PF  CF   op
3125   //  0 | 0 | 0 | X > Y
3126   //  0 | 0 | 1 | X < Y
3127   //  1 | 0 | 0 | X == Y
3128   //  1 | 1 | 1 | unordered
3129   switch (SetCCOpcode) {
3130   default: llvm_unreachable("Condcode should be pre-legalized away");
3131   case ISD::SETUEQ:
3132   case ISD::SETEQ:   return X86::COND_E;
3133   case ISD::SETOLT:              // flipped
3134   case ISD::SETOGT:
3135   case ISD::SETGT:   return X86::COND_A;
3136   case ISD::SETOLE:              // flipped
3137   case ISD::SETOGE:
3138   case ISD::SETGE:   return X86::COND_AE;
3139   case ISD::SETUGT:              // flipped
3140   case ISD::SETULT:
3141   case ISD::SETLT:   return X86::COND_B;
3142   case ISD::SETUGE:              // flipped
3143   case ISD::SETULE:
3144   case ISD::SETLE:   return X86::COND_BE;
3145   case ISD::SETONE:
3146   case ISD::SETNE:   return X86::COND_NE;
3147   case ISD::SETUO:   return X86::COND_P;
3148   case ISD::SETO:    return X86::COND_NP;
3149   case ISD::SETOEQ:
3150   case ISD::SETUNE:  return X86::COND_INVALID;
3151   }
3152 }
3153
3154 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3155 /// code. Current x86 isa includes the following FP cmov instructions:
3156 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3157 static bool hasFPCMov(unsigned X86CC) {
3158   switch (X86CC) {
3159   default:
3160     return false;
3161   case X86::COND_B:
3162   case X86::COND_BE:
3163   case X86::COND_E:
3164   case X86::COND_P:
3165   case X86::COND_A:
3166   case X86::COND_AE:
3167   case X86::COND_NE:
3168   case X86::COND_NP:
3169     return true;
3170   }
3171 }
3172
3173 /// isFPImmLegal - Returns true if the target can instruction select the
3174 /// specified FP immediate natively. If false, the legalizer will
3175 /// materialize the FP immediate as a load from a constant pool.
3176 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3177   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3178     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3179       return true;
3180   }
3181   return false;
3182 }
3183
3184 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3185 /// the specified range (L, H].
3186 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3187   return (Val < 0) || (Val >= Low && Val < Hi);
3188 }
3189
3190 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3191 /// specified value.
3192 static bool isUndefOrEqual(int Val, int CmpVal) {
3193   if (Val < 0 || Val == CmpVal)
3194     return true;
3195   return false;
3196 }
3197
3198 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3199 /// from position Pos and ending in Pos+Size, falls within the specified
3200 /// sequential range (L, L+Pos]. or is undef.
3201 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3202                                        unsigned Pos, unsigned Size, int Low) {
3203   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3204     if (!isUndefOrEqual(Mask[i], Low))
3205       return false;
3206   return true;
3207 }
3208
3209 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3210 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3211 /// the second operand.
3212 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3213   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3214     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3215   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3216     return (Mask[0] < 2 && Mask[1] < 2);
3217   return false;
3218 }
3219
3220 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3221 /// is suitable for input to PSHUFHW.
3222 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3223   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3224     return false;
3225
3226   // Lower quadword copied in order or undef.
3227   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3228     return false;
3229
3230   // Upper quadword shuffled.
3231   for (unsigned i = 4; i != 8; ++i)
3232     if (!isUndefOrInRange(Mask[i], 4, 8))
3233       return false;
3234
3235   if (VT == MVT::v16i16) {
3236     // Lower quadword copied in order or undef.
3237     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3238       return false;
3239
3240     // Upper quadword shuffled.
3241     for (unsigned i = 12; i != 16; ++i)
3242       if (!isUndefOrInRange(Mask[i], 12, 16))
3243         return false;
3244   }
3245
3246   return true;
3247 }
3248
3249 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3250 /// is suitable for input to PSHUFLW.
3251 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3252   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3253     return false;
3254
3255   // Upper quadword copied in order.
3256   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3257     return false;
3258
3259   // Lower quadword shuffled.
3260   for (unsigned i = 0; i != 4; ++i)
3261     if (!isUndefOrInRange(Mask[i], 0, 4))
3262       return false;
3263
3264   if (VT == MVT::v16i16) {
3265     // Upper quadword copied in order.
3266     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3267       return false;
3268
3269     // Lower quadword shuffled.
3270     for (unsigned i = 8; i != 12; ++i)
3271       if (!isUndefOrInRange(Mask[i], 8, 12))
3272         return false;
3273   }
3274
3275   return true;
3276 }
3277
3278 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3279 /// is suitable for input to PALIGNR.
3280 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3281                           const X86Subtarget *Subtarget) {
3282   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3283       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3284     return false;
3285
3286   unsigned NumElts = VT.getVectorNumElements();
3287   unsigned NumLanes = VT.getSizeInBits()/128;
3288   unsigned NumLaneElts = NumElts/NumLanes;
3289
3290   // Do not handle 64-bit element shuffles with palignr.
3291   if (NumLaneElts == 2)
3292     return false;
3293
3294   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3295     unsigned i;
3296     for (i = 0; i != NumLaneElts; ++i) {
3297       if (Mask[i+l] >= 0)
3298         break;
3299     }
3300
3301     // Lane is all undef, go to next lane
3302     if (i == NumLaneElts)
3303       continue;
3304
3305     int Start = Mask[i+l];
3306
3307     // Make sure its in this lane in one of the sources
3308     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3309         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3310       return false;
3311
3312     // If not lane 0, then we must match lane 0
3313     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3314       return false;
3315
3316     // Correct second source to be contiguous with first source
3317     if (Start >= (int)NumElts)
3318       Start -= NumElts - NumLaneElts;
3319
3320     // Make sure we're shifting in the right direction.
3321     if (Start <= (int)(i+l))
3322       return false;
3323
3324     Start -= i;
3325
3326     // Check the rest of the elements to see if they are consecutive.
3327     for (++i; i != NumLaneElts; ++i) {
3328       int Idx = Mask[i+l];
3329
3330       // Make sure its in this lane
3331       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3332           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3333         return false;
3334
3335       // If not lane 0, then we must match lane 0
3336       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3337         return false;
3338
3339       if (Idx >= (int)NumElts)
3340         Idx -= NumElts - NumLaneElts;
3341
3342       if (!isUndefOrEqual(Idx, Start+i))
3343         return false;
3344
3345     }
3346   }
3347
3348   return true;
3349 }
3350
3351 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3352 /// the two vector operands have swapped position.
3353 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3354                                      unsigned NumElems) {
3355   for (unsigned i = 0; i != NumElems; ++i) {
3356     int idx = Mask[i];
3357     if (idx < 0)
3358       continue;
3359     else if (idx < (int)NumElems)
3360       Mask[i] = idx + NumElems;
3361     else
3362       Mask[i] = idx - NumElems;
3363   }
3364 }
3365
3366 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3367 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3368 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3369 /// reverse of what x86 shuffles want.
3370 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3371                         bool Commuted = false) {
3372   if (!HasAVX && VT.getSizeInBits() == 256)
3373     return false;
3374
3375   unsigned NumElems = VT.getVectorNumElements();
3376   unsigned NumLanes = VT.getSizeInBits()/128;
3377   unsigned NumLaneElems = NumElems/NumLanes;
3378
3379   if (NumLaneElems != 2 && NumLaneElems != 4)
3380     return false;
3381
3382   // VSHUFPSY divides the resulting vector into 4 chunks.
3383   // The sources are also splitted into 4 chunks, and each destination
3384   // chunk must come from a different source chunk.
3385   //
3386   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3387   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3388   //
3389   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3390   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3391   //
3392   // VSHUFPDY divides the resulting vector into 4 chunks.
3393   // The sources are also splitted into 4 chunks, and each destination
3394   // chunk must come from a different source chunk.
3395   //
3396   //  SRC1 =>      X3       X2       X1       X0
3397   //  SRC2 =>      Y3       Y2       Y1       Y0
3398   //
3399   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3400   //
3401   unsigned HalfLaneElems = NumLaneElems/2;
3402   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3403     for (unsigned i = 0; i != NumLaneElems; ++i) {
3404       int Idx = Mask[i+l];
3405       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3406       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3407         return false;
3408       // For VSHUFPSY, the mask of the second half must be the same as the
3409       // first but with the appropriate offsets. This works in the same way as
3410       // VPERMILPS works with masks.
3411       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3412         continue;
3413       if (!isUndefOrEqual(Idx, Mask[i]+l))
3414         return false;
3415     }
3416   }
3417
3418   return true;
3419 }
3420
3421 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3422 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3423 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3424   unsigned NumElems = VT.getVectorNumElements();
3425
3426   if (VT.getSizeInBits() != 128)
3427     return false;
3428
3429   if (NumElems != 4)
3430     return false;
3431
3432   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3433   return isUndefOrEqual(Mask[0], 6) &&
3434          isUndefOrEqual(Mask[1], 7) &&
3435          isUndefOrEqual(Mask[2], 2) &&
3436          isUndefOrEqual(Mask[3], 3);
3437 }
3438
3439 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3440 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3441 /// <2, 3, 2, 3>
3442 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3443   unsigned NumElems = VT.getVectorNumElements();
3444
3445   if (VT.getSizeInBits() != 128)
3446     return false;
3447
3448   if (NumElems != 4)
3449     return false;
3450
3451   return isUndefOrEqual(Mask[0], 2) &&
3452          isUndefOrEqual(Mask[1], 3) &&
3453          isUndefOrEqual(Mask[2], 2) &&
3454          isUndefOrEqual(Mask[3], 3);
3455 }
3456
3457 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3458 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3459 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3460   if (VT.getSizeInBits() != 128)
3461     return false;
3462
3463   unsigned NumElems = VT.getVectorNumElements();
3464
3465   if (NumElems != 2 && NumElems != 4)
3466     return false;
3467
3468   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3469     if (!isUndefOrEqual(Mask[i], i + NumElems))
3470       return false;
3471
3472   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3473     if (!isUndefOrEqual(Mask[i], i))
3474       return false;
3475
3476   return true;
3477 }
3478
3479 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3480 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3481 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3482   unsigned NumElems = VT.getVectorNumElements();
3483
3484   if ((NumElems != 2 && NumElems != 4)
3485       || VT.getSizeInBits() > 128)
3486     return false;
3487
3488   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3489     if (!isUndefOrEqual(Mask[i], i))
3490       return false;
3491
3492   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3493     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3494       return false;
3495
3496   return true;
3497 }
3498
3499 //
3500 // Some special combinations that can be optimized.
3501 //
3502 static
3503 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3504                                SelectionDAG &DAG) {
3505   EVT VT = SVOp->getValueType(0);
3506   unsigned NumElts = VT.getVectorNumElements();
3507   DebugLoc dl = SVOp->getDebugLoc();
3508
3509   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3510     return SDValue();
3511
3512   ArrayRef<int> Mask = SVOp->getMask();
3513
3514   // These are the special masks that may be optimized.
3515   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3516   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3517   bool MatchEvenMask = true;
3518   bool MatchOddMask  = true;
3519   for (int i=0; i<8; ++i) {
3520     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3521       MatchEvenMask = false;
3522     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3523       MatchOddMask = false;
3524   }
3525   static const int CompactionMaskEven[] = {0, 2, -1, -1, 4, 6, -1, -1};
3526   static const int CompactionMaskOdd [] = {1, 3, -1, -1, 5, 7, -1, -1};
3527
3528   const int *CompactionMask;
3529   if (MatchEvenMask)
3530     CompactionMask = CompactionMaskEven;
3531   else if (MatchOddMask)
3532     CompactionMask = CompactionMaskOdd;
3533   else
3534     return SDValue();
3535
3536   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3537
3538   SDValue Op0 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(0),
3539                                      UndefNode, CompactionMask);
3540   SDValue Op1 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(1),
3541                                      UndefNode, CompactionMask);
3542   static const int UnpackMask[] = {0, 8, 1, 9, 4, 12, 5, 13};
3543   return DAG.getVectorShuffle(VT, dl, Op0, Op1, UnpackMask);
3544 }
3545
3546 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3547 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3548 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3549                          bool HasAVX2, bool V2IsSplat = false) {
3550   unsigned NumElts = VT.getVectorNumElements();
3551
3552   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3553          "Unsupported vector type for unpckh");
3554
3555   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3556       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3557     return false;
3558
3559   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3560   // independently on 128-bit lanes.
3561   unsigned NumLanes = VT.getSizeInBits()/128;
3562   unsigned NumLaneElts = NumElts/NumLanes;
3563
3564   for (unsigned l = 0; l != NumLanes; ++l) {
3565     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3566          i != (l+1)*NumLaneElts;
3567          i += 2, ++j) {
3568       int BitI  = Mask[i];
3569       int BitI1 = Mask[i+1];
3570       if (!isUndefOrEqual(BitI, j))
3571         return false;
3572       if (V2IsSplat) {
3573         if (!isUndefOrEqual(BitI1, NumElts))
3574           return false;
3575       } else {
3576         if (!isUndefOrEqual(BitI1, j + NumElts))
3577           return false;
3578       }
3579     }
3580   }
3581
3582   return true;
3583 }
3584
3585 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3586 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3587 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3588                          bool HasAVX2, bool V2IsSplat = false) {
3589   unsigned NumElts = VT.getVectorNumElements();
3590
3591   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3592          "Unsupported vector type for unpckh");
3593
3594   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3595       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3596     return false;
3597
3598   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3599   // independently on 128-bit lanes.
3600   unsigned NumLanes = VT.getSizeInBits()/128;
3601   unsigned NumLaneElts = NumElts/NumLanes;
3602
3603   for (unsigned l = 0; l != NumLanes; ++l) {
3604     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3605          i != (l+1)*NumLaneElts; i += 2, ++j) {
3606       int BitI  = Mask[i];
3607       int BitI1 = Mask[i+1];
3608       if (!isUndefOrEqual(BitI, j))
3609         return false;
3610       if (V2IsSplat) {
3611         if (isUndefOrEqual(BitI1, NumElts))
3612           return false;
3613       } else {
3614         if (!isUndefOrEqual(BitI1, j+NumElts))
3615           return false;
3616       }
3617     }
3618   }
3619   return true;
3620 }
3621
3622 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3623 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3624 /// <0, 0, 1, 1>
3625 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3626                                   bool HasAVX2) {
3627   unsigned NumElts = VT.getVectorNumElements();
3628
3629   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3630          "Unsupported vector type for unpckh");
3631
3632   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3633       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3634     return false;
3635
3636   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3637   // FIXME: Need a better way to get rid of this, there's no latency difference
3638   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3639   // the former later. We should also remove the "_undef" special mask.
3640   if (NumElts == 4 && VT.getSizeInBits() == 256)
3641     return false;
3642
3643   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3644   // independently on 128-bit lanes.
3645   unsigned NumLanes = VT.getSizeInBits()/128;
3646   unsigned NumLaneElts = NumElts/NumLanes;
3647
3648   for (unsigned l = 0; l != NumLanes; ++l) {
3649     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3650          i != (l+1)*NumLaneElts;
3651          i += 2, ++j) {
3652       int BitI  = Mask[i];
3653       int BitI1 = Mask[i+1];
3654
3655       if (!isUndefOrEqual(BitI, j))
3656         return false;
3657       if (!isUndefOrEqual(BitI1, j))
3658         return false;
3659     }
3660   }
3661
3662   return true;
3663 }
3664
3665 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3666 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3667 /// <2, 2, 3, 3>
3668 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3669   unsigned NumElts = VT.getVectorNumElements();
3670
3671   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3672          "Unsupported vector type for unpckh");
3673
3674   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3675       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3676     return false;
3677
3678   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3679   // independently on 128-bit lanes.
3680   unsigned NumLanes = VT.getSizeInBits()/128;
3681   unsigned NumLaneElts = NumElts/NumLanes;
3682
3683   for (unsigned l = 0; l != NumLanes; ++l) {
3684     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3685          i != (l+1)*NumLaneElts; i += 2, ++j) {
3686       int BitI  = Mask[i];
3687       int BitI1 = Mask[i+1];
3688       if (!isUndefOrEqual(BitI, j))
3689         return false;
3690       if (!isUndefOrEqual(BitI1, j))
3691         return false;
3692     }
3693   }
3694   return true;
3695 }
3696
3697 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3698 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3699 /// MOVSD, and MOVD, i.e. setting the lowest element.
3700 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3701   if (VT.getVectorElementType().getSizeInBits() < 32)
3702     return false;
3703   if (VT.getSizeInBits() == 256)
3704     return false;
3705
3706   unsigned NumElts = VT.getVectorNumElements();
3707
3708   if (!isUndefOrEqual(Mask[0], NumElts))
3709     return false;
3710
3711   for (unsigned i = 1; i != NumElts; ++i)
3712     if (!isUndefOrEqual(Mask[i], i))
3713       return false;
3714
3715   return true;
3716 }
3717
3718 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3719 /// as permutations between 128-bit chunks or halves. As an example: this
3720 /// shuffle bellow:
3721 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3722 /// The first half comes from the second half of V1 and the second half from the
3723 /// the second half of V2.
3724 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3725   if (!HasAVX || VT.getSizeInBits() != 256)
3726     return false;
3727
3728   // The shuffle result is divided into half A and half B. In total the two
3729   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3730   // B must come from C, D, E or F.
3731   unsigned HalfSize = VT.getVectorNumElements()/2;
3732   bool MatchA = false, MatchB = false;
3733
3734   // Check if A comes from one of C, D, E, F.
3735   for (unsigned Half = 0; Half != 4; ++Half) {
3736     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3737       MatchA = true;
3738       break;
3739     }
3740   }
3741
3742   // Check if B comes from one of C, D, E, F.
3743   for (unsigned Half = 0; Half != 4; ++Half) {
3744     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3745       MatchB = true;
3746       break;
3747     }
3748   }
3749
3750   return MatchA && MatchB;
3751 }
3752
3753 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3754 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3755 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3756   EVT VT = SVOp->getValueType(0);
3757
3758   unsigned HalfSize = VT.getVectorNumElements()/2;
3759
3760   unsigned FstHalf = 0, SndHalf = 0;
3761   for (unsigned i = 0; i < HalfSize; ++i) {
3762     if (SVOp->getMaskElt(i) > 0) {
3763       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3764       break;
3765     }
3766   }
3767   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3768     if (SVOp->getMaskElt(i) > 0) {
3769       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3770       break;
3771     }
3772   }
3773
3774   return (FstHalf | (SndHalf << 4));
3775 }
3776
3777 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3778 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3779 /// Note that VPERMIL mask matching is different depending whether theunderlying
3780 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3781 /// to the same elements of the low, but to the higher half of the source.
3782 /// In VPERMILPD the two lanes could be shuffled independently of each other
3783 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3784 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3785   if (!HasAVX)
3786     return false;
3787
3788   unsigned NumElts = VT.getVectorNumElements();
3789   // Only match 256-bit with 32/64-bit types
3790   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3791     return false;
3792
3793   unsigned NumLanes = VT.getSizeInBits()/128;
3794   unsigned LaneSize = NumElts/NumLanes;
3795   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3796     for (unsigned i = 0; i != LaneSize; ++i) {
3797       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3798         return false;
3799       if (NumElts != 8 || l == 0)
3800         continue;
3801       // VPERMILPS handling
3802       if (Mask[i] < 0)
3803         continue;
3804       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3805         return false;
3806     }
3807   }
3808
3809   return true;
3810 }
3811
3812 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3813 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3814 /// element of vector 2 and the other elements to come from vector 1 in order.
3815 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3816                                bool V2IsSplat = false, bool V2IsUndef = false) {
3817   unsigned NumOps = VT.getVectorNumElements();
3818   if (VT.getSizeInBits() == 256)
3819     return false;
3820   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3821     return false;
3822
3823   if (!isUndefOrEqual(Mask[0], 0))
3824     return false;
3825
3826   for (unsigned i = 1; i != NumOps; ++i)
3827     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3828           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3829           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3830       return false;
3831
3832   return true;
3833 }
3834
3835 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3836 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3837 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3838 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3839                            const X86Subtarget *Subtarget) {
3840   if (!Subtarget->hasSSE3())
3841     return false;
3842
3843   unsigned NumElems = VT.getVectorNumElements();
3844
3845   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3846       (VT.getSizeInBits() == 256 && NumElems != 8))
3847     return false;
3848
3849   // "i+1" is the value the indexed mask element must have
3850   for (unsigned i = 0; i != NumElems; i += 2)
3851     if (!isUndefOrEqual(Mask[i], i+1) ||
3852         !isUndefOrEqual(Mask[i+1], i+1))
3853       return false;
3854
3855   return true;
3856 }
3857
3858 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3859 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3860 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3861 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3862                            const X86Subtarget *Subtarget) {
3863   if (!Subtarget->hasSSE3())
3864     return false;
3865
3866   unsigned NumElems = VT.getVectorNumElements();
3867
3868   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3869       (VT.getSizeInBits() == 256 && NumElems != 8))
3870     return false;
3871
3872   // "i" is the value the indexed mask element must have
3873   for (unsigned i = 0; i != NumElems; i += 2)
3874     if (!isUndefOrEqual(Mask[i], i) ||
3875         !isUndefOrEqual(Mask[i+1], i))
3876       return false;
3877
3878   return true;
3879 }
3880
3881 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3882 /// specifies a shuffle of elements that is suitable for input to 256-bit
3883 /// version of MOVDDUP.
3884 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3885   unsigned NumElts = VT.getVectorNumElements();
3886
3887   if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3888     return false;
3889
3890   for (unsigned i = 0; i != NumElts/2; ++i)
3891     if (!isUndefOrEqual(Mask[i], 0))
3892       return false;
3893   for (unsigned i = NumElts/2; i != NumElts; ++i)
3894     if (!isUndefOrEqual(Mask[i], NumElts/2))
3895       return false;
3896   return true;
3897 }
3898
3899 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3900 /// specifies a shuffle of elements that is suitable for input to 128-bit
3901 /// version of MOVDDUP.
3902 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3903   if (VT.getSizeInBits() != 128)
3904     return false;
3905
3906   unsigned e = VT.getVectorNumElements() / 2;
3907   for (unsigned i = 0; i != e; ++i)
3908     if (!isUndefOrEqual(Mask[i], i))
3909       return false;
3910   for (unsigned i = 0; i != e; ++i)
3911     if (!isUndefOrEqual(Mask[e+i], i))
3912       return false;
3913   return true;
3914 }
3915
3916 /// isVEXTRACTF128Index - Return true if the specified
3917 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3918 /// suitable for input to VEXTRACTF128.
3919 bool X86::isVEXTRACTF128Index(SDNode *N) {
3920   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3921     return false;
3922
3923   // The index should be aligned on a 128-bit boundary.
3924   uint64_t Index =
3925     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3926
3927   unsigned VL = N->getValueType(0).getVectorNumElements();
3928   unsigned VBits = N->getValueType(0).getSizeInBits();
3929   unsigned ElSize = VBits / VL;
3930   bool Result = (Index * ElSize) % 128 == 0;
3931
3932   return Result;
3933 }
3934
3935 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3936 /// operand specifies a subvector insert that is suitable for input to
3937 /// VINSERTF128.
3938 bool X86::isVINSERTF128Index(SDNode *N) {
3939   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3940     return false;
3941
3942   // The index should be aligned on a 128-bit boundary.
3943   uint64_t Index =
3944     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3945
3946   unsigned VL = N->getValueType(0).getVectorNumElements();
3947   unsigned VBits = N->getValueType(0).getSizeInBits();
3948   unsigned ElSize = VBits / VL;
3949   bool Result = (Index * ElSize) % 128 == 0;
3950
3951   return Result;
3952 }
3953
3954 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3955 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3956 /// Handles 128-bit and 256-bit.
3957 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3958   EVT VT = N->getValueType(0);
3959
3960   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3961          "Unsupported vector type for PSHUF/SHUFP");
3962
3963   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3964   // independently on 128-bit lanes.
3965   unsigned NumElts = VT.getVectorNumElements();
3966   unsigned NumLanes = VT.getSizeInBits()/128;
3967   unsigned NumLaneElts = NumElts/NumLanes;
3968
3969   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3970          "Only supports 2 or 4 elements per lane");
3971
3972   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3973   unsigned Mask = 0;
3974   for (unsigned i = 0; i != NumElts; ++i) {
3975     int Elt = N->getMaskElt(i);
3976     if (Elt < 0) continue;
3977     Elt &= NumLaneElts - 1;
3978     unsigned ShAmt = (i << Shift) % 8;
3979     Mask |= Elt << ShAmt;
3980   }
3981
3982   return Mask;
3983 }
3984
3985 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3986 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3987 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3988   EVT VT = N->getValueType(0);
3989
3990   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3991          "Unsupported vector type for PSHUFHW");
3992
3993   unsigned NumElts = VT.getVectorNumElements();
3994
3995   unsigned Mask = 0;
3996   for (unsigned l = 0; l != NumElts; l += 8) {
3997     // 8 nodes per lane, but we only care about the last 4.
3998     for (unsigned i = 0; i < 4; ++i) {
3999       int Elt = N->getMaskElt(l+i+4);
4000       if (Elt < 0) continue;
4001       Elt &= 0x3; // only 2-bits.
4002       Mask |= Elt << (i * 2);
4003     }
4004   }
4005
4006   return Mask;
4007 }
4008
4009 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4010 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4011 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4012   EVT VT = N->getValueType(0);
4013
4014   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4015          "Unsupported vector type for PSHUFHW");
4016
4017   unsigned NumElts = VT.getVectorNumElements();
4018
4019   unsigned Mask = 0;
4020   for (unsigned l = 0; l != NumElts; l += 8) {
4021     // 8 nodes per lane, but we only care about the first 4.
4022     for (unsigned i = 0; i < 4; ++i) {
4023       int Elt = N->getMaskElt(l+i);
4024       if (Elt < 0) continue;
4025       Elt &= 0x3; // only 2-bits
4026       Mask |= Elt << (i * 2);
4027     }
4028   }
4029
4030   return Mask;
4031 }
4032
4033 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4034 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4035 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4036   EVT VT = SVOp->getValueType(0);
4037   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4038
4039   unsigned NumElts = VT.getVectorNumElements();
4040   unsigned NumLanes = VT.getSizeInBits()/128;
4041   unsigned NumLaneElts = NumElts/NumLanes;
4042
4043   int Val = 0;
4044   unsigned i;
4045   for (i = 0; i != NumElts; ++i) {
4046     Val = SVOp->getMaskElt(i);
4047     if (Val >= 0)
4048       break;
4049   }
4050   if (Val >= (int)NumElts)
4051     Val -= NumElts - NumLaneElts;
4052
4053   assert(Val - i > 0 && "PALIGNR imm should be positive");
4054   return (Val - i) * EltSize;
4055 }
4056
4057 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4058 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4059 /// instructions.
4060 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4061   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4062     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4063
4064   uint64_t Index =
4065     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4066
4067   EVT VecVT = N->getOperand(0).getValueType();
4068   EVT ElVT = VecVT.getVectorElementType();
4069
4070   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4071   return Index / NumElemsPerChunk;
4072 }
4073
4074 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4075 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4076 /// instructions.
4077 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4078   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4079     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4080
4081   uint64_t Index =
4082     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4083
4084   EVT VecVT = N->getValueType(0);
4085   EVT ElVT = VecVT.getVectorElementType();
4086
4087   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4088   return Index / NumElemsPerChunk;
4089 }
4090
4091 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4092 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4093 /// Handles 256-bit.
4094 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4095   EVT VT = N->getValueType(0);
4096
4097   unsigned NumElts = VT.getVectorNumElements();
4098
4099   assert((VT.is256BitVector() && NumElts == 4) &&
4100          "Unsupported vector type for VPERMQ/VPERMPD");
4101
4102   unsigned Mask = 0;
4103   for (unsigned i = 0; i != NumElts; ++i) {
4104     int Elt = N->getMaskElt(i);
4105     if (Elt < 0)
4106       continue;
4107     Mask |= Elt << (i*2);
4108   }
4109
4110   return Mask;
4111 }
4112 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4113 /// constant +0.0.
4114 bool X86::isZeroNode(SDValue Elt) {
4115   return ((isa<ConstantSDNode>(Elt) &&
4116            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4117           (isa<ConstantFPSDNode>(Elt) &&
4118            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4119 }
4120
4121 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4122 /// their permute mask.
4123 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4124                                     SelectionDAG &DAG) {
4125   EVT VT = SVOp->getValueType(0);
4126   unsigned NumElems = VT.getVectorNumElements();
4127   SmallVector<int, 8> MaskVec;
4128
4129   for (unsigned i = 0; i != NumElems; ++i) {
4130     int Idx = SVOp->getMaskElt(i);
4131     if (Idx >= 0) {
4132       if (Idx < (int)NumElems)
4133         Idx += NumElems;
4134       else
4135         Idx -= NumElems;
4136     }
4137     MaskVec.push_back(Idx);
4138   }
4139   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4140                               SVOp->getOperand(0), &MaskVec[0]);
4141 }
4142
4143 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4144 /// match movhlps. The lower half elements should come from upper half of
4145 /// V1 (and in order), and the upper half elements should come from the upper
4146 /// half of V2 (and in order).
4147 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4148   if (VT.getSizeInBits() != 128)
4149     return false;
4150   if (VT.getVectorNumElements() != 4)
4151     return false;
4152   for (unsigned i = 0, e = 2; i != e; ++i)
4153     if (!isUndefOrEqual(Mask[i], i+2))
4154       return false;
4155   for (unsigned i = 2; i != 4; ++i)
4156     if (!isUndefOrEqual(Mask[i], i+4))
4157       return false;
4158   return true;
4159 }
4160
4161 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4162 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4163 /// required.
4164 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4165   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4166     return false;
4167   N = N->getOperand(0).getNode();
4168   if (!ISD::isNON_EXTLoad(N))
4169     return false;
4170   if (LD)
4171     *LD = cast<LoadSDNode>(N);
4172   return true;
4173 }
4174
4175 // Test whether the given value is a vector value which will be legalized
4176 // into a load.
4177 static bool WillBeConstantPoolLoad(SDNode *N) {
4178   if (N->getOpcode() != ISD::BUILD_VECTOR)
4179     return false;
4180
4181   // Check for any non-constant elements.
4182   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4183     switch (N->getOperand(i).getNode()->getOpcode()) {
4184     case ISD::UNDEF:
4185     case ISD::ConstantFP:
4186     case ISD::Constant:
4187       break;
4188     default:
4189       return false;
4190     }
4191
4192   // Vectors of all-zeros and all-ones are materialized with special
4193   // instructions rather than being loaded.
4194   return !ISD::isBuildVectorAllZeros(N) &&
4195          !ISD::isBuildVectorAllOnes(N);
4196 }
4197
4198 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4199 /// match movlp{s|d}. The lower half elements should come from lower half of
4200 /// V1 (and in order), and the upper half elements should come from the upper
4201 /// half of V2 (and in order). And since V1 will become the source of the
4202 /// MOVLP, it must be either a vector load or a scalar load to vector.
4203 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4204                                ArrayRef<int> Mask, EVT VT) {
4205   if (VT.getSizeInBits() != 128)
4206     return false;
4207
4208   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4209     return false;
4210   // Is V2 is a vector load, don't do this transformation. We will try to use
4211   // load folding shufps op.
4212   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4213     return false;
4214
4215   unsigned NumElems = VT.getVectorNumElements();
4216
4217   if (NumElems != 2 && NumElems != 4)
4218     return false;
4219   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4220     if (!isUndefOrEqual(Mask[i], i))
4221       return false;
4222   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4223     if (!isUndefOrEqual(Mask[i], i+NumElems))
4224       return false;
4225   return true;
4226 }
4227
4228 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4229 /// all the same.
4230 static bool isSplatVector(SDNode *N) {
4231   if (N->getOpcode() != ISD::BUILD_VECTOR)
4232     return false;
4233
4234   SDValue SplatValue = N->getOperand(0);
4235   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4236     if (N->getOperand(i) != SplatValue)
4237       return false;
4238   return true;
4239 }
4240
4241 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4242 /// to an zero vector.
4243 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4244 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4245   SDValue V1 = N->getOperand(0);
4246   SDValue V2 = N->getOperand(1);
4247   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4248   for (unsigned i = 0; i != NumElems; ++i) {
4249     int Idx = N->getMaskElt(i);
4250     if (Idx >= (int)NumElems) {
4251       unsigned Opc = V2.getOpcode();
4252       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4253         continue;
4254       if (Opc != ISD::BUILD_VECTOR ||
4255           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4256         return false;
4257     } else if (Idx >= 0) {
4258       unsigned Opc = V1.getOpcode();
4259       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4260         continue;
4261       if (Opc != ISD::BUILD_VECTOR ||
4262           !X86::isZeroNode(V1.getOperand(Idx)))
4263         return false;
4264     }
4265   }
4266   return true;
4267 }
4268
4269 /// getZeroVector - Returns a vector of specified type with all zero elements.
4270 ///
4271 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4272                              SelectionDAG &DAG, DebugLoc dl) {
4273   assert(VT.isVector() && "Expected a vector type");
4274   unsigned Size = VT.getSizeInBits();
4275
4276   // Always build SSE zero vectors as <4 x i32> bitcasted
4277   // to their dest type. This ensures they get CSE'd.
4278   SDValue Vec;
4279   if (Size == 128) {  // SSE
4280     if (Subtarget->hasSSE2()) {  // SSE2
4281       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4282       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4283     } else { // SSE1
4284       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4285       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4286     }
4287   } else if (Size == 256) { // AVX
4288     if (Subtarget->hasAVX2()) { // AVX2
4289       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4290       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4291       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4292     } else {
4293       // 256-bit logic and arithmetic instructions in AVX are all
4294       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4295       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4296       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4297       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4298     }
4299   } else
4300     llvm_unreachable("Unexpected vector type");
4301
4302   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4303 }
4304
4305 /// getOnesVector - Returns a vector of specified type with all bits set.
4306 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4307 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4308 /// Then bitcast to their original type, ensuring they get CSE'd.
4309 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4310                              DebugLoc dl) {
4311   assert(VT.isVector() && "Expected a vector type");
4312   unsigned Size = VT.getSizeInBits();
4313
4314   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4315   SDValue Vec;
4316   if (Size == 256) {
4317     if (HasAVX2) { // AVX2
4318       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4319       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4320     } else { // AVX
4321       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4322       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4323     }
4324   } else if (Size == 128) {
4325     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4326   } else
4327     llvm_unreachable("Unexpected vector type");
4328
4329   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4330 }
4331
4332 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4333 /// that point to V2 points to its first element.
4334 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4335   for (unsigned i = 0; i != NumElems; ++i) {
4336     if (Mask[i] > (int)NumElems) {
4337       Mask[i] = NumElems;
4338     }
4339   }
4340 }
4341
4342 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4343 /// operation of specified width.
4344 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4345                        SDValue V2) {
4346   unsigned NumElems = VT.getVectorNumElements();
4347   SmallVector<int, 8> Mask;
4348   Mask.push_back(NumElems);
4349   for (unsigned i = 1; i != NumElems; ++i)
4350     Mask.push_back(i);
4351   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4352 }
4353
4354 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4355 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4356                           SDValue V2) {
4357   unsigned NumElems = VT.getVectorNumElements();
4358   SmallVector<int, 8> Mask;
4359   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4360     Mask.push_back(i);
4361     Mask.push_back(i + NumElems);
4362   }
4363   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4364 }
4365
4366 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4367 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4368                           SDValue V2) {
4369   unsigned NumElems = VT.getVectorNumElements();
4370   SmallVector<int, 8> Mask;
4371   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4372     Mask.push_back(i + Half);
4373     Mask.push_back(i + NumElems + Half);
4374   }
4375   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4376 }
4377
4378 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4379 // a generic shuffle instruction because the target has no such instructions.
4380 // Generate shuffles which repeat i16 and i8 several times until they can be
4381 // represented by v4f32 and then be manipulated by target suported shuffles.
4382 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4383   EVT VT = V.getValueType();
4384   int NumElems = VT.getVectorNumElements();
4385   DebugLoc dl = V.getDebugLoc();
4386
4387   while (NumElems > 4) {
4388     if (EltNo < NumElems/2) {
4389       V = getUnpackl(DAG, dl, VT, V, V);
4390     } else {
4391       V = getUnpackh(DAG, dl, VT, V, V);
4392       EltNo -= NumElems/2;
4393     }
4394     NumElems >>= 1;
4395   }
4396   return V;
4397 }
4398
4399 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4400 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4401   EVT VT = V.getValueType();
4402   DebugLoc dl = V.getDebugLoc();
4403   unsigned Size = VT.getSizeInBits();
4404
4405   if (Size == 128) {
4406     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4407     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4408     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4409                              &SplatMask[0]);
4410   } else if (Size == 256) {
4411     // To use VPERMILPS to splat scalars, the second half of indicies must
4412     // refer to the higher part, which is a duplication of the lower one,
4413     // because VPERMILPS can only handle in-lane permutations.
4414     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4415                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4416
4417     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4418     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4419                              &SplatMask[0]);
4420   } else
4421     llvm_unreachable("Vector size not supported");
4422
4423   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4424 }
4425
4426 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4427 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4428   EVT SrcVT = SV->getValueType(0);
4429   SDValue V1 = SV->getOperand(0);
4430   DebugLoc dl = SV->getDebugLoc();
4431
4432   int EltNo = SV->getSplatIndex();
4433   int NumElems = SrcVT.getVectorNumElements();
4434   unsigned Size = SrcVT.getSizeInBits();
4435
4436   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4437           "Unknown how to promote splat for type");
4438
4439   // Extract the 128-bit part containing the splat element and update
4440   // the splat element index when it refers to the higher register.
4441   if (Size == 256) {
4442     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4443     if (EltNo >= NumElems/2)
4444       EltNo -= NumElems/2;
4445   }
4446
4447   // All i16 and i8 vector types can't be used directly by a generic shuffle
4448   // instruction because the target has no such instruction. Generate shuffles
4449   // which repeat i16 and i8 several times until they fit in i32, and then can
4450   // be manipulated by target suported shuffles.
4451   EVT EltVT = SrcVT.getVectorElementType();
4452   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4453     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4454
4455   // Recreate the 256-bit vector and place the same 128-bit vector
4456   // into the low and high part. This is necessary because we want
4457   // to use VPERM* to shuffle the vectors
4458   if (Size == 256) {
4459     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4460   }
4461
4462   return getLegalSplat(DAG, V1, EltNo);
4463 }
4464
4465 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4466 /// vector of zero or undef vector.  This produces a shuffle where the low
4467 /// element of V2 is swizzled into the zero/undef vector, landing at element
4468 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4469 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4470                                            bool IsZero,
4471                                            const X86Subtarget *Subtarget,
4472                                            SelectionDAG &DAG) {
4473   EVT VT = V2.getValueType();
4474   SDValue V1 = IsZero
4475     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4476   unsigned NumElems = VT.getVectorNumElements();
4477   SmallVector<int, 16> MaskVec;
4478   for (unsigned i = 0; i != NumElems; ++i)
4479     // If this is the insertion idx, put the low elt of V2 here.
4480     MaskVec.push_back(i == Idx ? NumElems : i);
4481   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4482 }
4483
4484 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4485 /// target specific opcode. Returns true if the Mask could be calculated.
4486 /// Sets IsUnary to true if only uses one source.
4487 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4488                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4489   unsigned NumElems = VT.getVectorNumElements();
4490   SDValue ImmN;
4491
4492   IsUnary = false;
4493   switch(N->getOpcode()) {
4494   case X86ISD::SHUFP:
4495     ImmN = N->getOperand(N->getNumOperands()-1);
4496     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4497     break;
4498   case X86ISD::UNPCKH:
4499     DecodeUNPCKHMask(VT, Mask);
4500     break;
4501   case X86ISD::UNPCKL:
4502     DecodeUNPCKLMask(VT, Mask);
4503     break;
4504   case X86ISD::MOVHLPS:
4505     DecodeMOVHLPSMask(NumElems, Mask);
4506     break;
4507   case X86ISD::MOVLHPS:
4508     DecodeMOVLHPSMask(NumElems, Mask);
4509     break;
4510   case X86ISD::PSHUFD:
4511   case X86ISD::VPERMILP:
4512     ImmN = N->getOperand(N->getNumOperands()-1);
4513     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4514     IsUnary = true;
4515     break;
4516   case X86ISD::PSHUFHW:
4517     ImmN = N->getOperand(N->getNumOperands()-1);
4518     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4519     IsUnary = true;
4520     break;
4521   case X86ISD::PSHUFLW:
4522     ImmN = N->getOperand(N->getNumOperands()-1);
4523     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4524     IsUnary = true;
4525     break;
4526   case X86ISD::VPERMI:
4527     ImmN = N->getOperand(N->getNumOperands()-1);
4528     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4529     IsUnary = true;
4530     break;
4531   case X86ISD::MOVSS:
4532   case X86ISD::MOVSD: {
4533     // The index 0 always comes from the first element of the second source,
4534     // this is why MOVSS and MOVSD are used in the first place. The other
4535     // elements come from the other positions of the first source vector
4536     Mask.push_back(NumElems);
4537     for (unsigned i = 1; i != NumElems; ++i) {
4538       Mask.push_back(i);
4539     }
4540     break;
4541   }
4542   case X86ISD::VPERM2X128:
4543     ImmN = N->getOperand(N->getNumOperands()-1);
4544     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4545     if (Mask.empty()) return false;
4546     break;
4547   case X86ISD::MOVDDUP:
4548   case X86ISD::MOVLHPD:
4549   case X86ISD::MOVLPD:
4550   case X86ISD::MOVLPS:
4551   case X86ISD::MOVSHDUP:
4552   case X86ISD::MOVSLDUP:
4553   case X86ISD::PALIGN:
4554     // Not yet implemented
4555     return false;
4556   default: llvm_unreachable("unknown target shuffle node");
4557   }
4558
4559   return true;
4560 }
4561
4562 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4563 /// element of the result of the vector shuffle.
4564 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4565                                    unsigned Depth) {
4566   if (Depth == 6)
4567     return SDValue();  // Limit search depth.
4568
4569   SDValue V = SDValue(N, 0);
4570   EVT VT = V.getValueType();
4571   unsigned Opcode = V.getOpcode();
4572
4573   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4574   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4575     int Elt = SV->getMaskElt(Index);
4576
4577     if (Elt < 0)
4578       return DAG.getUNDEF(VT.getVectorElementType());
4579
4580     unsigned NumElems = VT.getVectorNumElements();
4581     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4582                                          : SV->getOperand(1);
4583     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4584   }
4585
4586   // Recurse into target specific vector shuffles to find scalars.
4587   if (isTargetShuffle(Opcode)) {
4588     MVT ShufVT = V.getValueType().getSimpleVT();
4589     unsigned NumElems = ShufVT.getVectorNumElements();
4590     SmallVector<int, 16> ShuffleMask;
4591     SDValue ImmN;
4592     bool IsUnary;
4593
4594     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4595       return SDValue();
4596
4597     int Elt = ShuffleMask[Index];
4598     if (Elt < 0)
4599       return DAG.getUNDEF(ShufVT.getVectorElementType());
4600
4601     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4602                                          : N->getOperand(1);
4603     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4604                                Depth+1);
4605   }
4606
4607   // Actual nodes that may contain scalar elements
4608   if (Opcode == ISD::BITCAST) {
4609     V = V.getOperand(0);
4610     EVT SrcVT = V.getValueType();
4611     unsigned NumElems = VT.getVectorNumElements();
4612
4613     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4614       return SDValue();
4615   }
4616
4617   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4618     return (Index == 0) ? V.getOperand(0)
4619                         : DAG.getUNDEF(VT.getVectorElementType());
4620
4621   if (V.getOpcode() == ISD::BUILD_VECTOR)
4622     return V.getOperand(Index);
4623
4624   return SDValue();
4625 }
4626
4627 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4628 /// shuffle operation which come from a consecutively from a zero. The
4629 /// search can start in two different directions, from left or right.
4630 static
4631 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4632                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4633   unsigned i;
4634   for (i = 0; i != NumElems; ++i) {
4635     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4636     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4637     if (!(Elt.getNode() &&
4638          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4639       break;
4640   }
4641
4642   return i;
4643 }
4644
4645 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4646 /// correspond consecutively to elements from one of the vector operands,
4647 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4648 static
4649 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4650                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4651                               unsigned NumElems, unsigned &OpNum) {
4652   bool SeenV1 = false;
4653   bool SeenV2 = false;
4654
4655   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4656     int Idx = SVOp->getMaskElt(i);
4657     // Ignore undef indicies
4658     if (Idx < 0)
4659       continue;
4660
4661     if (Idx < (int)NumElems)
4662       SeenV1 = true;
4663     else
4664       SeenV2 = true;
4665
4666     // Only accept consecutive elements from the same vector
4667     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4668       return false;
4669   }
4670
4671   OpNum = SeenV1 ? 0 : 1;
4672   return true;
4673 }
4674
4675 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4676 /// logical left shift of a vector.
4677 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4678                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4679   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4680   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4681               false /* check zeros from right */, DAG);
4682   unsigned OpSrc;
4683
4684   if (!NumZeros)
4685     return false;
4686
4687   // Considering the elements in the mask that are not consecutive zeros,
4688   // check if they consecutively come from only one of the source vectors.
4689   //
4690   //               V1 = {X, A, B, C}     0
4691   //                         \  \  \    /
4692   //   vector_shuffle V1, V2 <1, 2, 3, X>
4693   //
4694   if (!isShuffleMaskConsecutive(SVOp,
4695             0,                   // Mask Start Index
4696             NumElems-NumZeros,   // Mask End Index(exclusive)
4697             NumZeros,            // Where to start looking in the src vector
4698             NumElems,            // Number of elements in vector
4699             OpSrc))              // Which source operand ?
4700     return false;
4701
4702   isLeft = false;
4703   ShAmt = NumZeros;
4704   ShVal = SVOp->getOperand(OpSrc);
4705   return true;
4706 }
4707
4708 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4709 /// logical left shift of a vector.
4710 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4711                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4712   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4713   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4714               true /* check zeros from left */, DAG);
4715   unsigned OpSrc;
4716
4717   if (!NumZeros)
4718     return false;
4719
4720   // Considering the elements in the mask that are not consecutive zeros,
4721   // check if they consecutively come from only one of the source vectors.
4722   //
4723   //                           0    { A, B, X, X } = V2
4724   //                          / \    /  /
4725   //   vector_shuffle V1, V2 <X, X, 4, 5>
4726   //
4727   if (!isShuffleMaskConsecutive(SVOp,
4728             NumZeros,     // Mask Start Index
4729             NumElems,     // Mask End Index(exclusive)
4730             0,            // Where to start looking in the src vector
4731             NumElems,     // Number of elements in vector
4732             OpSrc))       // Which source operand ?
4733     return false;
4734
4735   isLeft = true;
4736   ShAmt = NumZeros;
4737   ShVal = SVOp->getOperand(OpSrc);
4738   return true;
4739 }
4740
4741 /// isVectorShift - Returns true if the shuffle can be implemented as a
4742 /// logical left or right shift of a vector.
4743 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4744                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4745   // Although the logic below support any bitwidth size, there are no
4746   // shift instructions which handle more than 128-bit vectors.
4747   if (SVOp->getValueType(0).getSizeInBits() > 128)
4748     return false;
4749
4750   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4751       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4752     return true;
4753
4754   return false;
4755 }
4756
4757 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4758 ///
4759 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4760                                        unsigned NumNonZero, unsigned NumZero,
4761                                        SelectionDAG &DAG,
4762                                        const X86Subtarget* Subtarget,
4763                                        const TargetLowering &TLI) {
4764   if (NumNonZero > 8)
4765     return SDValue();
4766
4767   DebugLoc dl = Op.getDebugLoc();
4768   SDValue V(0, 0);
4769   bool First = true;
4770   for (unsigned i = 0; i < 16; ++i) {
4771     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4772     if (ThisIsNonZero && First) {
4773       if (NumZero)
4774         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4775       else
4776         V = DAG.getUNDEF(MVT::v8i16);
4777       First = false;
4778     }
4779
4780     if ((i & 1) != 0) {
4781       SDValue ThisElt(0, 0), LastElt(0, 0);
4782       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4783       if (LastIsNonZero) {
4784         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4785                               MVT::i16, Op.getOperand(i-1));
4786       }
4787       if (ThisIsNonZero) {
4788         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4789         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4790                               ThisElt, DAG.getConstant(8, MVT::i8));
4791         if (LastIsNonZero)
4792           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4793       } else
4794         ThisElt = LastElt;
4795
4796       if (ThisElt.getNode())
4797         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4798                         DAG.getIntPtrConstant(i/2));
4799     }
4800   }
4801
4802   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4803 }
4804
4805 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4806 ///
4807 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4808                                      unsigned NumNonZero, unsigned NumZero,
4809                                      SelectionDAG &DAG,
4810                                      const X86Subtarget* Subtarget,
4811                                      const TargetLowering &TLI) {
4812   if (NumNonZero > 4)
4813     return SDValue();
4814
4815   DebugLoc dl = Op.getDebugLoc();
4816   SDValue V(0, 0);
4817   bool First = true;
4818   for (unsigned i = 0; i < 8; ++i) {
4819     bool isNonZero = (NonZeros & (1 << i)) != 0;
4820     if (isNonZero) {
4821       if (First) {
4822         if (NumZero)
4823           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4824         else
4825           V = DAG.getUNDEF(MVT::v8i16);
4826         First = false;
4827       }
4828       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4829                       MVT::v8i16, V, Op.getOperand(i),
4830                       DAG.getIntPtrConstant(i));
4831     }
4832   }
4833
4834   return V;
4835 }
4836
4837 /// getVShift - Return a vector logical shift node.
4838 ///
4839 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4840                          unsigned NumBits, SelectionDAG &DAG,
4841                          const TargetLowering &TLI, DebugLoc dl) {
4842   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4843   EVT ShVT = MVT::v2i64;
4844   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4845   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4846   return DAG.getNode(ISD::BITCAST, dl, VT,
4847                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4848                              DAG.getConstant(NumBits,
4849                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4850 }
4851
4852 SDValue
4853 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4854                                           SelectionDAG &DAG) const {
4855
4856   // Check if the scalar load can be widened into a vector load. And if
4857   // the address is "base + cst" see if the cst can be "absorbed" into
4858   // the shuffle mask.
4859   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4860     SDValue Ptr = LD->getBasePtr();
4861     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4862       return SDValue();
4863     EVT PVT = LD->getValueType(0);
4864     if (PVT != MVT::i32 && PVT != MVT::f32)
4865       return SDValue();
4866
4867     int FI = -1;
4868     int64_t Offset = 0;
4869     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4870       FI = FINode->getIndex();
4871       Offset = 0;
4872     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4873                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4874       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4875       Offset = Ptr.getConstantOperandVal(1);
4876       Ptr = Ptr.getOperand(0);
4877     } else {
4878       return SDValue();
4879     }
4880
4881     // FIXME: 256-bit vector instructions don't require a strict alignment,
4882     // improve this code to support it better.
4883     unsigned RequiredAlign = VT.getSizeInBits()/8;
4884     SDValue Chain = LD->getChain();
4885     // Make sure the stack object alignment is at least 16 or 32.
4886     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4887     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4888       if (MFI->isFixedObjectIndex(FI)) {
4889         // Can't change the alignment. FIXME: It's possible to compute
4890         // the exact stack offset and reference FI + adjust offset instead.
4891         // If someone *really* cares about this. That's the way to implement it.
4892         return SDValue();
4893       } else {
4894         MFI->setObjectAlignment(FI, RequiredAlign);
4895       }
4896     }
4897
4898     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4899     // Ptr + (Offset & ~15).
4900     if (Offset < 0)
4901       return SDValue();
4902     if ((Offset % RequiredAlign) & 3)
4903       return SDValue();
4904     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4905     if (StartOffset)
4906       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4907                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4908
4909     int EltNo = (Offset - StartOffset) >> 2;
4910     unsigned NumElems = VT.getVectorNumElements();
4911
4912     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4913     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4914                              LD->getPointerInfo().getWithOffset(StartOffset),
4915                              false, false, false, 0);
4916
4917     SmallVector<int, 8> Mask;
4918     for (unsigned i = 0; i != NumElems; ++i)
4919       Mask.push_back(EltNo);
4920
4921     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4922   }
4923
4924   return SDValue();
4925 }
4926
4927 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4928 /// vector of type 'VT', see if the elements can be replaced by a single large
4929 /// load which has the same value as a build_vector whose operands are 'elts'.
4930 ///
4931 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4932 ///
4933 /// FIXME: we'd also like to handle the case where the last elements are zero
4934 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4935 /// There's even a handy isZeroNode for that purpose.
4936 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4937                                         DebugLoc &DL, SelectionDAG &DAG) {
4938   EVT EltVT = VT.getVectorElementType();
4939   unsigned NumElems = Elts.size();
4940
4941   LoadSDNode *LDBase = NULL;
4942   unsigned LastLoadedElt = -1U;
4943
4944   // For each element in the initializer, see if we've found a load or an undef.
4945   // If we don't find an initial load element, or later load elements are
4946   // non-consecutive, bail out.
4947   for (unsigned i = 0; i < NumElems; ++i) {
4948     SDValue Elt = Elts[i];
4949
4950     if (!Elt.getNode() ||
4951         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4952       return SDValue();
4953     if (!LDBase) {
4954       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4955         return SDValue();
4956       LDBase = cast<LoadSDNode>(Elt.getNode());
4957       LastLoadedElt = i;
4958       continue;
4959     }
4960     if (Elt.getOpcode() == ISD::UNDEF)
4961       continue;
4962
4963     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4964     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4965       return SDValue();
4966     LastLoadedElt = i;
4967   }
4968
4969   // If we have found an entire vector of loads and undefs, then return a large
4970   // load of the entire vector width starting at the base pointer.  If we found
4971   // consecutive loads for the low half, generate a vzext_load node.
4972   if (LastLoadedElt == NumElems - 1) {
4973     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4974       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4975                          LDBase->getPointerInfo(),
4976                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4977                          LDBase->isInvariant(), 0);
4978     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4979                        LDBase->getPointerInfo(),
4980                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4981                        LDBase->isInvariant(), LDBase->getAlignment());
4982   }
4983   if (NumElems == 4 && LastLoadedElt == 1 &&
4984       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4985     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4986     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4987     SDValue ResNode =
4988         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4989                                 LDBase->getPointerInfo(),
4990                                 LDBase->getAlignment(),
4991                                 false/*isVolatile*/, true/*ReadMem*/,
4992                                 false/*WriteMem*/);
4993     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4994   }
4995   return SDValue();
4996 }
4997
4998 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4999 /// to generate a splat value for the following cases:
5000 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5001 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5002 /// a scalar load, or a constant.
5003 /// The VBROADCAST node is returned when a pattern is found,
5004 /// or SDValue() otherwise.
5005 SDValue
5006 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
5007   if (!Subtarget->hasAVX())
5008     return SDValue();
5009
5010   EVT VT = Op.getValueType();
5011   DebugLoc dl = Op.getDebugLoc();
5012
5013   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5014          "Unsupported vector type for broadcast.");
5015
5016   SDValue Ld;
5017   bool ConstSplatVal;
5018
5019   switch (Op.getOpcode()) {
5020     default:
5021       // Unknown pattern found.
5022       return SDValue();
5023
5024     case ISD::BUILD_VECTOR: {
5025       // The BUILD_VECTOR node must be a splat.
5026       if (!isSplatVector(Op.getNode()))
5027         return SDValue();
5028
5029       Ld = Op.getOperand(0);
5030       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5031                      Ld.getOpcode() == ISD::ConstantFP);
5032
5033       // The suspected load node has several users. Make sure that all
5034       // of its users are from the BUILD_VECTOR node.
5035       // Constants may have multiple users.
5036       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5037         return SDValue();
5038       break;
5039     }
5040
5041     case ISD::VECTOR_SHUFFLE: {
5042       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5043
5044       // Shuffles must have a splat mask where the first element is
5045       // broadcasted.
5046       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5047         return SDValue();
5048
5049       SDValue Sc = Op.getOperand(0);
5050       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5051           Sc.getOpcode() != ISD::BUILD_VECTOR)
5052         return SDValue();
5053
5054       Ld = Sc.getOperand(0);
5055       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5056                        Ld.getOpcode() == ISD::ConstantFP);
5057
5058       // The scalar_to_vector node and the suspected
5059       // load node must have exactly one user.
5060       // Constants may have multiple users.
5061       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5062         return SDValue();
5063       break;
5064     }
5065   }
5066
5067   bool Is256 = VT.getSizeInBits() == 256;
5068
5069   // Handle the broadcasting a single constant scalar from the constant pool
5070   // into a vector. On Sandybridge it is still better to load a constant vector
5071   // from the constant pool and not to broadcast it from a scalar.
5072   if (ConstSplatVal && Subtarget->hasAVX2()) {
5073     EVT CVT = Ld.getValueType();
5074     assert(!CVT.isVector() && "Must not broadcast a vector type");
5075     unsigned ScalarSize = CVT.getSizeInBits();
5076
5077     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5078       const Constant *C = 0;
5079       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5080         C = CI->getConstantIntValue();
5081       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5082         C = CF->getConstantFPValue();
5083
5084       assert(C && "Invalid constant type");
5085
5086       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5087       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5088       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5089                        MachinePointerInfo::getConstantPool(),
5090                        false, false, false, Alignment);
5091
5092       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5093     }
5094   }
5095
5096   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5097   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5098
5099   // Handle AVX2 in-register broadcasts.
5100   if (!IsLoad && Subtarget->hasAVX2() &&
5101       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5102     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5103
5104   // The scalar source must be a normal load.
5105   if (!IsLoad)
5106     return SDValue();
5107
5108   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5109     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5110
5111   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5112   // double since there is no vbroadcastsd xmm
5113   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5114     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5115       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5116   }
5117
5118   // Unsupported broadcast.
5119   return SDValue();
5120 }
5121
5122 SDValue
5123 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5124   DebugLoc dl = Op.getDebugLoc();
5125
5126   EVT VT = Op.getValueType();
5127   EVT ExtVT = VT.getVectorElementType();
5128   unsigned NumElems = Op.getNumOperands();
5129
5130   // Vectors containing all zeros can be matched by pxor and xorps later
5131   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5132     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5133     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5134     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5135       return Op;
5136
5137     return getZeroVector(VT, Subtarget, DAG, dl);
5138   }
5139
5140   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5141   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5142   // vpcmpeqd on 256-bit vectors.
5143   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5144     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5145       return Op;
5146
5147     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5148   }
5149
5150   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5151   if (Broadcast.getNode())
5152     return Broadcast;
5153
5154   unsigned EVTBits = ExtVT.getSizeInBits();
5155
5156   unsigned NumZero  = 0;
5157   unsigned NumNonZero = 0;
5158   unsigned NonZeros = 0;
5159   bool IsAllConstants = true;
5160   SmallSet<SDValue, 8> Values;
5161   for (unsigned i = 0; i < NumElems; ++i) {
5162     SDValue Elt = Op.getOperand(i);
5163     if (Elt.getOpcode() == ISD::UNDEF)
5164       continue;
5165     Values.insert(Elt);
5166     if (Elt.getOpcode() != ISD::Constant &&
5167         Elt.getOpcode() != ISD::ConstantFP)
5168       IsAllConstants = false;
5169     if (X86::isZeroNode(Elt))
5170       NumZero++;
5171     else {
5172       NonZeros |= (1 << i);
5173       NumNonZero++;
5174     }
5175   }
5176
5177   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5178   if (NumNonZero == 0)
5179     return DAG.getUNDEF(VT);
5180
5181   // Special case for single non-zero, non-undef, element.
5182   if (NumNonZero == 1) {
5183     unsigned Idx = CountTrailingZeros_32(NonZeros);
5184     SDValue Item = Op.getOperand(Idx);
5185
5186     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5187     // the value are obviously zero, truncate the value to i32 and do the
5188     // insertion that way.  Only do this if the value is non-constant or if the
5189     // value is a constant being inserted into element 0.  It is cheaper to do
5190     // a constant pool load than it is to do a movd + shuffle.
5191     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5192         (!IsAllConstants || Idx == 0)) {
5193       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5194         // Handle SSE only.
5195         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5196         EVT VecVT = MVT::v4i32;
5197         unsigned VecElts = 4;
5198
5199         // Truncate the value (which may itself be a constant) to i32, and
5200         // convert it to a vector with movd (S2V+shuffle to zero extend).
5201         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5202         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5203         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5204
5205         // Now we have our 32-bit value zero extended in the low element of
5206         // a vector.  If Idx != 0, swizzle it into place.
5207         if (Idx != 0) {
5208           SmallVector<int, 4> Mask;
5209           Mask.push_back(Idx);
5210           for (unsigned i = 1; i != VecElts; ++i)
5211             Mask.push_back(i);
5212           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5213                                       &Mask[0]);
5214         }
5215         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5216       }
5217     }
5218
5219     // If we have a constant or non-constant insertion into the low element of
5220     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5221     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5222     // depending on what the source datatype is.
5223     if (Idx == 0) {
5224       if (NumZero == 0)
5225         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5226
5227       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5228           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5229         if (VT.getSizeInBits() == 256) {
5230           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5231           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5232                              Item, DAG.getIntPtrConstant(0));
5233         }
5234         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5235         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5236         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5237         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5238       }
5239
5240       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5241         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5242         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5243         if (VT.getSizeInBits() == 256) {
5244           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5245           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5246         } else {
5247           assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5248           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5249         }
5250         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5251       }
5252     }
5253
5254     // Is it a vector logical left shift?
5255     if (NumElems == 2 && Idx == 1 &&
5256         X86::isZeroNode(Op.getOperand(0)) &&
5257         !X86::isZeroNode(Op.getOperand(1))) {
5258       unsigned NumBits = VT.getSizeInBits();
5259       return getVShift(true, VT,
5260                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5261                                    VT, Op.getOperand(1)),
5262                        NumBits/2, DAG, *this, dl);
5263     }
5264
5265     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5266       return SDValue();
5267
5268     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5269     // is a non-constant being inserted into an element other than the low one,
5270     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5271     // movd/movss) to move this into the low element, then shuffle it into
5272     // place.
5273     if (EVTBits == 32) {
5274       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5275
5276       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5277       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5278       SmallVector<int, 8> MaskVec;
5279       for (unsigned i = 0; i != NumElems; ++i)
5280         MaskVec.push_back(i == Idx ? 0 : 1);
5281       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5282     }
5283   }
5284
5285   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5286   if (Values.size() == 1) {
5287     if (EVTBits == 32) {
5288       // Instead of a shuffle like this:
5289       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5290       // Check if it's possible to issue this instead.
5291       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5292       unsigned Idx = CountTrailingZeros_32(NonZeros);
5293       SDValue Item = Op.getOperand(Idx);
5294       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5295         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5296     }
5297     return SDValue();
5298   }
5299
5300   // A vector full of immediates; various special cases are already
5301   // handled, so this is best done with a single constant-pool load.
5302   if (IsAllConstants)
5303     return SDValue();
5304
5305   // For AVX-length vectors, build the individual 128-bit pieces and use
5306   // shuffles to put them in place.
5307   if (VT.getSizeInBits() == 256) {
5308     SmallVector<SDValue, 32> V;
5309     for (unsigned i = 0; i != NumElems; ++i)
5310       V.push_back(Op.getOperand(i));
5311
5312     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5313
5314     // Build both the lower and upper subvector.
5315     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5316     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5317                                 NumElems/2);
5318
5319     // Recreate the wider vector with the lower and upper part.
5320     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5321   }
5322
5323   // Let legalizer expand 2-wide build_vectors.
5324   if (EVTBits == 64) {
5325     if (NumNonZero == 1) {
5326       // One half is zero or undef.
5327       unsigned Idx = CountTrailingZeros_32(NonZeros);
5328       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5329                                  Op.getOperand(Idx));
5330       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5331     }
5332     return SDValue();
5333   }
5334
5335   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5336   if (EVTBits == 8 && NumElems == 16) {
5337     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5338                                         Subtarget, *this);
5339     if (V.getNode()) return V;
5340   }
5341
5342   if (EVTBits == 16 && NumElems == 8) {
5343     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5344                                       Subtarget, *this);
5345     if (V.getNode()) return V;
5346   }
5347
5348   // If element VT is == 32 bits, turn it into a number of shuffles.
5349   SmallVector<SDValue, 8> V(NumElems);
5350   if (NumElems == 4 && NumZero > 0) {
5351     for (unsigned i = 0; i < 4; ++i) {
5352       bool isZero = !(NonZeros & (1 << i));
5353       if (isZero)
5354         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5355       else
5356         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5357     }
5358
5359     for (unsigned i = 0; i < 2; ++i) {
5360       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5361         default: break;
5362         case 0:
5363           V[i] = V[i*2];  // Must be a zero vector.
5364           break;
5365         case 1:
5366           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5367           break;
5368         case 2:
5369           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5370           break;
5371         case 3:
5372           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5373           break;
5374       }
5375     }
5376
5377     bool Reverse1 = (NonZeros & 0x3) == 2;
5378     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5379     int MaskVec[] = {
5380       Reverse1 ? 1 : 0,
5381       Reverse1 ? 0 : 1,
5382       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5383       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5384     };
5385     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5386   }
5387
5388   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5389     // Check for a build vector of consecutive loads.
5390     for (unsigned i = 0; i < NumElems; ++i)
5391       V[i] = Op.getOperand(i);
5392
5393     // Check for elements which are consecutive loads.
5394     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5395     if (LD.getNode())
5396       return LD;
5397
5398     // For SSE 4.1, use insertps to put the high elements into the low element.
5399     if (getSubtarget()->hasSSE41()) {
5400       SDValue Result;
5401       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5402         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5403       else
5404         Result = DAG.getUNDEF(VT);
5405
5406       for (unsigned i = 1; i < NumElems; ++i) {
5407         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5408         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5409                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5410       }
5411       return Result;
5412     }
5413
5414     // Otherwise, expand into a number of unpckl*, start by extending each of
5415     // our (non-undef) elements to the full vector width with the element in the
5416     // bottom slot of the vector (which generates no code for SSE).
5417     for (unsigned i = 0; i < NumElems; ++i) {
5418       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5419         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5420       else
5421         V[i] = DAG.getUNDEF(VT);
5422     }
5423
5424     // Next, we iteratively mix elements, e.g. for v4f32:
5425     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5426     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5427     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5428     unsigned EltStride = NumElems >> 1;
5429     while (EltStride != 0) {
5430       for (unsigned i = 0; i < EltStride; ++i) {
5431         // If V[i+EltStride] is undef and this is the first round of mixing,
5432         // then it is safe to just drop this shuffle: V[i] is already in the
5433         // right place, the one element (since it's the first round) being
5434         // inserted as undef can be dropped.  This isn't safe for successive
5435         // rounds because they will permute elements within both vectors.
5436         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5437             EltStride == NumElems/2)
5438           continue;
5439
5440         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5441       }
5442       EltStride >>= 1;
5443     }
5444     return V[0];
5445   }
5446   return SDValue();
5447 }
5448
5449 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5450 // them in a MMX register.  This is better than doing a stack convert.
5451 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5452   DebugLoc dl = Op.getDebugLoc();
5453   EVT ResVT = Op.getValueType();
5454
5455   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5456          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5457   int Mask[2];
5458   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5459   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5460   InVec = Op.getOperand(1);
5461   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5462     unsigned NumElts = ResVT.getVectorNumElements();
5463     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5464     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5465                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5466   } else {
5467     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5468     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5469     Mask[0] = 0; Mask[1] = 2;
5470     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5471   }
5472   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5473 }
5474
5475 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5476 // to create 256-bit vectors from two other 128-bit ones.
5477 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5478   DebugLoc dl = Op.getDebugLoc();
5479   EVT ResVT = Op.getValueType();
5480
5481   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5482
5483   SDValue V1 = Op.getOperand(0);
5484   SDValue V2 = Op.getOperand(1);
5485   unsigned NumElems = ResVT.getVectorNumElements();
5486
5487   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5488 }
5489
5490 SDValue
5491 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5492   EVT ResVT = Op.getValueType();
5493
5494   assert(Op.getNumOperands() == 2);
5495   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5496          "Unsupported CONCAT_VECTORS for value type");
5497
5498   // We support concatenate two MMX registers and place them in a MMX register.
5499   // This is better than doing a stack convert.
5500   if (ResVT.is128BitVector())
5501     return LowerMMXCONCAT_VECTORS(Op, DAG);
5502
5503   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5504   // from two other 128-bit ones.
5505   return LowerAVXCONCAT_VECTORS(Op, DAG);
5506 }
5507
5508 // Try to lower a shuffle node into a simple blend instruction.
5509 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5510                                           const X86Subtarget *Subtarget,
5511                                           SelectionDAG &DAG) {
5512   SDValue V1 = SVOp->getOperand(0);
5513   SDValue V2 = SVOp->getOperand(1);
5514   DebugLoc dl = SVOp->getDebugLoc();
5515   MVT VT = SVOp->getValueType(0).getSimpleVT();
5516   unsigned NumElems = VT.getVectorNumElements();
5517
5518   if (!Subtarget->hasSSE41())
5519     return SDValue();
5520
5521   unsigned ISDNo = 0;
5522   MVT OpTy;
5523
5524   switch (VT.SimpleTy) {
5525   default: return SDValue();
5526   case MVT::v8i16:
5527     ISDNo = X86ISD::BLENDPW;
5528     OpTy = MVT::v8i16;
5529     break;
5530   case MVT::v4i32:
5531   case MVT::v4f32:
5532     ISDNo = X86ISD::BLENDPS;
5533     OpTy = MVT::v4f32;
5534     break;
5535   case MVT::v2i64:
5536   case MVT::v2f64:
5537     ISDNo = X86ISD::BLENDPD;
5538     OpTy = MVT::v2f64;
5539     break;
5540   case MVT::v8i32:
5541   case MVT::v8f32:
5542     if (!Subtarget->hasAVX())
5543       return SDValue();
5544     ISDNo = X86ISD::BLENDPS;
5545     OpTy = MVT::v8f32;
5546     break;
5547   case MVT::v4i64:
5548   case MVT::v4f64:
5549     if (!Subtarget->hasAVX())
5550       return SDValue();
5551     ISDNo = X86ISD::BLENDPD;
5552     OpTy = MVT::v4f64;
5553     break;
5554   }
5555   assert(ISDNo && "Invalid Op Number");
5556
5557   unsigned MaskVals = 0;
5558
5559   for (unsigned i = 0; i != NumElems; ++i) {
5560     int EltIdx = SVOp->getMaskElt(i);
5561     if (EltIdx == (int)i || EltIdx < 0)
5562       MaskVals |= (1<<i);
5563     else if (EltIdx == (int)(i + NumElems))
5564       continue; // Bit is set to zero;
5565     else
5566       return SDValue();
5567   }
5568
5569   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5570   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5571   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5572                              DAG.getConstant(MaskVals, MVT::i32));
5573   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5574 }
5575
5576 // v8i16 shuffles - Prefer shuffles in the following order:
5577 // 1. [all]   pshuflw, pshufhw, optional move
5578 // 2. [ssse3] 1 x pshufb
5579 // 3. [ssse3] 2 x pshufb + 1 x por
5580 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5581 SDValue
5582 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5583                                             SelectionDAG &DAG) const {
5584   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5585   SDValue V1 = SVOp->getOperand(0);
5586   SDValue V2 = SVOp->getOperand(1);
5587   DebugLoc dl = SVOp->getDebugLoc();
5588   SmallVector<int, 8> MaskVals;
5589
5590   // Determine if more than 1 of the words in each of the low and high quadwords
5591   // of the result come from the same quadword of one of the two inputs.  Undef
5592   // mask values count as coming from any quadword, for better codegen.
5593   unsigned LoQuad[] = { 0, 0, 0, 0 };
5594   unsigned HiQuad[] = { 0, 0, 0, 0 };
5595   std::bitset<4> InputQuads;
5596   for (unsigned i = 0; i < 8; ++i) {
5597     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5598     int EltIdx = SVOp->getMaskElt(i);
5599     MaskVals.push_back(EltIdx);
5600     if (EltIdx < 0) {
5601       ++Quad[0];
5602       ++Quad[1];
5603       ++Quad[2];
5604       ++Quad[3];
5605       continue;
5606     }
5607     ++Quad[EltIdx / 4];
5608     InputQuads.set(EltIdx / 4);
5609   }
5610
5611   int BestLoQuad = -1;
5612   unsigned MaxQuad = 1;
5613   for (unsigned i = 0; i < 4; ++i) {
5614     if (LoQuad[i] > MaxQuad) {
5615       BestLoQuad = i;
5616       MaxQuad = LoQuad[i];
5617     }
5618   }
5619
5620   int BestHiQuad = -1;
5621   MaxQuad = 1;
5622   for (unsigned i = 0; i < 4; ++i) {
5623     if (HiQuad[i] > MaxQuad) {
5624       BestHiQuad = i;
5625       MaxQuad = HiQuad[i];
5626     }
5627   }
5628
5629   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5630   // of the two input vectors, shuffle them into one input vector so only a
5631   // single pshufb instruction is necessary. If There are more than 2 input
5632   // quads, disable the next transformation since it does not help SSSE3.
5633   bool V1Used = InputQuads[0] || InputQuads[1];
5634   bool V2Used = InputQuads[2] || InputQuads[3];
5635   if (Subtarget->hasSSSE3()) {
5636     if (InputQuads.count() == 2 && V1Used && V2Used) {
5637       BestLoQuad = InputQuads[0] ? 0 : 1;
5638       BestHiQuad = InputQuads[2] ? 2 : 3;
5639     }
5640     if (InputQuads.count() > 2) {
5641       BestLoQuad = -1;
5642       BestHiQuad = -1;
5643     }
5644   }
5645
5646   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5647   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5648   // words from all 4 input quadwords.
5649   SDValue NewV;
5650   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5651     int MaskV[] = {
5652       BestLoQuad < 0 ? 0 : BestLoQuad,
5653       BestHiQuad < 0 ? 1 : BestHiQuad
5654     };
5655     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5656                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5657                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5658     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5659
5660     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5661     // source words for the shuffle, to aid later transformations.
5662     bool AllWordsInNewV = true;
5663     bool InOrder[2] = { true, true };
5664     for (unsigned i = 0; i != 8; ++i) {
5665       int idx = MaskVals[i];
5666       if (idx != (int)i)
5667         InOrder[i/4] = false;
5668       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5669         continue;
5670       AllWordsInNewV = false;
5671       break;
5672     }
5673
5674     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5675     if (AllWordsInNewV) {
5676       for (int i = 0; i != 8; ++i) {
5677         int idx = MaskVals[i];
5678         if (idx < 0)
5679           continue;
5680         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5681         if ((idx != i) && idx < 4)
5682           pshufhw = false;
5683         if ((idx != i) && idx > 3)
5684           pshuflw = false;
5685       }
5686       V1 = NewV;
5687       V2Used = false;
5688       BestLoQuad = 0;
5689       BestHiQuad = 1;
5690     }
5691
5692     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5693     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5694     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5695       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5696       unsigned TargetMask = 0;
5697       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5698                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5699       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5700       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5701                              getShufflePSHUFLWImmediate(SVOp);
5702       V1 = NewV.getOperand(0);
5703       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5704     }
5705   }
5706
5707   // If we have SSSE3, and all words of the result are from 1 input vector,
5708   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5709   // is present, fall back to case 4.
5710   if (Subtarget->hasSSSE3()) {
5711     SmallVector<SDValue,16> pshufbMask;
5712
5713     // If we have elements from both input vectors, set the high bit of the
5714     // shuffle mask element to zero out elements that come from V2 in the V1
5715     // mask, and elements that come from V1 in the V2 mask, so that the two
5716     // results can be OR'd together.
5717     bool TwoInputs = V1Used && V2Used;
5718     for (unsigned i = 0; i != 8; ++i) {
5719       int EltIdx = MaskVals[i] * 2;
5720       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5721       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5722       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5723       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5724     }
5725     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5726     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5727                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5728                                  MVT::v16i8, &pshufbMask[0], 16));
5729     if (!TwoInputs)
5730       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5731
5732     // Calculate the shuffle mask for the second input, shuffle it, and
5733     // OR it with the first shuffled input.
5734     pshufbMask.clear();
5735     for (unsigned i = 0; i != 8; ++i) {
5736       int EltIdx = MaskVals[i] * 2;
5737       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5738       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5739       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5740       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5741     }
5742     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5743     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5744                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5745                                  MVT::v16i8, &pshufbMask[0], 16));
5746     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5747     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5748   }
5749
5750   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5751   // and update MaskVals with new element order.
5752   std::bitset<8> InOrder;
5753   if (BestLoQuad >= 0) {
5754     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5755     for (int i = 0; i != 4; ++i) {
5756       int idx = MaskVals[i];
5757       if (idx < 0) {
5758         InOrder.set(i);
5759       } else if ((idx / 4) == BestLoQuad) {
5760         MaskV[i] = idx & 3;
5761         InOrder.set(i);
5762       }
5763     }
5764     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5765                                 &MaskV[0]);
5766
5767     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5768       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5769       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5770                                   NewV.getOperand(0),
5771                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5772     }
5773   }
5774
5775   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5776   // and update MaskVals with the new element order.
5777   if (BestHiQuad >= 0) {
5778     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5779     for (unsigned i = 4; i != 8; ++i) {
5780       int idx = MaskVals[i];
5781       if (idx < 0) {
5782         InOrder.set(i);
5783       } else if ((idx / 4) == BestHiQuad) {
5784         MaskV[i] = (idx & 3) + 4;
5785         InOrder.set(i);
5786       }
5787     }
5788     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5789                                 &MaskV[0]);
5790
5791     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5792       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5793       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5794                                   NewV.getOperand(0),
5795                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5796     }
5797   }
5798
5799   // In case BestHi & BestLo were both -1, which means each quadword has a word
5800   // from each of the four input quadwords, calculate the InOrder bitvector now
5801   // before falling through to the insert/extract cleanup.
5802   if (BestLoQuad == -1 && BestHiQuad == -1) {
5803     NewV = V1;
5804     for (int i = 0; i != 8; ++i)
5805       if (MaskVals[i] < 0 || MaskVals[i] == i)
5806         InOrder.set(i);
5807   }
5808
5809   // The other elements are put in the right place using pextrw and pinsrw.
5810   for (unsigned i = 0; i != 8; ++i) {
5811     if (InOrder[i])
5812       continue;
5813     int EltIdx = MaskVals[i];
5814     if (EltIdx < 0)
5815       continue;
5816     SDValue ExtOp = (EltIdx < 8) ?
5817       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5818                   DAG.getIntPtrConstant(EltIdx)) :
5819       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5820                   DAG.getIntPtrConstant(EltIdx - 8));
5821     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5822                        DAG.getIntPtrConstant(i));
5823   }
5824   return NewV;
5825 }
5826
5827 // v16i8 shuffles - Prefer shuffles in the following order:
5828 // 1. [ssse3] 1 x pshufb
5829 // 2. [ssse3] 2 x pshufb + 1 x por
5830 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5831 static
5832 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5833                                  SelectionDAG &DAG,
5834                                  const X86TargetLowering &TLI) {
5835   SDValue V1 = SVOp->getOperand(0);
5836   SDValue V2 = SVOp->getOperand(1);
5837   DebugLoc dl = SVOp->getDebugLoc();
5838   ArrayRef<int> MaskVals = SVOp->getMask();
5839
5840   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5841
5842   // If we have SSSE3, case 1 is generated when all result bytes come from
5843   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5844   // present, fall back to case 3.
5845
5846   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5847   if (TLI.getSubtarget()->hasSSSE3()) {
5848     SmallVector<SDValue,16> pshufbMask;
5849
5850     // If all result elements are from one input vector, then only translate
5851     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5852     //
5853     // Otherwise, we have elements from both input vectors, and must zero out
5854     // elements that come from V2 in the first mask, and V1 in the second mask
5855     // so that we can OR them together.
5856     for (unsigned i = 0; i != 16; ++i) {
5857       int EltIdx = MaskVals[i];
5858       if (EltIdx < 0 || EltIdx >= 16)
5859         EltIdx = 0x80;
5860       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5861     }
5862     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5863                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5864                                  MVT::v16i8, &pshufbMask[0], 16));
5865     if (V2IsUndef)
5866       return V1;
5867
5868     // Calculate the shuffle mask for the second input, shuffle it, and
5869     // OR it with the first shuffled input.
5870     pshufbMask.clear();
5871     for (unsigned i = 0; i != 16; ++i) {
5872       int EltIdx = MaskVals[i];
5873       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5874       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5875     }
5876     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5877                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5878                                  MVT::v16i8, &pshufbMask[0], 16));
5879     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5880   }
5881
5882   // No SSSE3 - Calculate in place words and then fix all out of place words
5883   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5884   // the 16 different words that comprise the two doublequadword input vectors.
5885   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5886   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5887   SDValue NewV = V1;
5888   for (int i = 0; i != 8; ++i) {
5889     int Elt0 = MaskVals[i*2];
5890     int Elt1 = MaskVals[i*2+1];
5891
5892     // This word of the result is all undef, skip it.
5893     if (Elt0 < 0 && Elt1 < 0)
5894       continue;
5895
5896     // This word of the result is already in the correct place, skip it.
5897     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5898       continue;
5899
5900     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5901     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5902     SDValue InsElt;
5903
5904     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5905     // using a single extract together, load it and store it.
5906     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5907       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5908                            DAG.getIntPtrConstant(Elt1 / 2));
5909       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5910                         DAG.getIntPtrConstant(i));
5911       continue;
5912     }
5913
5914     // If Elt1 is defined, extract it from the appropriate source.  If the
5915     // source byte is not also odd, shift the extracted word left 8 bits
5916     // otherwise clear the bottom 8 bits if we need to do an or.
5917     if (Elt1 >= 0) {
5918       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5919                            DAG.getIntPtrConstant(Elt1 / 2));
5920       if ((Elt1 & 1) == 0)
5921         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5922                              DAG.getConstant(8,
5923                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5924       else if (Elt0 >= 0)
5925         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5926                              DAG.getConstant(0xFF00, MVT::i16));
5927     }
5928     // If Elt0 is defined, extract it from the appropriate source.  If the
5929     // source byte is not also even, shift the extracted word right 8 bits. If
5930     // Elt1 was also defined, OR the extracted values together before
5931     // inserting them in the result.
5932     if (Elt0 >= 0) {
5933       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5934                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5935       if ((Elt0 & 1) != 0)
5936         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5937                               DAG.getConstant(8,
5938                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5939       else if (Elt1 >= 0)
5940         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5941                              DAG.getConstant(0x00FF, MVT::i16));
5942       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5943                          : InsElt0;
5944     }
5945     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5946                        DAG.getIntPtrConstant(i));
5947   }
5948   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5949 }
5950
5951 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5952 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5953 /// done when every pair / quad of shuffle mask elements point to elements in
5954 /// the right sequence. e.g.
5955 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5956 static
5957 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5958                                  SelectionDAG &DAG, DebugLoc dl) {
5959   MVT VT = SVOp->getValueType(0).getSimpleVT();
5960   unsigned NumElems = VT.getVectorNumElements();
5961   MVT NewVT;
5962   unsigned Scale;
5963   switch (VT.SimpleTy) {
5964   default: llvm_unreachable("Unexpected!");
5965   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
5966   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
5967   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
5968   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
5969   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
5970   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
5971   }
5972
5973   SmallVector<int, 8> MaskVec;
5974   for (unsigned i = 0; i != NumElems; i += Scale) {
5975     int StartIdx = -1;
5976     for (unsigned j = 0; j != Scale; ++j) {
5977       int EltIdx = SVOp->getMaskElt(i+j);
5978       if (EltIdx < 0)
5979         continue;
5980       if (StartIdx < 0)
5981         StartIdx = (EltIdx / Scale);
5982       if (EltIdx != (int)(StartIdx*Scale + j))
5983         return SDValue();
5984     }
5985     MaskVec.push_back(StartIdx);
5986   }
5987
5988   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
5989   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
5990   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5991 }
5992
5993 /// getVZextMovL - Return a zero-extending vector move low node.
5994 ///
5995 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5996                             SDValue SrcOp, SelectionDAG &DAG,
5997                             const X86Subtarget *Subtarget, DebugLoc dl) {
5998   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5999     LoadSDNode *LD = NULL;
6000     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6001       LD = dyn_cast<LoadSDNode>(SrcOp);
6002     if (!LD) {
6003       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6004       // instead.
6005       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6006       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6007           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6008           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6009           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6010         // PR2108
6011         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6012         return DAG.getNode(ISD::BITCAST, dl, VT,
6013                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6014                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6015                                                    OpVT,
6016                                                    SrcOp.getOperand(0)
6017                                                           .getOperand(0))));
6018       }
6019     }
6020   }
6021
6022   return DAG.getNode(ISD::BITCAST, dl, VT,
6023                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6024                                  DAG.getNode(ISD::BITCAST, dl,
6025                                              OpVT, SrcOp)));
6026 }
6027
6028 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6029 /// which could not be matched by any known target speficic shuffle
6030 static SDValue
6031 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6032
6033   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6034   if (NewOp.getNode())
6035     return NewOp;
6036
6037   EVT VT = SVOp->getValueType(0);
6038
6039   unsigned NumElems = VT.getVectorNumElements();
6040   unsigned NumLaneElems = NumElems / 2;
6041
6042   DebugLoc dl = SVOp->getDebugLoc();
6043   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6044   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6045   SDValue Output[2];
6046
6047   SmallVector<int, 16> Mask;
6048   for (unsigned l = 0; l < 2; ++l) {
6049     // Build a shuffle mask for the output, discovering on the fly which
6050     // input vectors to use as shuffle operands (recorded in InputUsed).
6051     // If building a suitable shuffle vector proves too hard, then bail
6052     // out with UseBuildVector set.
6053     bool UseBuildVector = false;
6054     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6055     unsigned LaneStart = l * NumLaneElems;
6056     for (unsigned i = 0; i != NumLaneElems; ++i) {
6057       // The mask element.  This indexes into the input.
6058       int Idx = SVOp->getMaskElt(i+LaneStart);
6059       if (Idx < 0) {
6060         // the mask element does not index into any input vector.
6061         Mask.push_back(-1);
6062         continue;
6063       }
6064
6065       // The input vector this mask element indexes into.
6066       int Input = Idx / NumLaneElems;
6067
6068       // Turn the index into an offset from the start of the input vector.
6069       Idx -= Input * NumLaneElems;
6070
6071       // Find or create a shuffle vector operand to hold this input.
6072       unsigned OpNo;
6073       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6074         if (InputUsed[OpNo] == Input)
6075           // This input vector is already an operand.
6076           break;
6077         if (InputUsed[OpNo] < 0) {
6078           // Create a new operand for this input vector.
6079           InputUsed[OpNo] = Input;
6080           break;
6081         }
6082       }
6083
6084       if (OpNo >= array_lengthof(InputUsed)) {
6085         // More than two input vectors used!  Give up on trying to create a
6086         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6087         UseBuildVector = true;
6088         break;
6089       }
6090
6091       // Add the mask index for the new shuffle vector.
6092       Mask.push_back(Idx + OpNo * NumLaneElems);
6093     }
6094
6095     if (UseBuildVector) {
6096       SmallVector<SDValue, 16> SVOps;
6097       for (unsigned i = 0; i != NumLaneElems; ++i) {
6098         // The mask element.  This indexes into the input.
6099         int Idx = SVOp->getMaskElt(i+LaneStart);
6100         if (Idx < 0) {
6101           SVOps.push_back(DAG.getUNDEF(EltVT));
6102           continue;
6103         }
6104
6105         // The input vector this mask element indexes into.
6106         int Input = Idx / NumElems;
6107
6108         // Turn the index into an offset from the start of the input vector.
6109         Idx -= Input * NumElems;
6110
6111         // Extract the vector element by hand.
6112         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6113                                     SVOp->getOperand(Input),
6114                                     DAG.getIntPtrConstant(Idx)));
6115       }
6116
6117       // Construct the output using a BUILD_VECTOR.
6118       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6119                               SVOps.size());
6120     } else if (InputUsed[0] < 0) {
6121       // No input vectors were used! The result is undefined.
6122       Output[l] = DAG.getUNDEF(NVT);
6123     } else {
6124       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6125                                         (InputUsed[0] % 2) * NumLaneElems,
6126                                         DAG, dl);
6127       // If only one input was used, use an undefined vector for the other.
6128       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6129         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6130                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6131       // At least one input vector was used. Create a new shuffle vector.
6132       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6133     }
6134
6135     Mask.clear();
6136   }
6137
6138   // Concatenate the result back
6139   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6140 }
6141
6142 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6143 /// 4 elements, and match them with several different shuffle types.
6144 static SDValue
6145 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6146   SDValue V1 = SVOp->getOperand(0);
6147   SDValue V2 = SVOp->getOperand(1);
6148   DebugLoc dl = SVOp->getDebugLoc();
6149   EVT VT = SVOp->getValueType(0);
6150
6151   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6152
6153   std::pair<int, int> Locs[4];
6154   int Mask1[] = { -1, -1, -1, -1 };
6155   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6156
6157   unsigned NumHi = 0;
6158   unsigned NumLo = 0;
6159   for (unsigned i = 0; i != 4; ++i) {
6160     int Idx = PermMask[i];
6161     if (Idx < 0) {
6162       Locs[i] = std::make_pair(-1, -1);
6163     } else {
6164       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6165       if (Idx < 4) {
6166         Locs[i] = std::make_pair(0, NumLo);
6167         Mask1[NumLo] = Idx;
6168         NumLo++;
6169       } else {
6170         Locs[i] = std::make_pair(1, NumHi);
6171         if (2+NumHi < 4)
6172           Mask1[2+NumHi] = Idx;
6173         NumHi++;
6174       }
6175     }
6176   }
6177
6178   if (NumLo <= 2 && NumHi <= 2) {
6179     // If no more than two elements come from either vector. This can be
6180     // implemented with two shuffles. First shuffle gather the elements.
6181     // The second shuffle, which takes the first shuffle as both of its
6182     // vector operands, put the elements into the right order.
6183     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6184
6185     int Mask2[] = { -1, -1, -1, -1 };
6186
6187     for (unsigned i = 0; i != 4; ++i)
6188       if (Locs[i].first != -1) {
6189         unsigned Idx = (i < 2) ? 0 : 4;
6190         Idx += Locs[i].first * 2 + Locs[i].second;
6191         Mask2[i] = Idx;
6192       }
6193
6194     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6195   }
6196
6197   if (NumLo == 3 || NumHi == 3) {
6198     // Otherwise, we must have three elements from one vector, call it X, and
6199     // one element from the other, call it Y.  First, use a shufps to build an
6200     // intermediate vector with the one element from Y and the element from X
6201     // that will be in the same half in the final destination (the indexes don't
6202     // matter). Then, use a shufps to build the final vector, taking the half
6203     // containing the element from Y from the intermediate, and the other half
6204     // from X.
6205     if (NumHi == 3) {
6206       // Normalize it so the 3 elements come from V1.
6207       CommuteVectorShuffleMask(PermMask, 4);
6208       std::swap(V1, V2);
6209     }
6210
6211     // Find the element from V2.
6212     unsigned HiIndex;
6213     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6214       int Val = PermMask[HiIndex];
6215       if (Val < 0)
6216         continue;
6217       if (Val >= 4)
6218         break;
6219     }
6220
6221     Mask1[0] = PermMask[HiIndex];
6222     Mask1[1] = -1;
6223     Mask1[2] = PermMask[HiIndex^1];
6224     Mask1[3] = -1;
6225     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6226
6227     if (HiIndex >= 2) {
6228       Mask1[0] = PermMask[0];
6229       Mask1[1] = PermMask[1];
6230       Mask1[2] = HiIndex & 1 ? 6 : 4;
6231       Mask1[3] = HiIndex & 1 ? 4 : 6;
6232       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6233     }
6234
6235     Mask1[0] = HiIndex & 1 ? 2 : 0;
6236     Mask1[1] = HiIndex & 1 ? 0 : 2;
6237     Mask1[2] = PermMask[2];
6238     Mask1[3] = PermMask[3];
6239     if (Mask1[2] >= 0)
6240       Mask1[2] += 4;
6241     if (Mask1[3] >= 0)
6242       Mask1[3] += 4;
6243     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6244   }
6245
6246   // Break it into (shuffle shuffle_hi, shuffle_lo).
6247   int LoMask[] = { -1, -1, -1, -1 };
6248   int HiMask[] = { -1, -1, -1, -1 };
6249
6250   int *MaskPtr = LoMask;
6251   unsigned MaskIdx = 0;
6252   unsigned LoIdx = 0;
6253   unsigned HiIdx = 2;
6254   for (unsigned i = 0; i != 4; ++i) {
6255     if (i == 2) {
6256       MaskPtr = HiMask;
6257       MaskIdx = 1;
6258       LoIdx = 0;
6259       HiIdx = 2;
6260     }
6261     int Idx = PermMask[i];
6262     if (Idx < 0) {
6263       Locs[i] = std::make_pair(-1, -1);
6264     } else if (Idx < 4) {
6265       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6266       MaskPtr[LoIdx] = Idx;
6267       LoIdx++;
6268     } else {
6269       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6270       MaskPtr[HiIdx] = Idx;
6271       HiIdx++;
6272     }
6273   }
6274
6275   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6276   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6277   int MaskOps[] = { -1, -1, -1, -1 };
6278   for (unsigned i = 0; i != 4; ++i)
6279     if (Locs[i].first != -1)
6280       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6281   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6282 }
6283
6284 static bool MayFoldVectorLoad(SDValue V) {
6285   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6286     V = V.getOperand(0);
6287   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6288     V = V.getOperand(0);
6289   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6290       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6291     // BUILD_VECTOR (load), undef
6292     V = V.getOperand(0);
6293   if (MayFoldLoad(V))
6294     return true;
6295   return false;
6296 }
6297
6298 // FIXME: the version above should always be used. Since there's
6299 // a bug where several vector shuffles can't be folded because the
6300 // DAG is not updated during lowering and a node claims to have two
6301 // uses while it only has one, use this version, and let isel match
6302 // another instruction if the load really happens to have more than
6303 // one use. Remove this version after this bug get fixed.
6304 // rdar://8434668, PR8156
6305 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6306   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6307     V = V.getOperand(0);
6308   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6309     V = V.getOperand(0);
6310   if (ISD::isNormalLoad(V.getNode()))
6311     return true;
6312   return false;
6313 }
6314
6315 static
6316 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6317   EVT VT = Op.getValueType();
6318
6319   // Canonizalize to v2f64.
6320   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6321   return DAG.getNode(ISD::BITCAST, dl, VT,
6322                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6323                                           V1, DAG));
6324 }
6325
6326 static
6327 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6328                         bool HasSSE2) {
6329   SDValue V1 = Op.getOperand(0);
6330   SDValue V2 = Op.getOperand(1);
6331   EVT VT = Op.getValueType();
6332
6333   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6334
6335   if (HasSSE2 && VT == MVT::v2f64)
6336     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6337
6338   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6339   return DAG.getNode(ISD::BITCAST, dl, VT,
6340                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6341                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6342                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6343 }
6344
6345 static
6346 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6347   SDValue V1 = Op.getOperand(0);
6348   SDValue V2 = Op.getOperand(1);
6349   EVT VT = Op.getValueType();
6350
6351   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6352          "unsupported shuffle type");
6353
6354   if (V2.getOpcode() == ISD::UNDEF)
6355     V2 = V1;
6356
6357   // v4i32 or v4f32
6358   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6359 }
6360
6361 static
6362 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6363   SDValue V1 = Op.getOperand(0);
6364   SDValue V2 = Op.getOperand(1);
6365   EVT VT = Op.getValueType();
6366   unsigned NumElems = VT.getVectorNumElements();
6367
6368   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6369   // operand of these instructions is only memory, so check if there's a
6370   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6371   // same masks.
6372   bool CanFoldLoad = false;
6373
6374   // Trivial case, when V2 comes from a load.
6375   if (MayFoldVectorLoad(V2))
6376     CanFoldLoad = true;
6377
6378   // When V1 is a load, it can be folded later into a store in isel, example:
6379   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6380   //    turns into:
6381   //  (MOVLPSmr addr:$src1, VR128:$src2)
6382   // So, recognize this potential and also use MOVLPS or MOVLPD
6383   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6384     CanFoldLoad = true;
6385
6386   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6387   if (CanFoldLoad) {
6388     if (HasSSE2 && NumElems == 2)
6389       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6390
6391     if (NumElems == 4)
6392       // If we don't care about the second element, proceed to use movss.
6393       if (SVOp->getMaskElt(1) != -1)
6394         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6395   }
6396
6397   // movl and movlp will both match v2i64, but v2i64 is never matched by
6398   // movl earlier because we make it strict to avoid messing with the movlp load
6399   // folding logic (see the code above getMOVLP call). Match it here then,
6400   // this is horrible, but will stay like this until we move all shuffle
6401   // matching to x86 specific nodes. Note that for the 1st condition all
6402   // types are matched with movsd.
6403   if (HasSSE2) {
6404     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6405     // as to remove this logic from here, as much as possible
6406     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6407       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6408     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6409   }
6410
6411   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6412
6413   // Invert the operand order and use SHUFPS to match it.
6414   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6415                               getShuffleSHUFImmediate(SVOp), DAG);
6416 }
6417
6418 SDValue
6419 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6420   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6421   EVT VT = Op.getValueType();
6422   DebugLoc dl = Op.getDebugLoc();
6423   SDValue V1 = Op.getOperand(0);
6424   SDValue V2 = Op.getOperand(1);
6425
6426   if (isZeroShuffle(SVOp))
6427     return getZeroVector(VT, Subtarget, DAG, dl);
6428
6429   // Handle splat operations
6430   if (SVOp->isSplat()) {
6431     unsigned NumElem = VT.getVectorNumElements();
6432     int Size = VT.getSizeInBits();
6433
6434     // Use vbroadcast whenever the splat comes from a foldable load
6435     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6436     if (Broadcast.getNode())
6437       return Broadcast;
6438
6439     // Handle splats by matching through known shuffle masks
6440     if ((Size == 128 && NumElem <= 4) ||
6441         (Size == 256 && NumElem < 8))
6442       return SDValue();
6443
6444     // All remaning splats are promoted to target supported vector shuffles.
6445     return PromoteSplat(SVOp, DAG);
6446   }
6447
6448   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6449   // do it!
6450   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6451       VT == MVT::v16i16 || VT == MVT::v32i8) {
6452     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6453     if (NewOp.getNode())
6454       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6455   } else if ((VT == MVT::v4i32 ||
6456              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6457     // FIXME: Figure out a cleaner way to do this.
6458     // Try to make use of movq to zero out the top part.
6459     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6460       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6461       if (NewOp.getNode()) {
6462         EVT NewVT = NewOp.getValueType();
6463         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6464                                NewVT, true, false))
6465           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6466                               DAG, Subtarget, dl);
6467       }
6468     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6469       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6470       if (NewOp.getNode()) {
6471         EVT NewVT = NewOp.getValueType();
6472         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6473           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6474                               DAG, Subtarget, dl);
6475       }
6476     }
6477   }
6478   return SDValue();
6479 }
6480
6481 SDValue
6482 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6483   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6484   SDValue V1 = Op.getOperand(0);
6485   SDValue V2 = Op.getOperand(1);
6486   EVT VT = Op.getValueType();
6487   DebugLoc dl = Op.getDebugLoc();
6488   unsigned NumElems = VT.getVectorNumElements();
6489   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6490   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6491   bool V1IsSplat = false;
6492   bool V2IsSplat = false;
6493   bool HasSSE2 = Subtarget->hasSSE2();
6494   bool HasAVX    = Subtarget->hasAVX();
6495   bool HasAVX2   = Subtarget->hasAVX2();
6496   MachineFunction &MF = DAG.getMachineFunction();
6497   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6498
6499   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6500
6501   if (V1IsUndef && V2IsUndef)
6502     return DAG.getUNDEF(VT);
6503
6504   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6505
6506   // Vector shuffle lowering takes 3 steps:
6507   //
6508   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6509   //    narrowing and commutation of operands should be handled.
6510   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6511   //    shuffle nodes.
6512   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6513   //    so the shuffle can be broken into other shuffles and the legalizer can
6514   //    try the lowering again.
6515   //
6516   // The general idea is that no vector_shuffle operation should be left to
6517   // be matched during isel, all of them must be converted to a target specific
6518   // node here.
6519
6520   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6521   // narrowing and commutation of operands should be handled. The actual code
6522   // doesn't include all of those, work in progress...
6523   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6524   if (NewOp.getNode())
6525     return NewOp;
6526
6527   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6528
6529   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6530   // unpckh_undef). Only use pshufd if speed is more important than size.
6531   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6532     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6533   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6534     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6535
6536   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6537       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6538     return getMOVDDup(Op, dl, V1, DAG);
6539
6540   if (isMOVHLPS_v_undef_Mask(M, VT))
6541     return getMOVHighToLow(Op, dl, DAG);
6542
6543   // Use to match splats
6544   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6545       (VT == MVT::v2f64 || VT == MVT::v2i64))
6546     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6547
6548   if (isPSHUFDMask(M, VT)) {
6549     // The actual implementation will match the mask in the if above and then
6550     // during isel it can match several different instructions, not only pshufd
6551     // as its name says, sad but true, emulate the behavior for now...
6552     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6553       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6554
6555     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6556
6557     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6558       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6559
6560     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6561       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6562
6563     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6564                                 TargetMask, DAG);
6565   }
6566
6567   // Check if this can be converted into a logical shift.
6568   bool isLeft = false;
6569   unsigned ShAmt = 0;
6570   SDValue ShVal;
6571   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6572   if (isShift && ShVal.hasOneUse()) {
6573     // If the shifted value has multiple uses, it may be cheaper to use
6574     // v_set0 + movlhps or movhlps, etc.
6575     EVT EltVT = VT.getVectorElementType();
6576     ShAmt *= EltVT.getSizeInBits();
6577     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6578   }
6579
6580   if (isMOVLMask(M, VT)) {
6581     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6582       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6583     if (!isMOVLPMask(M, VT)) {
6584       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6585         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6586
6587       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6588         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6589     }
6590   }
6591
6592   // FIXME: fold these into legal mask.
6593   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6594     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6595
6596   if (isMOVHLPSMask(M, VT))
6597     return getMOVHighToLow(Op, dl, DAG);
6598
6599   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6600     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6601
6602   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6603     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6604
6605   if (isMOVLPMask(M, VT))
6606     return getMOVLP(Op, dl, DAG, HasSSE2);
6607
6608   if (ShouldXformToMOVHLPS(M, VT) ||
6609       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6610     return CommuteVectorShuffle(SVOp, DAG);
6611
6612   if (isShift) {
6613     // No better options. Use a vshldq / vsrldq.
6614     EVT EltVT = VT.getVectorElementType();
6615     ShAmt *= EltVT.getSizeInBits();
6616     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6617   }
6618
6619   bool Commuted = false;
6620   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6621   // 1,1,1,1 -> v8i16 though.
6622   V1IsSplat = isSplatVector(V1.getNode());
6623   V2IsSplat = isSplatVector(V2.getNode());
6624
6625   // Canonicalize the splat or undef, if present, to be on the RHS.
6626   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6627     CommuteVectorShuffleMask(M, NumElems);
6628     std::swap(V1, V2);
6629     std::swap(V1IsSplat, V2IsSplat);
6630     Commuted = true;
6631   }
6632
6633   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6634     // Shuffling low element of v1 into undef, just return v1.
6635     if (V2IsUndef)
6636       return V1;
6637     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6638     // the instruction selector will not match, so get a canonical MOVL with
6639     // swapped operands to undo the commute.
6640     return getMOVL(DAG, dl, VT, V2, V1);
6641   }
6642
6643   if (isUNPCKLMask(M, VT, HasAVX2))
6644     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6645
6646   if (isUNPCKHMask(M, VT, HasAVX2))
6647     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6648
6649   if (V2IsSplat) {
6650     // Normalize mask so all entries that point to V2 points to its first
6651     // element then try to match unpck{h|l} again. If match, return a
6652     // new vector_shuffle with the corrected mask.p
6653     SmallVector<int, 8> NewMask(M.begin(), M.end());
6654     NormalizeMask(NewMask, NumElems);
6655     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6656       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6657     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6658       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6659   }
6660
6661   if (Commuted) {
6662     // Commute is back and try unpck* again.
6663     // FIXME: this seems wrong.
6664     CommuteVectorShuffleMask(M, NumElems);
6665     std::swap(V1, V2);
6666     std::swap(V1IsSplat, V2IsSplat);
6667     Commuted = false;
6668
6669     if (isUNPCKLMask(M, VT, HasAVX2))
6670       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6671
6672     if (isUNPCKHMask(M, VT, HasAVX2))
6673       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6674   }
6675
6676   // Normalize the node to match x86 shuffle ops if needed
6677   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6678     return CommuteVectorShuffle(SVOp, DAG);
6679
6680   // The checks below are all present in isShuffleMaskLegal, but they are
6681   // inlined here right now to enable us to directly emit target specific
6682   // nodes, and remove one by one until they don't return Op anymore.
6683
6684   if (isPALIGNRMask(M, VT, Subtarget))
6685     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6686                                 getShufflePALIGNRImmediate(SVOp),
6687                                 DAG);
6688
6689   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6690       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6691     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6692       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6693   }
6694
6695   if (isPSHUFHWMask(M, VT, HasAVX2))
6696     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6697                                 getShufflePSHUFHWImmediate(SVOp),
6698                                 DAG);
6699
6700   if (isPSHUFLWMask(M, VT, HasAVX2))
6701     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6702                                 getShufflePSHUFLWImmediate(SVOp),
6703                                 DAG);
6704
6705   if (isSHUFPMask(M, VT, HasAVX))
6706     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6707                                 getShuffleSHUFImmediate(SVOp), DAG);
6708
6709   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6710     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6711   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6712     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6713
6714   //===--------------------------------------------------------------------===//
6715   // Generate target specific nodes for 128 or 256-bit shuffles only
6716   // supported in the AVX instruction set.
6717   //
6718
6719   // Handle VMOVDDUPY permutations
6720   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6721     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6722
6723   // Handle VPERMILPS/D* permutations
6724   if (isVPERMILPMask(M, VT, HasAVX)) {
6725     if (HasAVX2 && VT == MVT::v8i32)
6726       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6727                                   getShuffleSHUFImmediate(SVOp), DAG);
6728     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6729                                 getShuffleSHUFImmediate(SVOp), DAG);
6730   }
6731
6732   // Handle VPERM2F128/VPERM2I128 permutations
6733   if (isVPERM2X128Mask(M, VT, HasAVX))
6734     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6735                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6736
6737   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6738   if (BlendOp.getNode())
6739     return BlendOp;
6740
6741   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6742     SmallVector<SDValue, 8> permclMask;
6743     for (unsigned i = 0; i != 8; ++i) {
6744       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6745     }
6746     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6747                                &permclMask[0], 8);
6748     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6749     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6750                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6751   }
6752
6753   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6754     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6755                                 getShuffleCLImmediate(SVOp), DAG);
6756
6757
6758   //===--------------------------------------------------------------------===//
6759   // Since no target specific shuffle was selected for this generic one,
6760   // lower it into other known shuffles. FIXME: this isn't true yet, but
6761   // this is the plan.
6762   //
6763
6764   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6765   if (VT == MVT::v8i16) {
6766     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6767     if (NewOp.getNode())
6768       return NewOp;
6769   }
6770
6771   if (VT == MVT::v16i8) {
6772     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6773     if (NewOp.getNode())
6774       return NewOp;
6775   }
6776
6777   // Handle all 128-bit wide vectors with 4 elements, and match them with
6778   // several different shuffle types.
6779   if (NumElems == 4 && VT.getSizeInBits() == 128)
6780     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6781
6782   // Handle general 256-bit shuffles
6783   if (VT.is256BitVector())
6784     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6785
6786   return SDValue();
6787 }
6788
6789 SDValue
6790 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6791                                                 SelectionDAG &DAG) const {
6792   EVT VT = Op.getValueType();
6793   DebugLoc dl = Op.getDebugLoc();
6794
6795   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6796     return SDValue();
6797
6798   if (VT.getSizeInBits() == 8) {
6799     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6800                                     Op.getOperand(0), Op.getOperand(1));
6801     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6802                                     DAG.getValueType(VT));
6803     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6804   }
6805
6806   if (VT.getSizeInBits() == 16) {
6807     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6808     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6809     if (Idx == 0)
6810       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6811                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6812                                      DAG.getNode(ISD::BITCAST, dl,
6813                                                  MVT::v4i32,
6814                                                  Op.getOperand(0)),
6815                                      Op.getOperand(1)));
6816     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6817                                     Op.getOperand(0), Op.getOperand(1));
6818     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6819                                     DAG.getValueType(VT));
6820     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6821   }
6822
6823   if (VT == MVT::f32) {
6824     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6825     // the result back to FR32 register. It's only worth matching if the
6826     // result has a single use which is a store or a bitcast to i32.  And in
6827     // the case of a store, it's not worth it if the index is a constant 0,
6828     // because a MOVSSmr can be used instead, which is smaller and faster.
6829     if (!Op.hasOneUse())
6830       return SDValue();
6831     SDNode *User = *Op.getNode()->use_begin();
6832     if ((User->getOpcode() != ISD::STORE ||
6833          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6834           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6835         (User->getOpcode() != ISD::BITCAST ||
6836          User->getValueType(0) != MVT::i32))
6837       return SDValue();
6838     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6839                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6840                                               Op.getOperand(0)),
6841                                               Op.getOperand(1));
6842     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6843   }
6844
6845   if (VT == MVT::i32 || VT == MVT::i64) {
6846     // ExtractPS/pextrq works with constant index.
6847     if (isa<ConstantSDNode>(Op.getOperand(1)))
6848       return Op;
6849   }
6850   return SDValue();
6851 }
6852
6853
6854 SDValue
6855 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6856                                            SelectionDAG &DAG) const {
6857   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6858     return SDValue();
6859
6860   SDValue Vec = Op.getOperand(0);
6861   EVT VecVT = Vec.getValueType();
6862
6863   // If this is a 256-bit vector result, first extract the 128-bit vector and
6864   // then extract the element from the 128-bit vector.
6865   if (VecVT.getSizeInBits() == 256) {
6866     DebugLoc dl = Op.getNode()->getDebugLoc();
6867     unsigned NumElems = VecVT.getVectorNumElements();
6868     SDValue Idx = Op.getOperand(1);
6869     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6870
6871     // Get the 128-bit vector.
6872     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6873
6874     if (IdxVal >= NumElems/2)
6875       IdxVal -= NumElems/2;
6876     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6877                        DAG.getConstant(IdxVal, MVT::i32));
6878   }
6879
6880   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6881
6882   if (Subtarget->hasSSE41()) {
6883     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6884     if (Res.getNode())
6885       return Res;
6886   }
6887
6888   EVT VT = Op.getValueType();
6889   DebugLoc dl = Op.getDebugLoc();
6890   // TODO: handle v16i8.
6891   if (VT.getSizeInBits() == 16) {
6892     SDValue Vec = Op.getOperand(0);
6893     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6894     if (Idx == 0)
6895       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6896                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6897                                      DAG.getNode(ISD::BITCAST, dl,
6898                                                  MVT::v4i32, Vec),
6899                                      Op.getOperand(1)));
6900     // Transform it so it match pextrw which produces a 32-bit result.
6901     EVT EltVT = MVT::i32;
6902     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6903                                     Op.getOperand(0), Op.getOperand(1));
6904     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6905                                     DAG.getValueType(VT));
6906     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6907   }
6908
6909   if (VT.getSizeInBits() == 32) {
6910     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6911     if (Idx == 0)
6912       return Op;
6913
6914     // SHUFPS the element to the lowest double word, then movss.
6915     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6916     EVT VVT = Op.getOperand(0).getValueType();
6917     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6918                                        DAG.getUNDEF(VVT), Mask);
6919     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6920                        DAG.getIntPtrConstant(0));
6921   }
6922
6923   if (VT.getSizeInBits() == 64) {
6924     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6925     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6926     //        to match extract_elt for f64.
6927     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6928     if (Idx == 0)
6929       return Op;
6930
6931     // UNPCKHPD the element to the lowest double word, then movsd.
6932     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6933     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6934     int Mask[2] = { 1, -1 };
6935     EVT VVT = Op.getOperand(0).getValueType();
6936     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6937                                        DAG.getUNDEF(VVT), Mask);
6938     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6939                        DAG.getIntPtrConstant(0));
6940   }
6941
6942   return SDValue();
6943 }
6944
6945 SDValue
6946 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6947                                                SelectionDAG &DAG) const {
6948   EVT VT = Op.getValueType();
6949   EVT EltVT = VT.getVectorElementType();
6950   DebugLoc dl = Op.getDebugLoc();
6951
6952   SDValue N0 = Op.getOperand(0);
6953   SDValue N1 = Op.getOperand(1);
6954   SDValue N2 = Op.getOperand(2);
6955
6956   if (VT.getSizeInBits() == 256)
6957     return SDValue();
6958
6959   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6960       isa<ConstantSDNode>(N2)) {
6961     unsigned Opc;
6962     if (VT == MVT::v8i16)
6963       Opc = X86ISD::PINSRW;
6964     else if (VT == MVT::v16i8)
6965       Opc = X86ISD::PINSRB;
6966     else
6967       Opc = X86ISD::PINSRB;
6968
6969     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6970     // argument.
6971     if (N1.getValueType() != MVT::i32)
6972       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6973     if (N2.getValueType() != MVT::i32)
6974       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6975     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6976   }
6977
6978   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6979     // Bits [7:6] of the constant are the source select.  This will always be
6980     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6981     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6982     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6983     // Bits [5:4] of the constant are the destination select.  This is the
6984     //  value of the incoming immediate.
6985     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6986     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6987     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6988     // Create this as a scalar to vector..
6989     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6990     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6991   }
6992
6993   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
6994     // PINSR* works with constant index.
6995     return Op;
6996   }
6997   return SDValue();
6998 }
6999
7000 SDValue
7001 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7002   EVT VT = Op.getValueType();
7003   EVT EltVT = VT.getVectorElementType();
7004
7005   DebugLoc dl = Op.getDebugLoc();
7006   SDValue N0 = Op.getOperand(0);
7007   SDValue N1 = Op.getOperand(1);
7008   SDValue N2 = Op.getOperand(2);
7009
7010   // If this is a 256-bit vector result, first extract the 128-bit vector,
7011   // insert the element into the extracted half and then place it back.
7012   if (VT.getSizeInBits() == 256) {
7013     if (!isa<ConstantSDNode>(N2))
7014       return SDValue();
7015
7016     // Get the desired 128-bit vector half.
7017     unsigned NumElems = VT.getVectorNumElements();
7018     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7019     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7020
7021     // Insert the element into the desired half.
7022     bool Upper = IdxVal >= NumElems/2;
7023     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7024                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7025
7026     // Insert the changed part back to the 256-bit vector
7027     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7028   }
7029
7030   if (Subtarget->hasSSE41())
7031     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7032
7033   if (EltVT == MVT::i8)
7034     return SDValue();
7035
7036   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7037     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7038     // as its second argument.
7039     if (N1.getValueType() != MVT::i32)
7040       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7041     if (N2.getValueType() != MVT::i32)
7042       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7043     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7044   }
7045   return SDValue();
7046 }
7047
7048 SDValue
7049 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7050   LLVMContext *Context = DAG.getContext();
7051   DebugLoc dl = Op.getDebugLoc();
7052   EVT OpVT = Op.getValueType();
7053
7054   // If this is a 256-bit vector result, first insert into a 128-bit
7055   // vector and then insert into the 256-bit vector.
7056   if (OpVT.getSizeInBits() > 128) {
7057     // Insert into a 128-bit vector.
7058     EVT VT128 = EVT::getVectorVT(*Context,
7059                                  OpVT.getVectorElementType(),
7060                                  OpVT.getVectorNumElements() / 2);
7061
7062     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7063
7064     // Insert the 128-bit vector.
7065     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7066   }
7067
7068   if (OpVT == MVT::v1i64 &&
7069       Op.getOperand(0).getValueType() == MVT::i64)
7070     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7071
7072   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7073   assert(OpVT.getSizeInBits() == 128 && "Expected an SSE type!");
7074   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7075                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7076 }
7077
7078 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7079 // a simple subregister reference or explicit instructions to grab
7080 // upper bits of a vector.
7081 SDValue
7082 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7083   if (Subtarget->hasAVX()) {
7084     DebugLoc dl = Op.getNode()->getDebugLoc();
7085     SDValue Vec = Op.getNode()->getOperand(0);
7086     SDValue Idx = Op.getNode()->getOperand(1);
7087
7088     if (Op.getNode()->getValueType(0).getSizeInBits() == 128 &&
7089         Vec.getNode()->getValueType(0).getSizeInBits() == 256 &&
7090         isa<ConstantSDNode>(Idx)) {
7091       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7092       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7093     }
7094   }
7095   return SDValue();
7096 }
7097
7098 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7099 // simple superregister reference or explicit instructions to insert
7100 // the upper bits of a vector.
7101 SDValue
7102 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7103   if (Subtarget->hasAVX()) {
7104     DebugLoc dl = Op.getNode()->getDebugLoc();
7105     SDValue Vec = Op.getNode()->getOperand(0);
7106     SDValue SubVec = Op.getNode()->getOperand(1);
7107     SDValue Idx = Op.getNode()->getOperand(2);
7108
7109     if (Op.getNode()->getValueType(0).getSizeInBits() == 256 &&
7110         SubVec.getNode()->getValueType(0).getSizeInBits() == 128 &&
7111         isa<ConstantSDNode>(Idx)) {
7112       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7113       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7114     }
7115   }
7116   return SDValue();
7117 }
7118
7119 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7120 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7121 // one of the above mentioned nodes. It has to be wrapped because otherwise
7122 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7123 // be used to form addressing mode. These wrapped nodes will be selected
7124 // into MOV32ri.
7125 SDValue
7126 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7127   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7128
7129   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7130   // global base reg.
7131   unsigned char OpFlag = 0;
7132   unsigned WrapperKind = X86ISD::Wrapper;
7133   CodeModel::Model M = getTargetMachine().getCodeModel();
7134
7135   if (Subtarget->isPICStyleRIPRel() &&
7136       (M == CodeModel::Small || M == CodeModel::Kernel))
7137     WrapperKind = X86ISD::WrapperRIP;
7138   else if (Subtarget->isPICStyleGOT())
7139     OpFlag = X86II::MO_GOTOFF;
7140   else if (Subtarget->isPICStyleStubPIC())
7141     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7142
7143   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7144                                              CP->getAlignment(),
7145                                              CP->getOffset(), OpFlag);
7146   DebugLoc DL = CP->getDebugLoc();
7147   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7148   // With PIC, the address is actually $g + Offset.
7149   if (OpFlag) {
7150     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7151                          DAG.getNode(X86ISD::GlobalBaseReg,
7152                                      DebugLoc(), getPointerTy()),
7153                          Result);
7154   }
7155
7156   return Result;
7157 }
7158
7159 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7160   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7161
7162   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7163   // global base reg.
7164   unsigned char OpFlag = 0;
7165   unsigned WrapperKind = X86ISD::Wrapper;
7166   CodeModel::Model M = getTargetMachine().getCodeModel();
7167
7168   if (Subtarget->isPICStyleRIPRel() &&
7169       (M == CodeModel::Small || M == CodeModel::Kernel))
7170     WrapperKind = X86ISD::WrapperRIP;
7171   else if (Subtarget->isPICStyleGOT())
7172     OpFlag = X86II::MO_GOTOFF;
7173   else if (Subtarget->isPICStyleStubPIC())
7174     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7175
7176   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7177                                           OpFlag);
7178   DebugLoc DL = JT->getDebugLoc();
7179   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7180
7181   // With PIC, the address is actually $g + Offset.
7182   if (OpFlag)
7183     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7184                          DAG.getNode(X86ISD::GlobalBaseReg,
7185                                      DebugLoc(), getPointerTy()),
7186                          Result);
7187
7188   return Result;
7189 }
7190
7191 SDValue
7192 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7193   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7194
7195   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7196   // global base reg.
7197   unsigned char OpFlag = 0;
7198   unsigned WrapperKind = X86ISD::Wrapper;
7199   CodeModel::Model M = getTargetMachine().getCodeModel();
7200
7201   if (Subtarget->isPICStyleRIPRel() &&
7202       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7203     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7204       OpFlag = X86II::MO_GOTPCREL;
7205     WrapperKind = X86ISD::WrapperRIP;
7206   } else if (Subtarget->isPICStyleGOT()) {
7207     OpFlag = X86II::MO_GOT;
7208   } else if (Subtarget->isPICStyleStubPIC()) {
7209     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7210   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7211     OpFlag = X86II::MO_DARWIN_NONLAZY;
7212   }
7213
7214   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7215
7216   DebugLoc DL = Op.getDebugLoc();
7217   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7218
7219
7220   // With PIC, the address is actually $g + Offset.
7221   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7222       !Subtarget->is64Bit()) {
7223     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7224                          DAG.getNode(X86ISD::GlobalBaseReg,
7225                                      DebugLoc(), getPointerTy()),
7226                          Result);
7227   }
7228
7229   // For symbols that require a load from a stub to get the address, emit the
7230   // load.
7231   if (isGlobalStubReference(OpFlag))
7232     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7233                          MachinePointerInfo::getGOT(), false, false, false, 0);
7234
7235   return Result;
7236 }
7237
7238 SDValue
7239 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7240   // Create the TargetBlockAddressAddress node.
7241   unsigned char OpFlags =
7242     Subtarget->ClassifyBlockAddressReference();
7243   CodeModel::Model M = getTargetMachine().getCodeModel();
7244   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7245   DebugLoc dl = Op.getDebugLoc();
7246   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7247                                        /*isTarget=*/true, OpFlags);
7248
7249   if (Subtarget->isPICStyleRIPRel() &&
7250       (M == CodeModel::Small || M == CodeModel::Kernel))
7251     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7252   else
7253     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7254
7255   // With PIC, the address is actually $g + Offset.
7256   if (isGlobalRelativeToPICBase(OpFlags)) {
7257     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7258                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7259                          Result);
7260   }
7261
7262   return Result;
7263 }
7264
7265 SDValue
7266 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7267                                       int64_t Offset,
7268                                       SelectionDAG &DAG) const {
7269   // Create the TargetGlobalAddress node, folding in the constant
7270   // offset if it is legal.
7271   unsigned char OpFlags =
7272     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7273   CodeModel::Model M = getTargetMachine().getCodeModel();
7274   SDValue Result;
7275   if (OpFlags == X86II::MO_NO_FLAG &&
7276       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7277     // A direct static reference to a global.
7278     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7279     Offset = 0;
7280   } else {
7281     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7282   }
7283
7284   if (Subtarget->isPICStyleRIPRel() &&
7285       (M == CodeModel::Small || M == CodeModel::Kernel))
7286     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7287   else
7288     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7289
7290   // With PIC, the address is actually $g + Offset.
7291   if (isGlobalRelativeToPICBase(OpFlags)) {
7292     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7293                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7294                          Result);
7295   }
7296
7297   // For globals that require a load from a stub to get the address, emit the
7298   // load.
7299   if (isGlobalStubReference(OpFlags))
7300     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7301                          MachinePointerInfo::getGOT(), false, false, false, 0);
7302
7303   // If there was a non-zero offset that we didn't fold, create an explicit
7304   // addition for it.
7305   if (Offset != 0)
7306     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7307                          DAG.getConstant(Offset, getPointerTy()));
7308
7309   return Result;
7310 }
7311
7312 SDValue
7313 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7314   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7315   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7316   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7317 }
7318
7319 static SDValue
7320 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7321            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7322            unsigned char OperandFlags, bool LocalDynamic = false) {
7323   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7324   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7325   DebugLoc dl = GA->getDebugLoc();
7326   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7327                                            GA->getValueType(0),
7328                                            GA->getOffset(),
7329                                            OperandFlags);
7330
7331   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7332                                            : X86ISD::TLSADDR;
7333
7334   if (InFlag) {
7335     SDValue Ops[] = { Chain,  TGA, *InFlag };
7336     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7337   } else {
7338     SDValue Ops[]  = { Chain, TGA };
7339     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7340   }
7341
7342   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7343   MFI->setAdjustsStack(true);
7344
7345   SDValue Flag = Chain.getValue(1);
7346   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7347 }
7348
7349 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7350 static SDValue
7351 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7352                                 const EVT PtrVT) {
7353   SDValue InFlag;
7354   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7355   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7356                                      DAG.getNode(X86ISD::GlobalBaseReg,
7357                                                  DebugLoc(), PtrVT), InFlag);
7358   InFlag = Chain.getValue(1);
7359
7360   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7361 }
7362
7363 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7364 static SDValue
7365 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7366                                 const EVT PtrVT) {
7367   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7368                     X86::RAX, X86II::MO_TLSGD);
7369 }
7370
7371 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7372                                            SelectionDAG &DAG,
7373                                            const EVT PtrVT,
7374                                            bool is64Bit) {
7375   DebugLoc dl = GA->getDebugLoc();
7376
7377   // Get the start address of the TLS block for this module.
7378   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7379       .getInfo<X86MachineFunctionInfo>();
7380   MFI->incNumLocalDynamicTLSAccesses();
7381
7382   SDValue Base;
7383   if (is64Bit) {
7384     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7385                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7386   } else {
7387     SDValue InFlag;
7388     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7389         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7390     InFlag = Chain.getValue(1);
7391     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7392                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7393   }
7394
7395   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7396   // of Base.
7397
7398   // Build x@dtpoff.
7399   unsigned char OperandFlags = X86II::MO_DTPOFF;
7400   unsigned WrapperKind = X86ISD::Wrapper;
7401   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7402                                            GA->getValueType(0),
7403                                            GA->getOffset(), OperandFlags);
7404   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7405
7406   // Add x@dtpoff with the base.
7407   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7408 }
7409
7410 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7411 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7412                                    const EVT PtrVT, TLSModel::Model model,
7413                                    bool is64Bit, bool isPIC) {
7414   DebugLoc dl = GA->getDebugLoc();
7415
7416   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7417   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7418                                                          is64Bit ? 257 : 256));
7419
7420   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7421                                       DAG.getIntPtrConstant(0),
7422                                       MachinePointerInfo(Ptr),
7423                                       false, false, false, 0);
7424
7425   unsigned char OperandFlags = 0;
7426   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7427   // initialexec.
7428   unsigned WrapperKind = X86ISD::Wrapper;
7429   if (model == TLSModel::LocalExec) {
7430     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7431   } else if (model == TLSModel::InitialExec) {
7432     if (is64Bit) {
7433       OperandFlags = X86II::MO_GOTTPOFF;
7434       WrapperKind = X86ISD::WrapperRIP;
7435     } else {
7436       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7437     }
7438   } else {
7439     llvm_unreachable("Unexpected model");
7440   }
7441
7442   // emit "addl x@ntpoff,%eax" (local exec)
7443   // or "addl x@indntpoff,%eax" (initial exec)
7444   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7445   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7446                                            GA->getValueType(0),
7447                                            GA->getOffset(), OperandFlags);
7448   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7449
7450   if (model == TLSModel::InitialExec) {
7451     if (isPIC && !is64Bit) {
7452       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7453                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7454                            Offset);
7455     } else {
7456       Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7457                            MachinePointerInfo::getGOT(), false, false, false,
7458                            0);
7459     }
7460   }
7461
7462   // The address of the thread local variable is the add of the thread
7463   // pointer with the offset of the variable.
7464   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7465 }
7466
7467 SDValue
7468 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7469
7470   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7471   const GlobalValue *GV = GA->getGlobal();
7472
7473   if (Subtarget->isTargetELF()) {
7474     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7475
7476     switch (model) {
7477       case TLSModel::GeneralDynamic:
7478         if (Subtarget->is64Bit())
7479           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7480         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7481       case TLSModel::LocalDynamic:
7482         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7483                                            Subtarget->is64Bit());
7484       case TLSModel::InitialExec:
7485       case TLSModel::LocalExec:
7486         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7487                                    Subtarget->is64Bit(),
7488                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7489     }
7490     llvm_unreachable("Unknown TLS model.");
7491   }
7492
7493   if (Subtarget->isTargetDarwin()) {
7494     // Darwin only has one model of TLS.  Lower to that.
7495     unsigned char OpFlag = 0;
7496     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7497                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7498
7499     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7500     // global base reg.
7501     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7502                   !Subtarget->is64Bit();
7503     if (PIC32)
7504       OpFlag = X86II::MO_TLVP_PIC_BASE;
7505     else
7506       OpFlag = X86II::MO_TLVP;
7507     DebugLoc DL = Op.getDebugLoc();
7508     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7509                                                 GA->getValueType(0),
7510                                                 GA->getOffset(), OpFlag);
7511     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7512
7513     // With PIC32, the address is actually $g + Offset.
7514     if (PIC32)
7515       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7516                            DAG.getNode(X86ISD::GlobalBaseReg,
7517                                        DebugLoc(), getPointerTy()),
7518                            Offset);
7519
7520     // Lowering the machine isd will make sure everything is in the right
7521     // location.
7522     SDValue Chain = DAG.getEntryNode();
7523     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7524     SDValue Args[] = { Chain, Offset };
7525     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7526
7527     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7528     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7529     MFI->setAdjustsStack(true);
7530
7531     // And our return value (tls address) is in the standard call return value
7532     // location.
7533     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7534     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7535                               Chain.getValue(1));
7536   }
7537
7538   if (Subtarget->isTargetWindows()) {
7539     // Just use the implicit TLS architecture
7540     // Need to generate someting similar to:
7541     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7542     //                                  ; from TEB
7543     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7544     //   mov     rcx, qword [rdx+rcx*8]
7545     //   mov     eax, .tls$:tlsvar
7546     //   [rax+rcx] contains the address
7547     // Windows 64bit: gs:0x58
7548     // Windows 32bit: fs:__tls_array
7549
7550     // If GV is an alias then use the aliasee for determining
7551     // thread-localness.
7552     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7553       GV = GA->resolveAliasedGlobal(false);
7554     DebugLoc dl = GA->getDebugLoc();
7555     SDValue Chain = DAG.getEntryNode();
7556
7557     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7558     // %gs:0x58 (64-bit).
7559     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7560                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7561                                                              256)
7562                                         : Type::getInt32PtrTy(*DAG.getContext(),
7563                                                               257));
7564
7565     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7566                                         Subtarget->is64Bit()
7567                                         ? DAG.getIntPtrConstant(0x58)
7568                                         : DAG.getExternalSymbol("_tls_array",
7569                                                                 getPointerTy()),
7570                                         MachinePointerInfo(Ptr),
7571                                         false, false, false, 0);
7572
7573     // Load the _tls_index variable
7574     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7575     if (Subtarget->is64Bit())
7576       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7577                            IDX, MachinePointerInfo(), MVT::i32,
7578                            false, false, 0);
7579     else
7580       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7581                         false, false, false, 0);
7582
7583     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7584                                     getPointerTy());
7585     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7586
7587     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7588     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7589                       false, false, false, 0);
7590
7591     // Get the offset of start of .tls section
7592     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7593                                              GA->getValueType(0),
7594                                              GA->getOffset(), X86II::MO_SECREL);
7595     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7596
7597     // The address of the thread local variable is the add of the thread
7598     // pointer with the offset of the variable.
7599     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7600   }
7601
7602   llvm_unreachable("TLS not implemented for this target.");
7603 }
7604
7605
7606 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7607 /// and take a 2 x i32 value to shift plus a shift amount.
7608 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7609   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7610   EVT VT = Op.getValueType();
7611   unsigned VTBits = VT.getSizeInBits();
7612   DebugLoc dl = Op.getDebugLoc();
7613   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7614   SDValue ShOpLo = Op.getOperand(0);
7615   SDValue ShOpHi = Op.getOperand(1);
7616   SDValue ShAmt  = Op.getOperand(2);
7617   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7618                                      DAG.getConstant(VTBits - 1, MVT::i8))
7619                        : DAG.getConstant(0, VT);
7620
7621   SDValue Tmp2, Tmp3;
7622   if (Op.getOpcode() == ISD::SHL_PARTS) {
7623     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7624     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7625   } else {
7626     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7627     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7628   }
7629
7630   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7631                                 DAG.getConstant(VTBits, MVT::i8));
7632   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7633                              AndNode, DAG.getConstant(0, MVT::i8));
7634
7635   SDValue Hi, Lo;
7636   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7637   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7638   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7639
7640   if (Op.getOpcode() == ISD::SHL_PARTS) {
7641     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7642     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7643   } else {
7644     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7645     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7646   }
7647
7648   SDValue Ops[2] = { Lo, Hi };
7649   return DAG.getMergeValues(Ops, 2, dl);
7650 }
7651
7652 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7653                                            SelectionDAG &DAG) const {
7654   EVT SrcVT = Op.getOperand(0).getValueType();
7655
7656   if (SrcVT.isVector())
7657     return SDValue();
7658
7659   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7660          "Unknown SINT_TO_FP to lower!");
7661
7662   // These are really Legal; return the operand so the caller accepts it as
7663   // Legal.
7664   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7665     return Op;
7666   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7667       Subtarget->is64Bit()) {
7668     return Op;
7669   }
7670
7671   DebugLoc dl = Op.getDebugLoc();
7672   unsigned Size = SrcVT.getSizeInBits()/8;
7673   MachineFunction &MF = DAG.getMachineFunction();
7674   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7675   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7676   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7677                                StackSlot,
7678                                MachinePointerInfo::getFixedStack(SSFI),
7679                                false, false, 0);
7680   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7681 }
7682
7683 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7684                                      SDValue StackSlot,
7685                                      SelectionDAG &DAG) const {
7686   // Build the FILD
7687   DebugLoc DL = Op.getDebugLoc();
7688   SDVTList Tys;
7689   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7690   if (useSSE)
7691     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7692   else
7693     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7694
7695   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7696
7697   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7698   MachineMemOperand *MMO;
7699   if (FI) {
7700     int SSFI = FI->getIndex();
7701     MMO =
7702       DAG.getMachineFunction()
7703       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7704                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7705   } else {
7706     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7707     StackSlot = StackSlot.getOperand(1);
7708   }
7709   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7710   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7711                                            X86ISD::FILD, DL,
7712                                            Tys, Ops, array_lengthof(Ops),
7713                                            SrcVT, MMO);
7714
7715   if (useSSE) {
7716     Chain = Result.getValue(1);
7717     SDValue InFlag = Result.getValue(2);
7718
7719     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7720     // shouldn't be necessary except that RFP cannot be live across
7721     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7722     MachineFunction &MF = DAG.getMachineFunction();
7723     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7724     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7725     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7726     Tys = DAG.getVTList(MVT::Other);
7727     SDValue Ops[] = {
7728       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7729     };
7730     MachineMemOperand *MMO =
7731       DAG.getMachineFunction()
7732       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7733                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7734
7735     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7736                                     Ops, array_lengthof(Ops),
7737                                     Op.getValueType(), MMO);
7738     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7739                          MachinePointerInfo::getFixedStack(SSFI),
7740                          false, false, false, 0);
7741   }
7742
7743   return Result;
7744 }
7745
7746 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7747 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7748                                                SelectionDAG &DAG) const {
7749   // This algorithm is not obvious. Here it is what we're trying to output:
7750   /*
7751      movq       %rax,  %xmm0
7752      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7753      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7754      #ifdef __SSE3__
7755        haddpd   %xmm0, %xmm0          
7756      #else
7757        pshufd   $0x4e, %xmm0, %xmm1 
7758        addpd    %xmm1, %xmm0
7759      #endif
7760   */
7761
7762   DebugLoc dl = Op.getDebugLoc();
7763   LLVMContext *Context = DAG.getContext();
7764
7765   // Build some magic constants.
7766   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7767   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7768   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7769
7770   SmallVector<Constant*,2> CV1;
7771   CV1.push_back(
7772         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7773   CV1.push_back(
7774         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7775   Constant *C1 = ConstantVector::get(CV1);
7776   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7777
7778   // Load the 64-bit value into an XMM register.
7779   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7780                             Op.getOperand(0));
7781   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7782                               MachinePointerInfo::getConstantPool(),
7783                               false, false, false, 16);
7784   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7785                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7786                               CLod0);
7787
7788   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7789                               MachinePointerInfo::getConstantPool(),
7790                               false, false, false, 16);
7791   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7792   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7793   SDValue Result;
7794
7795   if (Subtarget->hasSSE3()) {
7796     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7797     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7798   } else {
7799     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7800     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7801                                            S2F, 0x4E, DAG);
7802     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7803                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7804                          Sub);
7805   }
7806
7807   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7808                      DAG.getIntPtrConstant(0));
7809 }
7810
7811 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7812 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7813                                                SelectionDAG &DAG) const {
7814   DebugLoc dl = Op.getDebugLoc();
7815   // FP constant to bias correct the final result.
7816   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7817                                    MVT::f64);
7818
7819   // Load the 32-bit value into an XMM register.
7820   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7821                              Op.getOperand(0));
7822
7823   // Zero out the upper parts of the register.
7824   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7825
7826   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7827                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7828                      DAG.getIntPtrConstant(0));
7829
7830   // Or the load with the bias.
7831   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7832                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7833                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7834                                                    MVT::v2f64, Load)),
7835                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7836                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7837                                                    MVT::v2f64, Bias)));
7838   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7839                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7840                    DAG.getIntPtrConstant(0));
7841
7842   // Subtract the bias.
7843   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7844
7845   // Handle final rounding.
7846   EVT DestVT = Op.getValueType();
7847
7848   if (DestVT.bitsLT(MVT::f64))
7849     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7850                        DAG.getIntPtrConstant(0));
7851   if (DestVT.bitsGT(MVT::f64))
7852     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7853
7854   // Handle final rounding.
7855   return Sub;
7856 }
7857
7858 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7859                                            SelectionDAG &DAG) const {
7860   SDValue N0 = Op.getOperand(0);
7861   DebugLoc dl = Op.getDebugLoc();
7862
7863   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7864   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7865   // the optimization here.
7866   if (DAG.SignBitIsZero(N0))
7867     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7868
7869   EVT SrcVT = N0.getValueType();
7870   EVT DstVT = Op.getValueType();
7871   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7872     return LowerUINT_TO_FP_i64(Op, DAG);
7873   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7874     return LowerUINT_TO_FP_i32(Op, DAG);
7875   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7876     return SDValue();
7877
7878   // Make a 64-bit buffer, and use it to build an FILD.
7879   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7880   if (SrcVT == MVT::i32) {
7881     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7882     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7883                                      getPointerTy(), StackSlot, WordOff);
7884     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7885                                   StackSlot, MachinePointerInfo(),
7886                                   false, false, 0);
7887     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7888                                   OffsetSlot, MachinePointerInfo(),
7889                                   false, false, 0);
7890     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7891     return Fild;
7892   }
7893
7894   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7895   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7896                                StackSlot, MachinePointerInfo(),
7897                                false, false, 0);
7898   // For i64 source, we need to add the appropriate power of 2 if the input
7899   // was negative.  This is the same as the optimization in
7900   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7901   // we must be careful to do the computation in x87 extended precision, not
7902   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7903   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7904   MachineMemOperand *MMO =
7905     DAG.getMachineFunction()
7906     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7907                           MachineMemOperand::MOLoad, 8, 8);
7908
7909   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7910   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7911   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7912                                          MVT::i64, MMO);
7913
7914   APInt FF(32, 0x5F800000ULL);
7915
7916   // Check whether the sign bit is set.
7917   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7918                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7919                                  ISD::SETLT);
7920
7921   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7922   SDValue FudgePtr = DAG.getConstantPool(
7923                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7924                                          getPointerTy());
7925
7926   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7927   SDValue Zero = DAG.getIntPtrConstant(0);
7928   SDValue Four = DAG.getIntPtrConstant(4);
7929   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7930                                Zero, Four);
7931   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7932
7933   // Load the value out, extending it from f32 to f80.
7934   // FIXME: Avoid the extend by constructing the right constant pool?
7935   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7936                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7937                                  MVT::f32, false, false, 4);
7938   // Extend everything to 80 bits to force it to be done on x87.
7939   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7940   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7941 }
7942
7943 std::pair<SDValue,SDValue> X86TargetLowering::
7944 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7945   DebugLoc DL = Op.getDebugLoc();
7946
7947   EVT DstTy = Op.getValueType();
7948
7949   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7950     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7951     DstTy = MVT::i64;
7952   }
7953
7954   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7955          DstTy.getSimpleVT() >= MVT::i16 &&
7956          "Unknown FP_TO_INT to lower!");
7957
7958   // These are really Legal.
7959   if (DstTy == MVT::i32 &&
7960       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7961     return std::make_pair(SDValue(), SDValue());
7962   if (Subtarget->is64Bit() &&
7963       DstTy == MVT::i64 &&
7964       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7965     return std::make_pair(SDValue(), SDValue());
7966
7967   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
7968   // stack slot, or into the FTOL runtime function.
7969   MachineFunction &MF = DAG.getMachineFunction();
7970   unsigned MemSize = DstTy.getSizeInBits()/8;
7971   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7972   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7973
7974   unsigned Opc;
7975   if (!IsSigned && isIntegerTypeFTOL(DstTy))
7976     Opc = X86ISD::WIN_FTOL;
7977   else
7978     switch (DstTy.getSimpleVT().SimpleTy) {
7979     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7980     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7981     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7982     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7983     }
7984
7985   SDValue Chain = DAG.getEntryNode();
7986   SDValue Value = Op.getOperand(0);
7987   EVT TheVT = Op.getOperand(0).getValueType();
7988   // FIXME This causes a redundant load/store if the SSE-class value is already
7989   // in memory, such as if it is on the callstack.
7990   if (isScalarFPTypeInSSEReg(TheVT)) {
7991     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7992     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7993                          MachinePointerInfo::getFixedStack(SSFI),
7994                          false, false, 0);
7995     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7996     SDValue Ops[] = {
7997       Chain, StackSlot, DAG.getValueType(TheVT)
7998     };
7999
8000     MachineMemOperand *MMO =
8001       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8002                               MachineMemOperand::MOLoad, MemSize, MemSize);
8003     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8004                                     DstTy, MMO);
8005     Chain = Value.getValue(1);
8006     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8007     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8008   }
8009
8010   MachineMemOperand *MMO =
8011     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8012                             MachineMemOperand::MOStore, MemSize, MemSize);
8013
8014   if (Opc != X86ISD::WIN_FTOL) {
8015     // Build the FP_TO_INT*_IN_MEM
8016     SDValue Ops[] = { Chain, Value, StackSlot };
8017     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8018                                            Ops, 3, DstTy, MMO);
8019     return std::make_pair(FIST, StackSlot);
8020   } else {
8021     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8022       DAG.getVTList(MVT::Other, MVT::Glue),
8023       Chain, Value);
8024     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8025       MVT::i32, ftol.getValue(1));
8026     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8027       MVT::i32, eax.getValue(2));
8028     SDValue Ops[] = { eax, edx };
8029     SDValue pair = IsReplace
8030       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8031       : DAG.getMergeValues(Ops, 2, DL);
8032     return std::make_pair(pair, SDValue());
8033   }
8034 }
8035
8036 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8037                                            SelectionDAG &DAG) const {
8038   if (Op.getValueType().isVector())
8039     return SDValue();
8040
8041   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8042     /*IsSigned=*/ true, /*IsReplace=*/ false);
8043   SDValue FIST = Vals.first, StackSlot = Vals.second;
8044   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8045   if (FIST.getNode() == 0) return Op;
8046
8047   if (StackSlot.getNode())
8048     // Load the result.
8049     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8050                        FIST, StackSlot, MachinePointerInfo(),
8051                        false, false, false, 0);
8052
8053   // The node is the result.
8054   return FIST;
8055 }
8056
8057 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8058                                            SelectionDAG &DAG) const {
8059   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8060     /*IsSigned=*/ false, /*IsReplace=*/ false);
8061   SDValue FIST = Vals.first, StackSlot = Vals.second;
8062   assert(FIST.getNode() && "Unexpected failure");
8063
8064   if (StackSlot.getNode())
8065     // Load the result.
8066     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8067                        FIST, StackSlot, MachinePointerInfo(),
8068                        false, false, false, 0);
8069
8070   // The node is the result.
8071   return FIST;
8072 }
8073
8074 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8075                                      SelectionDAG &DAG) const {
8076   LLVMContext *Context = DAG.getContext();
8077   DebugLoc dl = Op.getDebugLoc();
8078   EVT VT = Op.getValueType();
8079   EVT EltVT = VT;
8080   if (VT.isVector())
8081     EltVT = VT.getVectorElementType();
8082   Constant *C;
8083   if (EltVT == MVT::f64) {
8084     C = ConstantVector::getSplat(2, 
8085                 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8086   } else {
8087     C = ConstantVector::getSplat(4,
8088                ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8089   }
8090   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8091   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8092                              MachinePointerInfo::getConstantPool(),
8093                              false, false, false, 16);
8094   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8095 }
8096
8097 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8098   LLVMContext *Context = DAG.getContext();
8099   DebugLoc dl = Op.getDebugLoc();
8100   EVT VT = Op.getValueType();
8101   EVT EltVT = VT;
8102   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8103   if (VT.isVector()) {
8104     EltVT = VT.getVectorElementType();
8105     NumElts = VT.getVectorNumElements();
8106   }
8107   Constant *C;
8108   if (EltVT == MVT::f64)
8109     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8110   else
8111     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8112   C = ConstantVector::getSplat(NumElts, C);
8113   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8114   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8115                              MachinePointerInfo::getConstantPool(),
8116                              false, false, false, 16);
8117   if (VT.isVector()) {
8118     MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
8119     return DAG.getNode(ISD::BITCAST, dl, VT,
8120                        DAG.getNode(ISD::XOR, dl, XORVT,
8121                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8122                                                Op.getOperand(0)),
8123                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8124   }
8125
8126   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8127 }
8128
8129 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8130   LLVMContext *Context = DAG.getContext();
8131   SDValue Op0 = Op.getOperand(0);
8132   SDValue Op1 = Op.getOperand(1);
8133   DebugLoc dl = Op.getDebugLoc();
8134   EVT VT = Op.getValueType();
8135   EVT SrcVT = Op1.getValueType();
8136
8137   // If second operand is smaller, extend it first.
8138   if (SrcVT.bitsLT(VT)) {
8139     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8140     SrcVT = VT;
8141   }
8142   // And if it is bigger, shrink it first.
8143   if (SrcVT.bitsGT(VT)) {
8144     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8145     SrcVT = VT;
8146   }
8147
8148   // At this point the operands and the result should have the same
8149   // type, and that won't be f80 since that is not custom lowered.
8150
8151   // First get the sign bit of second operand.
8152   SmallVector<Constant*,4> CV;
8153   if (SrcVT == MVT::f64) {
8154     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8155     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8156   } else {
8157     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8158     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8159     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8160     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8161   }
8162   Constant *C = ConstantVector::get(CV);
8163   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8164   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8165                               MachinePointerInfo::getConstantPool(),
8166                               false, false, false, 16);
8167   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8168
8169   // Shift sign bit right or left if the two operands have different types.
8170   if (SrcVT.bitsGT(VT)) {
8171     // Op0 is MVT::f32, Op1 is MVT::f64.
8172     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8173     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8174                           DAG.getConstant(32, MVT::i32));
8175     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8176     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8177                           DAG.getIntPtrConstant(0));
8178   }
8179
8180   // Clear first operand sign bit.
8181   CV.clear();
8182   if (VT == MVT::f64) {
8183     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8184     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8185   } else {
8186     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8187     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8188     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8189     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8190   }
8191   C = ConstantVector::get(CV);
8192   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8193   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8194                               MachinePointerInfo::getConstantPool(),
8195                               false, false, false, 16);
8196   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8197
8198   // Or the value with the sign bit.
8199   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8200 }
8201
8202 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8203   SDValue N0 = Op.getOperand(0);
8204   DebugLoc dl = Op.getDebugLoc();
8205   EVT VT = Op.getValueType();
8206
8207   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8208   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8209                                   DAG.getConstant(1, VT));
8210   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8211 }
8212
8213 /// Emit nodes that will be selected as "test Op0,Op0", or something
8214 /// equivalent.
8215 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8216                                     SelectionDAG &DAG) const {
8217   DebugLoc dl = Op.getDebugLoc();
8218
8219   // CF and OF aren't always set the way we want. Determine which
8220   // of these we need.
8221   bool NeedCF = false;
8222   bool NeedOF = false;
8223   switch (X86CC) {
8224   default: break;
8225   case X86::COND_A: case X86::COND_AE:
8226   case X86::COND_B: case X86::COND_BE:
8227     NeedCF = true;
8228     break;
8229   case X86::COND_G: case X86::COND_GE:
8230   case X86::COND_L: case X86::COND_LE:
8231   case X86::COND_O: case X86::COND_NO:
8232     NeedOF = true;
8233     break;
8234   }
8235
8236   // See if we can use the EFLAGS value from the operand instead of
8237   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8238   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8239   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8240     // Emit a CMP with 0, which is the TEST pattern.
8241     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8242                        DAG.getConstant(0, Op.getValueType()));
8243
8244   unsigned Opcode = 0;
8245   unsigned NumOperands = 0;
8246   switch (Op.getNode()->getOpcode()) {
8247   case ISD::ADD:
8248     // Due to an isel shortcoming, be conservative if this add is likely to be
8249     // selected as part of a load-modify-store instruction. When the root node
8250     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8251     // uses of other nodes in the match, such as the ADD in this case. This
8252     // leads to the ADD being left around and reselected, with the result being
8253     // two adds in the output.  Alas, even if none our users are stores, that
8254     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8255     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8256     // climbing the DAG back to the root, and it doesn't seem to be worth the
8257     // effort.
8258     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8259          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8260       if (UI->getOpcode() != ISD::CopyToReg &&
8261           UI->getOpcode() != ISD::SETCC &&
8262           UI->getOpcode() != ISD::STORE)
8263         goto default_case;
8264
8265     if (ConstantSDNode *C =
8266         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8267       // An add of one will be selected as an INC.
8268       if (C->getAPIntValue() == 1) {
8269         Opcode = X86ISD::INC;
8270         NumOperands = 1;
8271         break;
8272       }
8273
8274       // An add of negative one (subtract of one) will be selected as a DEC.
8275       if (C->getAPIntValue().isAllOnesValue()) {
8276         Opcode = X86ISD::DEC;
8277         NumOperands = 1;
8278         break;
8279       }
8280     }
8281
8282     // Otherwise use a regular EFLAGS-setting add.
8283     Opcode = X86ISD::ADD;
8284     NumOperands = 2;
8285     break;
8286   case ISD::AND: {
8287     // If the primary and result isn't used, don't bother using X86ISD::AND,
8288     // because a TEST instruction will be better.
8289     bool NonFlagUse = false;
8290     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8291            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8292       SDNode *User = *UI;
8293       unsigned UOpNo = UI.getOperandNo();
8294       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8295         // Look pass truncate.
8296         UOpNo = User->use_begin().getOperandNo();
8297         User = *User->use_begin();
8298       }
8299
8300       if (User->getOpcode() != ISD::BRCOND &&
8301           User->getOpcode() != ISD::SETCC &&
8302           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8303         NonFlagUse = true;
8304         break;
8305       }
8306     }
8307
8308     if (!NonFlagUse)
8309       break;
8310   }
8311     // FALL THROUGH
8312   case ISD::SUB:
8313   case ISD::OR:
8314   case ISD::XOR:
8315     // Due to the ISEL shortcoming noted above, be conservative if this op is
8316     // likely to be selected as part of a load-modify-store instruction.
8317     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8318            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8319       if (UI->getOpcode() == ISD::STORE)
8320         goto default_case;
8321
8322     // Otherwise use a regular EFLAGS-setting instruction.
8323     switch (Op.getNode()->getOpcode()) {
8324     default: llvm_unreachable("unexpected operator!");
8325     case ISD::SUB:
8326       // If the only use of SUB is EFLAGS, use CMP instead.
8327       if (Op.hasOneUse())
8328         Opcode = X86ISD::CMP;
8329       else
8330         Opcode = X86ISD::SUB;
8331       break;
8332     case ISD::OR:  Opcode = X86ISD::OR;  break;
8333     case ISD::XOR: Opcode = X86ISD::XOR; break;
8334     case ISD::AND: Opcode = X86ISD::AND; break;
8335     }
8336
8337     NumOperands = 2;
8338     break;
8339   case X86ISD::ADD:
8340   case X86ISD::SUB:
8341   case X86ISD::INC:
8342   case X86ISD::DEC:
8343   case X86ISD::OR:
8344   case X86ISD::XOR:
8345   case X86ISD::AND:
8346     return SDValue(Op.getNode(), 1);
8347   default:
8348   default_case:
8349     break;
8350   }
8351
8352   if (Opcode == 0)
8353     // Emit a CMP with 0, which is the TEST pattern.
8354     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8355                        DAG.getConstant(0, Op.getValueType()));
8356
8357   if (Opcode == X86ISD::CMP) {
8358     SDValue New = DAG.getNode(Opcode, dl, MVT::i32, Op.getOperand(0),
8359                               Op.getOperand(1));
8360     // We can't replace usage of SUB with CMP.
8361     // The SUB node will be removed later because there is no use of it.
8362     return SDValue(New.getNode(), 0);
8363   }
8364
8365   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8366   SmallVector<SDValue, 4> Ops;
8367   for (unsigned i = 0; i != NumOperands; ++i)
8368     Ops.push_back(Op.getOperand(i));
8369
8370   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8371   DAG.ReplaceAllUsesWith(Op, New);
8372   return SDValue(New.getNode(), 1);
8373 }
8374
8375 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8376 /// equivalent.
8377 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8378                                    SelectionDAG &DAG) const {
8379   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8380     if (C->getAPIntValue() == 0)
8381       return EmitTest(Op0, X86CC, DAG);
8382
8383   DebugLoc dl = Op0.getDebugLoc();
8384   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8385 }
8386
8387 /// Convert a comparison if required by the subtarget.
8388 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8389                                                  SelectionDAG &DAG) const {
8390   // If the subtarget does not support the FUCOMI instruction, floating-point
8391   // comparisons have to be converted.
8392   if (Subtarget->hasCMov() ||
8393       Cmp.getOpcode() != X86ISD::CMP ||
8394       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8395       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8396     return Cmp;
8397
8398   // The instruction selector will select an FUCOM instruction instead of
8399   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8400   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8401   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8402   DebugLoc dl = Cmp.getDebugLoc();
8403   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8404   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8405   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8406                             DAG.getConstant(8, MVT::i8));
8407   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8408   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8409 }
8410
8411 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8412 /// if it's possible.
8413 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8414                                      DebugLoc dl, SelectionDAG &DAG) const {
8415   SDValue Op0 = And.getOperand(0);
8416   SDValue Op1 = And.getOperand(1);
8417   if (Op0.getOpcode() == ISD::TRUNCATE)
8418     Op0 = Op0.getOperand(0);
8419   if (Op1.getOpcode() == ISD::TRUNCATE)
8420     Op1 = Op1.getOperand(0);
8421
8422   SDValue LHS, RHS;
8423   if (Op1.getOpcode() == ISD::SHL)
8424     std::swap(Op0, Op1);
8425   if (Op0.getOpcode() == ISD::SHL) {
8426     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8427       if (And00C->getZExtValue() == 1) {
8428         // If we looked past a truncate, check that it's only truncating away
8429         // known zeros.
8430         unsigned BitWidth = Op0.getValueSizeInBits();
8431         unsigned AndBitWidth = And.getValueSizeInBits();
8432         if (BitWidth > AndBitWidth) {
8433           APInt Zeros, Ones;
8434           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8435           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8436             return SDValue();
8437         }
8438         LHS = Op1;
8439         RHS = Op0.getOperand(1);
8440       }
8441   } else if (Op1.getOpcode() == ISD::Constant) {
8442     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8443     uint64_t AndRHSVal = AndRHS->getZExtValue();
8444     SDValue AndLHS = Op0;
8445
8446     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8447       LHS = AndLHS.getOperand(0);
8448       RHS = AndLHS.getOperand(1);
8449     }
8450
8451     // Use BT if the immediate can't be encoded in a TEST instruction.
8452     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8453       LHS = AndLHS;
8454       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8455     }
8456   }
8457
8458   if (LHS.getNode()) {
8459     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8460     // instruction.  Since the shift amount is in-range-or-undefined, we know
8461     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8462     // the encoding for the i16 version is larger than the i32 version.
8463     // Also promote i16 to i32 for performance / code size reason.
8464     if (LHS.getValueType() == MVT::i8 ||
8465         LHS.getValueType() == MVT::i16)
8466       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8467
8468     // If the operand types disagree, extend the shift amount to match.  Since
8469     // BT ignores high bits (like shifts) we can use anyextend.
8470     if (LHS.getValueType() != RHS.getValueType())
8471       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8472
8473     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8474     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8475     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8476                        DAG.getConstant(Cond, MVT::i8), BT);
8477   }
8478
8479   return SDValue();
8480 }
8481
8482 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8483
8484   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8485
8486   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8487   SDValue Op0 = Op.getOperand(0);
8488   SDValue Op1 = Op.getOperand(1);
8489   DebugLoc dl = Op.getDebugLoc();
8490   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8491
8492   // Optimize to BT if possible.
8493   // Lower (X & (1 << N)) == 0 to BT(X, N).
8494   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8495   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8496   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8497       Op1.getOpcode() == ISD::Constant &&
8498       cast<ConstantSDNode>(Op1)->isNullValue() &&
8499       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8500     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8501     if (NewSetCC.getNode())
8502       return NewSetCC;
8503   }
8504
8505   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8506   // these.
8507   if (Op1.getOpcode() == ISD::Constant &&
8508       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8509        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8510       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8511
8512     // If the input is a setcc, then reuse the input setcc or use a new one with
8513     // the inverted condition.
8514     if (Op0.getOpcode() == X86ISD::SETCC) {
8515       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8516       bool Invert = (CC == ISD::SETNE) ^
8517         cast<ConstantSDNode>(Op1)->isNullValue();
8518       if (!Invert) return Op0;
8519
8520       CCode = X86::GetOppositeBranchCondition(CCode);
8521       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8522                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8523     }
8524   }
8525
8526   bool isFP = Op1.getValueType().isFloatingPoint();
8527   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8528   if (X86CC == X86::COND_INVALID)
8529     return SDValue();
8530
8531   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8532   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8533   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8534                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8535 }
8536
8537 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8538 // ones, and then concatenate the result back.
8539 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8540   EVT VT = Op.getValueType();
8541
8542   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8543          "Unsupported value type for operation");
8544
8545   unsigned NumElems = VT.getVectorNumElements();
8546   DebugLoc dl = Op.getDebugLoc();
8547   SDValue CC = Op.getOperand(2);
8548
8549   // Extract the LHS vectors
8550   SDValue LHS = Op.getOperand(0);
8551   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8552   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8553
8554   // Extract the RHS vectors
8555   SDValue RHS = Op.getOperand(1);
8556   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8557   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8558
8559   // Issue the operation on the smaller types and concatenate the result back
8560   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8561   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8562   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8563                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8564                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8565 }
8566
8567
8568 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8569   SDValue Cond;
8570   SDValue Op0 = Op.getOperand(0);
8571   SDValue Op1 = Op.getOperand(1);
8572   SDValue CC = Op.getOperand(2);
8573   EVT VT = Op.getValueType();
8574   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8575   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8576   DebugLoc dl = Op.getDebugLoc();
8577
8578   if (isFP) {
8579     unsigned SSECC = 8;
8580     EVT EltVT = Op0.getValueType().getVectorElementType();
8581     assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8582
8583     bool Swap = false;
8584
8585     // SSE Condition code mapping:
8586     //  0 - EQ
8587     //  1 - LT
8588     //  2 - LE
8589     //  3 - UNORD
8590     //  4 - NEQ
8591     //  5 - NLT
8592     //  6 - NLE
8593     //  7 - ORD
8594     switch (SetCCOpcode) {
8595     default: break;
8596     case ISD::SETOEQ:
8597     case ISD::SETEQ:  SSECC = 0; break;
8598     case ISD::SETOGT:
8599     case ISD::SETGT: Swap = true; // Fallthrough
8600     case ISD::SETLT:
8601     case ISD::SETOLT: SSECC = 1; break;
8602     case ISD::SETOGE:
8603     case ISD::SETGE: Swap = true; // Fallthrough
8604     case ISD::SETLE:
8605     case ISD::SETOLE: SSECC = 2; break;
8606     case ISD::SETUO:  SSECC = 3; break;
8607     case ISD::SETUNE:
8608     case ISD::SETNE:  SSECC = 4; break;
8609     case ISD::SETULE: Swap = true;
8610     case ISD::SETUGE: SSECC = 5; break;
8611     case ISD::SETULT: Swap = true;
8612     case ISD::SETUGT: SSECC = 6; break;
8613     case ISD::SETO:   SSECC = 7; break;
8614     }
8615     if (Swap)
8616       std::swap(Op0, Op1);
8617
8618     // In the two special cases we can't handle, emit two comparisons.
8619     if (SSECC == 8) {
8620       if (SetCCOpcode == ISD::SETUEQ) {
8621         SDValue UNORD, EQ;
8622         UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8623                             DAG.getConstant(3, MVT::i8));
8624         EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8625                          DAG.getConstant(0, MVT::i8));
8626         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8627       }
8628       if (SetCCOpcode == ISD::SETONE) {
8629         SDValue ORD, NEQ;
8630         ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8631                           DAG.getConstant(7, MVT::i8));
8632         NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8633                           DAG.getConstant(4, MVT::i8));
8634         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8635       }
8636       llvm_unreachable("Illegal FP comparison");
8637     }
8638     // Handle all other FP comparisons here.
8639     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8640                        DAG.getConstant(SSECC, MVT::i8));
8641   }
8642
8643   // Break 256-bit integer vector compare into smaller ones.
8644   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8645     return Lower256IntVSETCC(Op, DAG);
8646
8647   // We are handling one of the integer comparisons here.  Since SSE only has
8648   // GT and EQ comparisons for integer, swapping operands and multiple
8649   // operations may be required for some comparisons.
8650   unsigned Opc = 0;
8651   bool Swap = false, Invert = false, FlipSigns = false;
8652
8653   switch (SetCCOpcode) {
8654   default: break;
8655   case ISD::SETNE:  Invert = true;
8656   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8657   case ISD::SETLT:  Swap = true;
8658   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8659   case ISD::SETGE:  Swap = true;
8660   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8661   case ISD::SETULT: Swap = true;
8662   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8663   case ISD::SETUGE: Swap = true;
8664   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8665   }
8666   if (Swap)
8667     std::swap(Op0, Op1);
8668
8669   // Check that the operation in question is available (most are plain SSE2,
8670   // but PCMPGTQ and PCMPEQQ have different requirements).
8671   if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8672     return SDValue();
8673   if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8674     return SDValue();
8675
8676   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8677   // bits of the inputs before performing those operations.
8678   if (FlipSigns) {
8679     EVT EltVT = VT.getVectorElementType();
8680     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8681                                       EltVT);
8682     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8683     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8684                                     SignBits.size());
8685     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8686     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8687   }
8688
8689   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8690
8691   // If the logical-not of the result is required, perform that now.
8692   if (Invert)
8693     Result = DAG.getNOT(dl, Result, VT);
8694
8695   return Result;
8696 }
8697
8698 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8699 static bool isX86LogicalCmp(SDValue Op) {
8700   unsigned Opc = Op.getNode()->getOpcode();
8701   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8702       Opc == X86ISD::SAHF)
8703     return true;
8704   if (Op.getResNo() == 1 &&
8705       (Opc == X86ISD::ADD ||
8706        Opc == X86ISD::SUB ||
8707        Opc == X86ISD::ADC ||
8708        Opc == X86ISD::SBB ||
8709        Opc == X86ISD::SMUL ||
8710        Opc == X86ISD::UMUL ||
8711        Opc == X86ISD::INC ||
8712        Opc == X86ISD::DEC ||
8713        Opc == X86ISD::OR ||
8714        Opc == X86ISD::XOR ||
8715        Opc == X86ISD::AND))
8716     return true;
8717
8718   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8719     return true;
8720
8721   return false;
8722 }
8723
8724 static bool isZero(SDValue V) {
8725   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8726   return C && C->isNullValue();
8727 }
8728
8729 static bool isAllOnes(SDValue V) {
8730   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8731   return C && C->isAllOnesValue();
8732 }
8733
8734 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8735   bool addTest = true;
8736   SDValue Cond  = Op.getOperand(0);
8737   SDValue Op1 = Op.getOperand(1);
8738   SDValue Op2 = Op.getOperand(2);
8739   DebugLoc DL = Op.getDebugLoc();
8740   SDValue CC;
8741
8742   if (Cond.getOpcode() == ISD::SETCC) {
8743     SDValue NewCond = LowerSETCC(Cond, DAG);
8744     if (NewCond.getNode())
8745       Cond = NewCond;
8746   }
8747
8748   // Handle the following cases related to max and min:
8749   // (a > b) ? (a-b) : 0
8750   // (a >= b) ? (a-b) : 0
8751   // (b < a) ? (a-b) : 0
8752   // (b <= a) ? (a-b) : 0
8753   // Comparison is removed to use EFLAGS from SUB.
8754   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2))
8755     if (Cond.getOpcode() == X86ISD::SETCC &&
8756         Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8757         (Op1.getOpcode() == ISD::SUB || Op1.getOpcode() == X86ISD::SUB) &&
8758         C->getAPIntValue() == 0) {
8759       SDValue Cmp = Cond.getOperand(1);
8760       unsigned CC = cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8761       if ((DAG.isEqualTo(Op1.getOperand(0), Cmp.getOperand(0)) &&
8762            DAG.isEqualTo(Op1.getOperand(1), Cmp.getOperand(1)) &&
8763            (CC == X86::COND_G || CC == X86::COND_GE ||
8764             CC == X86::COND_A || CC == X86::COND_AE)) ||
8765           (DAG.isEqualTo(Op1.getOperand(0), Cmp.getOperand(1)) &&
8766            DAG.isEqualTo(Op1.getOperand(1), Cmp.getOperand(0)) &&
8767            (CC == X86::COND_L || CC == X86::COND_LE ||
8768             CC == X86::COND_B || CC == X86::COND_BE))) {
8769
8770         if (Op1.getOpcode() == ISD::SUB) {
8771           SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i32);
8772           SDValue New = DAG.getNode(X86ISD::SUB, DL, VTs,
8773                                     Op1.getOperand(0), Op1.getOperand(1));
8774           DAG.ReplaceAllUsesWith(Op1, New);
8775           Op1 = New;
8776         }
8777
8778         SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8779         unsigned NewCC = (CC == X86::COND_G || CC == X86::COND_GE ||
8780                           CC == X86::COND_L ||
8781                           CC == X86::COND_LE) ? X86::COND_GE : X86::COND_AE;
8782         SDValue Ops[] = { Op2, Op1, DAG.getConstant(NewCC, MVT::i8),
8783                           SDValue(Op1.getNode(), 1) };
8784         return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8785       }
8786     }
8787
8788   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8789   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8790   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8791   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8792   if (Cond.getOpcode() == X86ISD::SETCC &&
8793       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8794       isZero(Cond.getOperand(1).getOperand(1))) {
8795     SDValue Cmp = Cond.getOperand(1);
8796
8797     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8798
8799     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8800         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8801       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8802
8803       SDValue CmpOp0 = Cmp.getOperand(0);
8804       // Apply further optimizations for special cases
8805       // (select (x != 0), -1, 0) -> neg & sbb
8806       // (select (x == 0), 0, -1) -> neg & sbb
8807       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8808         if (YC->isNullValue() && 
8809             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8810           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8811           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs, 
8812                                     DAG.getConstant(0, CmpOp0.getValueType()), 
8813                                     CmpOp0);
8814           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8815                                     DAG.getConstant(X86::COND_B, MVT::i8),
8816                                     SDValue(Neg.getNode(), 1));
8817           return Res;
8818         }
8819
8820       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8821                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8822       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8823
8824       SDValue Res =   // Res = 0 or -1.
8825         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8826                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8827
8828       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8829         Res = DAG.getNOT(DL, Res, Res.getValueType());
8830
8831       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8832       if (N2C == 0 || !N2C->isNullValue())
8833         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8834       return Res;
8835     }
8836   }
8837
8838   // Look past (and (setcc_carry (cmp ...)), 1).
8839   if (Cond.getOpcode() == ISD::AND &&
8840       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8841     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8842     if (C && C->getAPIntValue() == 1)
8843       Cond = Cond.getOperand(0);
8844   }
8845
8846   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8847   // setting operand in place of the X86ISD::SETCC.
8848   unsigned CondOpcode = Cond.getOpcode();
8849   if (CondOpcode == X86ISD::SETCC ||
8850       CondOpcode == X86ISD::SETCC_CARRY) {
8851     CC = Cond.getOperand(0);
8852
8853     SDValue Cmp = Cond.getOperand(1);
8854     unsigned Opc = Cmp.getOpcode();
8855     EVT VT = Op.getValueType();
8856
8857     bool IllegalFPCMov = false;
8858     if (VT.isFloatingPoint() && !VT.isVector() &&
8859         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8860       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8861
8862     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8863         Opc == X86ISD::BT) { // FIXME
8864       Cond = Cmp;
8865       addTest = false;
8866     }
8867   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8868              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8869              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8870               Cond.getOperand(0).getValueType() != MVT::i8)) {
8871     SDValue LHS = Cond.getOperand(0);
8872     SDValue RHS = Cond.getOperand(1);
8873     unsigned X86Opcode;
8874     unsigned X86Cond;
8875     SDVTList VTs;
8876     switch (CondOpcode) {
8877     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8878     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8879     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8880     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8881     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8882     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8883     default: llvm_unreachable("unexpected overflowing operator");
8884     }
8885     if (CondOpcode == ISD::UMULO)
8886       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8887                           MVT::i32);
8888     else
8889       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8890
8891     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8892
8893     if (CondOpcode == ISD::UMULO)
8894       Cond = X86Op.getValue(2);
8895     else
8896       Cond = X86Op.getValue(1);
8897
8898     CC = DAG.getConstant(X86Cond, MVT::i8);
8899     addTest = false;
8900   }
8901
8902   if (addTest) {
8903     // Look pass the truncate.
8904     if (Cond.getOpcode() == ISD::TRUNCATE)
8905       Cond = Cond.getOperand(0);
8906
8907     // We know the result of AND is compared against zero. Try to match
8908     // it to BT.
8909     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8910       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8911       if (NewSetCC.getNode()) {
8912         CC = NewSetCC.getOperand(0);
8913         Cond = NewSetCC.getOperand(1);
8914         addTest = false;
8915       }
8916     }
8917   }
8918
8919   if (addTest) {
8920     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8921     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8922   }
8923
8924   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8925   // a <  b ?  0 : -1 -> RES = setcc_carry
8926   // a >= b ? -1 :  0 -> RES = setcc_carry
8927   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8928   if (Cond.getOpcode() == X86ISD::CMP) {
8929     Cond = ConvertCmpIfNecessary(Cond, DAG);
8930     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8931
8932     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8933         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8934       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8935                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8936       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8937         return DAG.getNOT(DL, Res, Res.getValueType());
8938       return Res;
8939     }
8940   }
8941
8942   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8943   // condition is true.
8944   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8945   SDValue Ops[] = { Op2, Op1, CC, Cond };
8946   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8947 }
8948
8949 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8950 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8951 // from the AND / OR.
8952 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8953   Opc = Op.getOpcode();
8954   if (Opc != ISD::OR && Opc != ISD::AND)
8955     return false;
8956   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8957           Op.getOperand(0).hasOneUse() &&
8958           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8959           Op.getOperand(1).hasOneUse());
8960 }
8961
8962 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8963 // 1 and that the SETCC node has a single use.
8964 static bool isXor1OfSetCC(SDValue Op) {
8965   if (Op.getOpcode() != ISD::XOR)
8966     return false;
8967   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8968   if (N1C && N1C->getAPIntValue() == 1) {
8969     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8970       Op.getOperand(0).hasOneUse();
8971   }
8972   return false;
8973 }
8974
8975 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8976   bool addTest = true;
8977   SDValue Chain = Op.getOperand(0);
8978   SDValue Cond  = Op.getOperand(1);
8979   SDValue Dest  = Op.getOperand(2);
8980   DebugLoc dl = Op.getDebugLoc();
8981   SDValue CC;
8982   bool Inverted = false;
8983
8984   if (Cond.getOpcode() == ISD::SETCC) {
8985     // Check for setcc([su]{add,sub,mul}o == 0).
8986     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8987         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8988         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8989         Cond.getOperand(0).getResNo() == 1 &&
8990         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8991          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8992          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8993          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8994          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8995          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8996       Inverted = true;
8997       Cond = Cond.getOperand(0);
8998     } else {
8999       SDValue NewCond = LowerSETCC(Cond, DAG);
9000       if (NewCond.getNode())
9001         Cond = NewCond;
9002     }
9003   }
9004 #if 0
9005   // FIXME: LowerXALUO doesn't handle these!!
9006   else if (Cond.getOpcode() == X86ISD::ADD  ||
9007            Cond.getOpcode() == X86ISD::SUB  ||
9008            Cond.getOpcode() == X86ISD::SMUL ||
9009            Cond.getOpcode() == X86ISD::UMUL)
9010     Cond = LowerXALUO(Cond, DAG);
9011 #endif
9012
9013   // Look pass (and (setcc_carry (cmp ...)), 1).
9014   if (Cond.getOpcode() == ISD::AND &&
9015       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9016     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9017     if (C && C->getAPIntValue() == 1)
9018       Cond = Cond.getOperand(0);
9019   }
9020
9021   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9022   // setting operand in place of the X86ISD::SETCC.
9023   unsigned CondOpcode = Cond.getOpcode();
9024   if (CondOpcode == X86ISD::SETCC ||
9025       CondOpcode == X86ISD::SETCC_CARRY) {
9026     CC = Cond.getOperand(0);
9027
9028     SDValue Cmp = Cond.getOperand(1);
9029     unsigned Opc = Cmp.getOpcode();
9030     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9031     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9032       Cond = Cmp;
9033       addTest = false;
9034     } else {
9035       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9036       default: break;
9037       case X86::COND_O:
9038       case X86::COND_B:
9039         // These can only come from an arithmetic instruction with overflow,
9040         // e.g. SADDO, UADDO.
9041         Cond = Cond.getNode()->getOperand(1);
9042         addTest = false;
9043         break;
9044       }
9045     }
9046   }
9047   CondOpcode = Cond.getOpcode();
9048   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9049       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9050       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9051        Cond.getOperand(0).getValueType() != MVT::i8)) {
9052     SDValue LHS = Cond.getOperand(0);
9053     SDValue RHS = Cond.getOperand(1);
9054     unsigned X86Opcode;
9055     unsigned X86Cond;
9056     SDVTList VTs;
9057     switch (CondOpcode) {
9058     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9059     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9060     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9061     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9062     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9063     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9064     default: llvm_unreachable("unexpected overflowing operator");
9065     }
9066     if (Inverted)
9067       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9068     if (CondOpcode == ISD::UMULO)
9069       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9070                           MVT::i32);
9071     else
9072       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9073
9074     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9075
9076     if (CondOpcode == ISD::UMULO)
9077       Cond = X86Op.getValue(2);
9078     else
9079       Cond = X86Op.getValue(1);
9080
9081     CC = DAG.getConstant(X86Cond, MVT::i8);
9082     addTest = false;
9083   } else {
9084     unsigned CondOpc;
9085     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9086       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9087       if (CondOpc == ISD::OR) {
9088         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9089         // two branches instead of an explicit OR instruction with a
9090         // separate test.
9091         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9092             isX86LogicalCmp(Cmp)) {
9093           CC = Cond.getOperand(0).getOperand(0);
9094           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9095                               Chain, Dest, CC, Cmp);
9096           CC = Cond.getOperand(1).getOperand(0);
9097           Cond = Cmp;
9098           addTest = false;
9099         }
9100       } else { // ISD::AND
9101         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9102         // two branches instead of an explicit AND instruction with a
9103         // separate test. However, we only do this if this block doesn't
9104         // have a fall-through edge, because this requires an explicit
9105         // jmp when the condition is false.
9106         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9107             isX86LogicalCmp(Cmp) &&
9108             Op.getNode()->hasOneUse()) {
9109           X86::CondCode CCode =
9110             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9111           CCode = X86::GetOppositeBranchCondition(CCode);
9112           CC = DAG.getConstant(CCode, MVT::i8);
9113           SDNode *User = *Op.getNode()->use_begin();
9114           // Look for an unconditional branch following this conditional branch.
9115           // We need this because we need to reverse the successors in order
9116           // to implement FCMP_OEQ.
9117           if (User->getOpcode() == ISD::BR) {
9118             SDValue FalseBB = User->getOperand(1);
9119             SDNode *NewBR =
9120               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9121             assert(NewBR == User);
9122             (void)NewBR;
9123             Dest = FalseBB;
9124
9125             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9126                                 Chain, Dest, CC, Cmp);
9127             X86::CondCode CCode =
9128               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9129             CCode = X86::GetOppositeBranchCondition(CCode);
9130             CC = DAG.getConstant(CCode, MVT::i8);
9131             Cond = Cmp;
9132             addTest = false;
9133           }
9134         }
9135       }
9136     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9137       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9138       // It should be transformed during dag combiner except when the condition
9139       // is set by a arithmetics with overflow node.
9140       X86::CondCode CCode =
9141         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9142       CCode = X86::GetOppositeBranchCondition(CCode);
9143       CC = DAG.getConstant(CCode, MVT::i8);
9144       Cond = Cond.getOperand(0).getOperand(1);
9145       addTest = false;
9146     } else if (Cond.getOpcode() == ISD::SETCC &&
9147                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9148       // For FCMP_OEQ, we can emit
9149       // two branches instead of an explicit AND instruction with a
9150       // separate test. However, we only do this if this block doesn't
9151       // have a fall-through edge, because this requires an explicit
9152       // jmp when the condition is false.
9153       if (Op.getNode()->hasOneUse()) {
9154         SDNode *User = *Op.getNode()->use_begin();
9155         // Look for an unconditional branch following this conditional branch.
9156         // We need this because we need to reverse the successors in order
9157         // to implement FCMP_OEQ.
9158         if (User->getOpcode() == ISD::BR) {
9159           SDValue FalseBB = User->getOperand(1);
9160           SDNode *NewBR =
9161             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9162           assert(NewBR == User);
9163           (void)NewBR;
9164           Dest = FalseBB;
9165
9166           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9167                                     Cond.getOperand(0), Cond.getOperand(1));
9168           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9169           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9170           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9171                               Chain, Dest, CC, Cmp);
9172           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9173           Cond = Cmp;
9174           addTest = false;
9175         }
9176       }
9177     } else if (Cond.getOpcode() == ISD::SETCC &&
9178                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9179       // For FCMP_UNE, we can emit
9180       // two branches instead of an explicit AND instruction with a
9181       // separate test. However, we only do this if this block doesn't
9182       // have a fall-through edge, because this requires an explicit
9183       // jmp when the condition is false.
9184       if (Op.getNode()->hasOneUse()) {
9185         SDNode *User = *Op.getNode()->use_begin();
9186         // Look for an unconditional branch following this conditional branch.
9187         // We need this because we need to reverse the successors in order
9188         // to implement FCMP_UNE.
9189         if (User->getOpcode() == ISD::BR) {
9190           SDValue FalseBB = User->getOperand(1);
9191           SDNode *NewBR =
9192             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9193           assert(NewBR == User);
9194           (void)NewBR;
9195
9196           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9197                                     Cond.getOperand(0), Cond.getOperand(1));
9198           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9199           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9200           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9201                               Chain, Dest, CC, Cmp);
9202           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9203           Cond = Cmp;
9204           addTest = false;
9205           Dest = FalseBB;
9206         }
9207       }
9208     }
9209   }
9210
9211   if (addTest) {
9212     // Look pass the truncate.
9213     if (Cond.getOpcode() == ISD::TRUNCATE)
9214       Cond = Cond.getOperand(0);
9215
9216     // We know the result of AND is compared against zero. Try to match
9217     // it to BT.
9218     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9219       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9220       if (NewSetCC.getNode()) {
9221         CC = NewSetCC.getOperand(0);
9222         Cond = NewSetCC.getOperand(1);
9223         addTest = false;
9224       }
9225     }
9226   }
9227
9228   if (addTest) {
9229     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9230     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9231   }
9232   Cond = ConvertCmpIfNecessary(Cond, DAG);
9233   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9234                      Chain, Dest, CC, Cond);
9235 }
9236
9237
9238 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9239 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9240 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9241 // that the guard pages used by the OS virtual memory manager are allocated in
9242 // correct sequence.
9243 SDValue
9244 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9245                                            SelectionDAG &DAG) const {
9246   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9247           getTargetMachine().Options.EnableSegmentedStacks) &&
9248          "This should be used only on Windows targets or when segmented stacks "
9249          "are being used");
9250   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9251   DebugLoc dl = Op.getDebugLoc();
9252
9253   // Get the inputs.
9254   SDValue Chain = Op.getOperand(0);
9255   SDValue Size  = Op.getOperand(1);
9256   // FIXME: Ensure alignment here
9257
9258   bool Is64Bit = Subtarget->is64Bit();
9259   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9260
9261   if (getTargetMachine().Options.EnableSegmentedStacks) {
9262     MachineFunction &MF = DAG.getMachineFunction();
9263     MachineRegisterInfo &MRI = MF.getRegInfo();
9264
9265     if (Is64Bit) {
9266       // The 64 bit implementation of segmented stacks needs to clobber both r10
9267       // r11. This makes it impossible to use it along with nested parameters.
9268       const Function *F = MF.getFunction();
9269
9270       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9271            I != E; ++I)
9272         if (I->hasNestAttr())
9273           report_fatal_error("Cannot use segmented stacks with functions that "
9274                              "have nested arguments.");
9275     }
9276
9277     const TargetRegisterClass *AddrRegClass =
9278       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9279     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9280     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9281     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9282                                 DAG.getRegister(Vreg, SPTy));
9283     SDValue Ops1[2] = { Value, Chain };
9284     return DAG.getMergeValues(Ops1, 2, dl);
9285   } else {
9286     SDValue Flag;
9287     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9288
9289     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9290     Flag = Chain.getValue(1);
9291     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9292
9293     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9294     Flag = Chain.getValue(1);
9295
9296     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9297
9298     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9299     return DAG.getMergeValues(Ops1, 2, dl);
9300   }
9301 }
9302
9303 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9304   MachineFunction &MF = DAG.getMachineFunction();
9305   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9306
9307   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9308   DebugLoc DL = Op.getDebugLoc();
9309
9310   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9311     // vastart just stores the address of the VarArgsFrameIndex slot into the
9312     // memory location argument.
9313     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9314                                    getPointerTy());
9315     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9316                         MachinePointerInfo(SV), false, false, 0);
9317   }
9318
9319   // __va_list_tag:
9320   //   gp_offset         (0 - 6 * 8)
9321   //   fp_offset         (48 - 48 + 8 * 16)
9322   //   overflow_arg_area (point to parameters coming in memory).
9323   //   reg_save_area
9324   SmallVector<SDValue, 8> MemOps;
9325   SDValue FIN = Op.getOperand(1);
9326   // Store gp_offset
9327   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9328                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9329                                                MVT::i32),
9330                                FIN, MachinePointerInfo(SV), false, false, 0);
9331   MemOps.push_back(Store);
9332
9333   // Store fp_offset
9334   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9335                     FIN, DAG.getIntPtrConstant(4));
9336   Store = DAG.getStore(Op.getOperand(0), DL,
9337                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9338                                        MVT::i32),
9339                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9340   MemOps.push_back(Store);
9341
9342   // Store ptr to overflow_arg_area
9343   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9344                     FIN, DAG.getIntPtrConstant(4));
9345   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9346                                     getPointerTy());
9347   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9348                        MachinePointerInfo(SV, 8),
9349                        false, false, 0);
9350   MemOps.push_back(Store);
9351
9352   // Store ptr to reg_save_area.
9353   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9354                     FIN, DAG.getIntPtrConstant(8));
9355   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9356                                     getPointerTy());
9357   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9358                        MachinePointerInfo(SV, 16), false, false, 0);
9359   MemOps.push_back(Store);
9360   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9361                      &MemOps[0], MemOps.size());
9362 }
9363
9364 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9365   assert(Subtarget->is64Bit() &&
9366          "LowerVAARG only handles 64-bit va_arg!");
9367   assert((Subtarget->isTargetLinux() ||
9368           Subtarget->isTargetDarwin()) &&
9369           "Unhandled target in LowerVAARG");
9370   assert(Op.getNode()->getNumOperands() == 4);
9371   SDValue Chain = Op.getOperand(0);
9372   SDValue SrcPtr = Op.getOperand(1);
9373   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9374   unsigned Align = Op.getConstantOperandVal(3);
9375   DebugLoc dl = Op.getDebugLoc();
9376
9377   EVT ArgVT = Op.getNode()->getValueType(0);
9378   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9379   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9380   uint8_t ArgMode;
9381
9382   // Decide which area this value should be read from.
9383   // TODO: Implement the AMD64 ABI in its entirety. This simple
9384   // selection mechanism works only for the basic types.
9385   if (ArgVT == MVT::f80) {
9386     llvm_unreachable("va_arg for f80 not yet implemented");
9387   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9388     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9389   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9390     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9391   } else {
9392     llvm_unreachable("Unhandled argument type in LowerVAARG");
9393   }
9394
9395   if (ArgMode == 2) {
9396     // Sanity Check: Make sure using fp_offset makes sense.
9397     assert(!getTargetMachine().Options.UseSoftFloat &&
9398            !(DAG.getMachineFunction()
9399                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9400            Subtarget->hasSSE1());
9401   }
9402
9403   // Insert VAARG_64 node into the DAG
9404   // VAARG_64 returns two values: Variable Argument Address, Chain
9405   SmallVector<SDValue, 11> InstOps;
9406   InstOps.push_back(Chain);
9407   InstOps.push_back(SrcPtr);
9408   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9409   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9410   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9411   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9412   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9413                                           VTs, &InstOps[0], InstOps.size(),
9414                                           MVT::i64,
9415                                           MachinePointerInfo(SV),
9416                                           /*Align=*/0,
9417                                           /*Volatile=*/false,
9418                                           /*ReadMem=*/true,
9419                                           /*WriteMem=*/true);
9420   Chain = VAARG.getValue(1);
9421
9422   // Load the next argument and return it
9423   return DAG.getLoad(ArgVT, dl,
9424                      Chain,
9425                      VAARG,
9426                      MachinePointerInfo(),
9427                      false, false, false, 0);
9428 }
9429
9430 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9431   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9432   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9433   SDValue Chain = Op.getOperand(0);
9434   SDValue DstPtr = Op.getOperand(1);
9435   SDValue SrcPtr = Op.getOperand(2);
9436   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9437   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9438   DebugLoc DL = Op.getDebugLoc();
9439
9440   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9441                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9442                        false,
9443                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9444 }
9445
9446 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9447 // may or may not be a constant. Takes immediate version of shift as input.
9448 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9449                                    SDValue SrcOp, SDValue ShAmt,
9450                                    SelectionDAG &DAG) {
9451   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9452
9453   if (isa<ConstantSDNode>(ShAmt)) {
9454     switch (Opc) {
9455       default: llvm_unreachable("Unknown target vector shift node");
9456       case X86ISD::VSHLI:
9457       case X86ISD::VSRLI:
9458       case X86ISD::VSRAI:
9459         return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9460     }
9461   }
9462
9463   // Change opcode to non-immediate version
9464   switch (Opc) {
9465     default: llvm_unreachable("Unknown target vector shift node");
9466     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9467     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9468     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9469   }
9470
9471   // Need to build a vector containing shift amount
9472   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9473   SDValue ShOps[4];
9474   ShOps[0] = ShAmt;
9475   ShOps[1] = DAG.getConstant(0, MVT::i32);
9476   ShOps[2] = DAG.getUNDEF(MVT::i32);
9477   ShOps[3] = DAG.getUNDEF(MVT::i32);
9478   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9479   ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9480   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9481 }
9482
9483 SDValue
9484 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9485   DebugLoc dl = Op.getDebugLoc();
9486   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9487   switch (IntNo) {
9488   default: return SDValue();    // Don't custom lower most intrinsics.
9489   // Comparison intrinsics.
9490   case Intrinsic::x86_sse_comieq_ss:
9491   case Intrinsic::x86_sse_comilt_ss:
9492   case Intrinsic::x86_sse_comile_ss:
9493   case Intrinsic::x86_sse_comigt_ss:
9494   case Intrinsic::x86_sse_comige_ss:
9495   case Intrinsic::x86_sse_comineq_ss:
9496   case Intrinsic::x86_sse_ucomieq_ss:
9497   case Intrinsic::x86_sse_ucomilt_ss:
9498   case Intrinsic::x86_sse_ucomile_ss:
9499   case Intrinsic::x86_sse_ucomigt_ss:
9500   case Intrinsic::x86_sse_ucomige_ss:
9501   case Intrinsic::x86_sse_ucomineq_ss:
9502   case Intrinsic::x86_sse2_comieq_sd:
9503   case Intrinsic::x86_sse2_comilt_sd:
9504   case Intrinsic::x86_sse2_comile_sd:
9505   case Intrinsic::x86_sse2_comigt_sd:
9506   case Intrinsic::x86_sse2_comige_sd:
9507   case Intrinsic::x86_sse2_comineq_sd:
9508   case Intrinsic::x86_sse2_ucomieq_sd:
9509   case Intrinsic::x86_sse2_ucomilt_sd:
9510   case Intrinsic::x86_sse2_ucomile_sd:
9511   case Intrinsic::x86_sse2_ucomigt_sd:
9512   case Intrinsic::x86_sse2_ucomige_sd:
9513   case Intrinsic::x86_sse2_ucomineq_sd: {
9514     unsigned Opc = 0;
9515     ISD::CondCode CC = ISD::SETCC_INVALID;
9516     switch (IntNo) {
9517     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9518     case Intrinsic::x86_sse_comieq_ss:
9519     case Intrinsic::x86_sse2_comieq_sd:
9520       Opc = X86ISD::COMI;
9521       CC = ISD::SETEQ;
9522       break;
9523     case Intrinsic::x86_sse_comilt_ss:
9524     case Intrinsic::x86_sse2_comilt_sd:
9525       Opc = X86ISD::COMI;
9526       CC = ISD::SETLT;
9527       break;
9528     case Intrinsic::x86_sse_comile_ss:
9529     case Intrinsic::x86_sse2_comile_sd:
9530       Opc = X86ISD::COMI;
9531       CC = ISD::SETLE;
9532       break;
9533     case Intrinsic::x86_sse_comigt_ss:
9534     case Intrinsic::x86_sse2_comigt_sd:
9535       Opc = X86ISD::COMI;
9536       CC = ISD::SETGT;
9537       break;
9538     case Intrinsic::x86_sse_comige_ss:
9539     case Intrinsic::x86_sse2_comige_sd:
9540       Opc = X86ISD::COMI;
9541       CC = ISD::SETGE;
9542       break;
9543     case Intrinsic::x86_sse_comineq_ss:
9544     case Intrinsic::x86_sse2_comineq_sd:
9545       Opc = X86ISD::COMI;
9546       CC = ISD::SETNE;
9547       break;
9548     case Intrinsic::x86_sse_ucomieq_ss:
9549     case Intrinsic::x86_sse2_ucomieq_sd:
9550       Opc = X86ISD::UCOMI;
9551       CC = ISD::SETEQ;
9552       break;
9553     case Intrinsic::x86_sse_ucomilt_ss:
9554     case Intrinsic::x86_sse2_ucomilt_sd:
9555       Opc = X86ISD::UCOMI;
9556       CC = ISD::SETLT;
9557       break;
9558     case Intrinsic::x86_sse_ucomile_ss:
9559     case Intrinsic::x86_sse2_ucomile_sd:
9560       Opc = X86ISD::UCOMI;
9561       CC = ISD::SETLE;
9562       break;
9563     case Intrinsic::x86_sse_ucomigt_ss:
9564     case Intrinsic::x86_sse2_ucomigt_sd:
9565       Opc = X86ISD::UCOMI;
9566       CC = ISD::SETGT;
9567       break;
9568     case Intrinsic::x86_sse_ucomige_ss:
9569     case Intrinsic::x86_sse2_ucomige_sd:
9570       Opc = X86ISD::UCOMI;
9571       CC = ISD::SETGE;
9572       break;
9573     case Intrinsic::x86_sse_ucomineq_ss:
9574     case Intrinsic::x86_sse2_ucomineq_sd:
9575       Opc = X86ISD::UCOMI;
9576       CC = ISD::SETNE;
9577       break;
9578     }
9579
9580     SDValue LHS = Op.getOperand(1);
9581     SDValue RHS = Op.getOperand(2);
9582     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9583     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9584     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9585     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9586                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9587     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9588   }
9589   // Arithmetic intrinsics.
9590   case Intrinsic::x86_sse2_pmulu_dq:
9591   case Intrinsic::x86_avx2_pmulu_dq:
9592     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9593                        Op.getOperand(1), Op.getOperand(2));
9594   case Intrinsic::x86_sse3_hadd_ps:
9595   case Intrinsic::x86_sse3_hadd_pd:
9596   case Intrinsic::x86_avx_hadd_ps_256:
9597   case Intrinsic::x86_avx_hadd_pd_256:
9598     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9599                        Op.getOperand(1), Op.getOperand(2));
9600   case Intrinsic::x86_sse3_hsub_ps:
9601   case Intrinsic::x86_sse3_hsub_pd:
9602   case Intrinsic::x86_avx_hsub_ps_256:
9603   case Intrinsic::x86_avx_hsub_pd_256:
9604     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9605                        Op.getOperand(1), Op.getOperand(2));
9606   case Intrinsic::x86_ssse3_phadd_w_128:
9607   case Intrinsic::x86_ssse3_phadd_d_128:
9608   case Intrinsic::x86_avx2_phadd_w:
9609   case Intrinsic::x86_avx2_phadd_d:
9610     return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9611                        Op.getOperand(1), Op.getOperand(2));
9612   case Intrinsic::x86_ssse3_phsub_w_128:
9613   case Intrinsic::x86_ssse3_phsub_d_128:
9614   case Intrinsic::x86_avx2_phsub_w:
9615   case Intrinsic::x86_avx2_phsub_d:
9616     return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9617                        Op.getOperand(1), Op.getOperand(2));
9618   case Intrinsic::x86_avx2_psllv_d:
9619   case Intrinsic::x86_avx2_psllv_q:
9620   case Intrinsic::x86_avx2_psllv_d_256:
9621   case Intrinsic::x86_avx2_psllv_q_256:
9622     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9623                       Op.getOperand(1), Op.getOperand(2));
9624   case Intrinsic::x86_avx2_psrlv_d:
9625   case Intrinsic::x86_avx2_psrlv_q:
9626   case Intrinsic::x86_avx2_psrlv_d_256:
9627   case Intrinsic::x86_avx2_psrlv_q_256:
9628     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9629                       Op.getOperand(1), Op.getOperand(2));
9630   case Intrinsic::x86_avx2_psrav_d:
9631   case Intrinsic::x86_avx2_psrav_d_256:
9632     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9633                       Op.getOperand(1), Op.getOperand(2));
9634   case Intrinsic::x86_ssse3_pshuf_b_128:
9635   case Intrinsic::x86_avx2_pshuf_b:
9636     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9637                        Op.getOperand(1), Op.getOperand(2));
9638   case Intrinsic::x86_ssse3_psign_b_128:
9639   case Intrinsic::x86_ssse3_psign_w_128:
9640   case Intrinsic::x86_ssse3_psign_d_128:
9641   case Intrinsic::x86_avx2_psign_b:
9642   case Intrinsic::x86_avx2_psign_w:
9643   case Intrinsic::x86_avx2_psign_d:
9644     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9645                        Op.getOperand(1), Op.getOperand(2));
9646   case Intrinsic::x86_sse41_insertps:
9647     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9648                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9649   case Intrinsic::x86_avx_vperm2f128_ps_256:
9650   case Intrinsic::x86_avx_vperm2f128_pd_256:
9651   case Intrinsic::x86_avx_vperm2f128_si_256:
9652   case Intrinsic::x86_avx2_vperm2i128:
9653     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9654                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9655   case Intrinsic::x86_avx2_permd:
9656   case Intrinsic::x86_avx2_permps:
9657     // Operands intentionally swapped. Mask is last operand to intrinsic,
9658     // but second operand for node/intruction.
9659     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9660                        Op.getOperand(2), Op.getOperand(1));
9661
9662   // ptest and testp intrinsics. The intrinsic these come from are designed to
9663   // return an integer value, not just an instruction so lower it to the ptest
9664   // or testp pattern and a setcc for the result.
9665   case Intrinsic::x86_sse41_ptestz:
9666   case Intrinsic::x86_sse41_ptestc:
9667   case Intrinsic::x86_sse41_ptestnzc:
9668   case Intrinsic::x86_avx_ptestz_256:
9669   case Intrinsic::x86_avx_ptestc_256:
9670   case Intrinsic::x86_avx_ptestnzc_256:
9671   case Intrinsic::x86_avx_vtestz_ps:
9672   case Intrinsic::x86_avx_vtestc_ps:
9673   case Intrinsic::x86_avx_vtestnzc_ps:
9674   case Intrinsic::x86_avx_vtestz_pd:
9675   case Intrinsic::x86_avx_vtestc_pd:
9676   case Intrinsic::x86_avx_vtestnzc_pd:
9677   case Intrinsic::x86_avx_vtestz_ps_256:
9678   case Intrinsic::x86_avx_vtestc_ps_256:
9679   case Intrinsic::x86_avx_vtestnzc_ps_256:
9680   case Intrinsic::x86_avx_vtestz_pd_256:
9681   case Intrinsic::x86_avx_vtestc_pd_256:
9682   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9683     bool IsTestPacked = false;
9684     unsigned X86CC = 0;
9685     switch (IntNo) {
9686     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9687     case Intrinsic::x86_avx_vtestz_ps:
9688     case Intrinsic::x86_avx_vtestz_pd:
9689     case Intrinsic::x86_avx_vtestz_ps_256:
9690     case Intrinsic::x86_avx_vtestz_pd_256:
9691       IsTestPacked = true; // Fallthrough
9692     case Intrinsic::x86_sse41_ptestz:
9693     case Intrinsic::x86_avx_ptestz_256:
9694       // ZF = 1
9695       X86CC = X86::COND_E;
9696       break;
9697     case Intrinsic::x86_avx_vtestc_ps:
9698     case Intrinsic::x86_avx_vtestc_pd:
9699     case Intrinsic::x86_avx_vtestc_ps_256:
9700     case Intrinsic::x86_avx_vtestc_pd_256:
9701       IsTestPacked = true; // Fallthrough
9702     case Intrinsic::x86_sse41_ptestc:
9703     case Intrinsic::x86_avx_ptestc_256:
9704       // CF = 1
9705       X86CC = X86::COND_B;
9706       break;
9707     case Intrinsic::x86_avx_vtestnzc_ps:
9708     case Intrinsic::x86_avx_vtestnzc_pd:
9709     case Intrinsic::x86_avx_vtestnzc_ps_256:
9710     case Intrinsic::x86_avx_vtestnzc_pd_256:
9711       IsTestPacked = true; // Fallthrough
9712     case Intrinsic::x86_sse41_ptestnzc:
9713     case Intrinsic::x86_avx_ptestnzc_256:
9714       // ZF and CF = 0
9715       X86CC = X86::COND_A;
9716       break;
9717     }
9718
9719     SDValue LHS = Op.getOperand(1);
9720     SDValue RHS = Op.getOperand(2);
9721     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9722     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9723     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9724     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9725     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9726   }
9727
9728   // SSE/AVX shift intrinsics
9729   case Intrinsic::x86_sse2_psll_w:
9730   case Intrinsic::x86_sse2_psll_d:
9731   case Intrinsic::x86_sse2_psll_q:
9732   case Intrinsic::x86_avx2_psll_w:
9733   case Intrinsic::x86_avx2_psll_d:
9734   case Intrinsic::x86_avx2_psll_q:
9735     return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9736                        Op.getOperand(1), Op.getOperand(2));
9737   case Intrinsic::x86_sse2_psrl_w:
9738   case Intrinsic::x86_sse2_psrl_d:
9739   case Intrinsic::x86_sse2_psrl_q:
9740   case Intrinsic::x86_avx2_psrl_w:
9741   case Intrinsic::x86_avx2_psrl_d:
9742   case Intrinsic::x86_avx2_psrl_q:
9743     return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9744                        Op.getOperand(1), Op.getOperand(2));
9745   case Intrinsic::x86_sse2_psra_w:
9746   case Intrinsic::x86_sse2_psra_d:
9747   case Intrinsic::x86_avx2_psra_w:
9748   case Intrinsic::x86_avx2_psra_d:
9749     return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9750                        Op.getOperand(1), Op.getOperand(2));
9751   case Intrinsic::x86_sse2_pslli_w:
9752   case Intrinsic::x86_sse2_pslli_d:
9753   case Intrinsic::x86_sse2_pslli_q:
9754   case Intrinsic::x86_avx2_pslli_w:
9755   case Intrinsic::x86_avx2_pslli_d:
9756   case Intrinsic::x86_avx2_pslli_q:
9757     return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9758                                Op.getOperand(1), Op.getOperand(2), DAG);
9759   case Intrinsic::x86_sse2_psrli_w:
9760   case Intrinsic::x86_sse2_psrli_d:
9761   case Intrinsic::x86_sse2_psrli_q:
9762   case Intrinsic::x86_avx2_psrli_w:
9763   case Intrinsic::x86_avx2_psrli_d:
9764   case Intrinsic::x86_avx2_psrli_q:
9765     return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9766                                Op.getOperand(1), Op.getOperand(2), DAG);
9767   case Intrinsic::x86_sse2_psrai_w:
9768   case Intrinsic::x86_sse2_psrai_d:
9769   case Intrinsic::x86_avx2_psrai_w:
9770   case Intrinsic::x86_avx2_psrai_d:
9771     return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9772                                Op.getOperand(1), Op.getOperand(2), DAG);
9773   // Fix vector shift instructions where the last operand is a non-immediate
9774   // i32 value.
9775   case Intrinsic::x86_mmx_pslli_w:
9776   case Intrinsic::x86_mmx_pslli_d:
9777   case Intrinsic::x86_mmx_pslli_q:
9778   case Intrinsic::x86_mmx_psrli_w:
9779   case Intrinsic::x86_mmx_psrli_d:
9780   case Intrinsic::x86_mmx_psrli_q:
9781   case Intrinsic::x86_mmx_psrai_w:
9782   case Intrinsic::x86_mmx_psrai_d: {
9783     SDValue ShAmt = Op.getOperand(2);
9784     if (isa<ConstantSDNode>(ShAmt))
9785       return SDValue();
9786
9787     unsigned NewIntNo = 0;
9788     switch (IntNo) {
9789     case Intrinsic::x86_mmx_pslli_w:
9790       NewIntNo = Intrinsic::x86_mmx_psll_w;
9791       break;
9792     case Intrinsic::x86_mmx_pslli_d:
9793       NewIntNo = Intrinsic::x86_mmx_psll_d;
9794       break;
9795     case Intrinsic::x86_mmx_pslli_q:
9796       NewIntNo = Intrinsic::x86_mmx_psll_q;
9797       break;
9798     case Intrinsic::x86_mmx_psrli_w:
9799       NewIntNo = Intrinsic::x86_mmx_psrl_w;
9800       break;
9801     case Intrinsic::x86_mmx_psrli_d:
9802       NewIntNo = Intrinsic::x86_mmx_psrl_d;
9803       break;
9804     case Intrinsic::x86_mmx_psrli_q:
9805       NewIntNo = Intrinsic::x86_mmx_psrl_q;
9806       break;
9807     case Intrinsic::x86_mmx_psrai_w:
9808       NewIntNo = Intrinsic::x86_mmx_psra_w;
9809       break;
9810     case Intrinsic::x86_mmx_psrai_d:
9811       NewIntNo = Intrinsic::x86_mmx_psra_d;
9812       break;
9813     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9814     }
9815
9816     // The vector shift intrinsics with scalars uses 32b shift amounts but
9817     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9818     // to be zero.
9819     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9820                          DAG.getConstant(0, MVT::i32));
9821 // FIXME this must be lowered to get rid of the invalid type.
9822
9823     EVT VT = Op.getValueType();
9824     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9825     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9826                        DAG.getConstant(NewIntNo, MVT::i32),
9827                        Op.getOperand(1), ShAmt);
9828   }
9829   }
9830 }
9831
9832 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9833                                            SelectionDAG &DAG) const {
9834   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9835   MFI->setReturnAddressIsTaken(true);
9836
9837   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9838   DebugLoc dl = Op.getDebugLoc();
9839
9840   if (Depth > 0) {
9841     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9842     SDValue Offset =
9843       DAG.getConstant(TD->getPointerSize(),
9844                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9845     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9846                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9847                                    FrameAddr, Offset),
9848                        MachinePointerInfo(), false, false, false, 0);
9849   }
9850
9851   // Just load the return address.
9852   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9853   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9854                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9855 }
9856
9857 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9858   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9859   MFI->setFrameAddressIsTaken(true);
9860
9861   EVT VT = Op.getValueType();
9862   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9863   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9864   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9865   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9866   while (Depth--)
9867     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9868                             MachinePointerInfo(),
9869                             false, false, false, 0);
9870   return FrameAddr;
9871 }
9872
9873 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9874                                                      SelectionDAG &DAG) const {
9875   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9876 }
9877
9878 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9879   SDValue Chain     = Op.getOperand(0);
9880   SDValue Offset    = Op.getOperand(1);
9881   SDValue Handler   = Op.getOperand(2);
9882   DebugLoc dl       = Op.getDebugLoc();
9883
9884   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9885                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9886                                      getPointerTy());
9887   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9888
9889   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9890                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9891   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9892   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9893                        false, false, 0);
9894   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9895
9896   return DAG.getNode(X86ISD::EH_RETURN, dl,
9897                      MVT::Other,
9898                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9899 }
9900
9901 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9902                                                   SelectionDAG &DAG) const {
9903   return Op.getOperand(0);
9904 }
9905
9906 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9907                                                 SelectionDAG &DAG) const {
9908   SDValue Root = Op.getOperand(0);
9909   SDValue Trmp = Op.getOperand(1); // trampoline
9910   SDValue FPtr = Op.getOperand(2); // nested function
9911   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9912   DebugLoc dl  = Op.getDebugLoc();
9913
9914   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9915
9916   if (Subtarget->is64Bit()) {
9917     SDValue OutChains[6];
9918
9919     // Large code-model.
9920     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9921     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9922
9923     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9924     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9925
9926     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9927
9928     // Load the pointer to the nested function into R11.
9929     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9930     SDValue Addr = Trmp;
9931     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9932                                 Addr, MachinePointerInfo(TrmpAddr),
9933                                 false, false, 0);
9934
9935     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9936                        DAG.getConstant(2, MVT::i64));
9937     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9938                                 MachinePointerInfo(TrmpAddr, 2),
9939                                 false, false, 2);
9940
9941     // Load the 'nest' parameter value into R10.
9942     // R10 is specified in X86CallingConv.td
9943     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9944     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9945                        DAG.getConstant(10, MVT::i64));
9946     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9947                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9948                                 false, false, 0);
9949
9950     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9951                        DAG.getConstant(12, MVT::i64));
9952     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9953                                 MachinePointerInfo(TrmpAddr, 12),
9954                                 false, false, 2);
9955
9956     // Jump to the nested function.
9957     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9958     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9959                        DAG.getConstant(20, MVT::i64));
9960     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9961                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9962                                 false, false, 0);
9963
9964     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9965     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9966                        DAG.getConstant(22, MVT::i64));
9967     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9968                                 MachinePointerInfo(TrmpAddr, 22),
9969                                 false, false, 0);
9970
9971     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9972   } else {
9973     const Function *Func =
9974       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9975     CallingConv::ID CC = Func->getCallingConv();
9976     unsigned NestReg;
9977
9978     switch (CC) {
9979     default:
9980       llvm_unreachable("Unsupported calling convention");
9981     case CallingConv::C:
9982     case CallingConv::X86_StdCall: {
9983       // Pass 'nest' parameter in ECX.
9984       // Must be kept in sync with X86CallingConv.td
9985       NestReg = X86::ECX;
9986
9987       // Check that ECX wasn't needed by an 'inreg' parameter.
9988       FunctionType *FTy = Func->getFunctionType();
9989       const AttrListPtr &Attrs = Func->getAttributes();
9990
9991       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9992         unsigned InRegCount = 0;
9993         unsigned Idx = 1;
9994
9995         for (FunctionType::param_iterator I = FTy->param_begin(),
9996              E = FTy->param_end(); I != E; ++I, ++Idx)
9997           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9998             // FIXME: should only count parameters that are lowered to integers.
9999             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10000
10001         if (InRegCount > 2) {
10002           report_fatal_error("Nest register in use - reduce number of inreg"
10003                              " parameters!");
10004         }
10005       }
10006       break;
10007     }
10008     case CallingConv::X86_FastCall:
10009     case CallingConv::X86_ThisCall:
10010     case CallingConv::Fast:
10011       // Pass 'nest' parameter in EAX.
10012       // Must be kept in sync with X86CallingConv.td
10013       NestReg = X86::EAX;
10014       break;
10015     }
10016
10017     SDValue OutChains[4];
10018     SDValue Addr, Disp;
10019
10020     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10021                        DAG.getConstant(10, MVT::i32));
10022     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10023
10024     // This is storing the opcode for MOV32ri.
10025     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10026     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10027     OutChains[0] = DAG.getStore(Root, dl,
10028                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10029                                 Trmp, MachinePointerInfo(TrmpAddr),
10030                                 false, false, 0);
10031
10032     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10033                        DAG.getConstant(1, MVT::i32));
10034     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10035                                 MachinePointerInfo(TrmpAddr, 1),
10036                                 false, false, 1);
10037
10038     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10039     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10040                        DAG.getConstant(5, MVT::i32));
10041     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10042                                 MachinePointerInfo(TrmpAddr, 5),
10043                                 false, false, 1);
10044
10045     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10046                        DAG.getConstant(6, MVT::i32));
10047     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10048                                 MachinePointerInfo(TrmpAddr, 6),
10049                                 false, false, 1);
10050
10051     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10052   }
10053 }
10054
10055 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10056                                             SelectionDAG &DAG) const {
10057   /*
10058    The rounding mode is in bits 11:10 of FPSR, and has the following
10059    settings:
10060      00 Round to nearest
10061      01 Round to -inf
10062      10 Round to +inf
10063      11 Round to 0
10064
10065   FLT_ROUNDS, on the other hand, expects the following:
10066     -1 Undefined
10067      0 Round to 0
10068      1 Round to nearest
10069      2 Round to +inf
10070      3 Round to -inf
10071
10072   To perform the conversion, we do:
10073     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10074   */
10075
10076   MachineFunction &MF = DAG.getMachineFunction();
10077   const TargetMachine &TM = MF.getTarget();
10078   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10079   unsigned StackAlignment = TFI.getStackAlignment();
10080   EVT VT = Op.getValueType();
10081   DebugLoc DL = Op.getDebugLoc();
10082
10083   // Save FP Control Word to stack slot
10084   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10085   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10086
10087
10088   MachineMemOperand *MMO =
10089    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10090                            MachineMemOperand::MOStore, 2, 2);
10091
10092   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10093   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10094                                           DAG.getVTList(MVT::Other),
10095                                           Ops, 2, MVT::i16, MMO);
10096
10097   // Load FP Control Word from stack slot
10098   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10099                             MachinePointerInfo(), false, false, false, 0);
10100
10101   // Transform as necessary
10102   SDValue CWD1 =
10103     DAG.getNode(ISD::SRL, DL, MVT::i16,
10104                 DAG.getNode(ISD::AND, DL, MVT::i16,
10105                             CWD, DAG.getConstant(0x800, MVT::i16)),
10106                 DAG.getConstant(11, MVT::i8));
10107   SDValue CWD2 =
10108     DAG.getNode(ISD::SRL, DL, MVT::i16,
10109                 DAG.getNode(ISD::AND, DL, MVT::i16,
10110                             CWD, DAG.getConstant(0x400, MVT::i16)),
10111                 DAG.getConstant(9, MVT::i8));
10112
10113   SDValue RetVal =
10114     DAG.getNode(ISD::AND, DL, MVT::i16,
10115                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10116                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10117                             DAG.getConstant(1, MVT::i16)),
10118                 DAG.getConstant(3, MVT::i16));
10119
10120
10121   return DAG.getNode((VT.getSizeInBits() < 16 ?
10122                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10123 }
10124
10125 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10126   EVT VT = Op.getValueType();
10127   EVT OpVT = VT;
10128   unsigned NumBits = VT.getSizeInBits();
10129   DebugLoc dl = Op.getDebugLoc();
10130
10131   Op = Op.getOperand(0);
10132   if (VT == MVT::i8) {
10133     // Zero extend to i32 since there is not an i8 bsr.
10134     OpVT = MVT::i32;
10135     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10136   }
10137
10138   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10139   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10140   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10141
10142   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10143   SDValue Ops[] = {
10144     Op,
10145     DAG.getConstant(NumBits+NumBits-1, OpVT),
10146     DAG.getConstant(X86::COND_E, MVT::i8),
10147     Op.getValue(1)
10148   };
10149   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10150
10151   // Finally xor with NumBits-1.
10152   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10153
10154   if (VT == MVT::i8)
10155     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10156   return Op;
10157 }
10158
10159 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10160                                                 SelectionDAG &DAG) const {
10161   EVT VT = Op.getValueType();
10162   EVT OpVT = VT;
10163   unsigned NumBits = VT.getSizeInBits();
10164   DebugLoc dl = Op.getDebugLoc();
10165
10166   Op = Op.getOperand(0);
10167   if (VT == MVT::i8) {
10168     // Zero extend to i32 since there is not an i8 bsr.
10169     OpVT = MVT::i32;
10170     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10171   }
10172
10173   // Issue a bsr (scan bits in reverse).
10174   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10175   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10176
10177   // And xor with NumBits-1.
10178   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10179
10180   if (VT == MVT::i8)
10181     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10182   return Op;
10183 }
10184
10185 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10186   EVT VT = Op.getValueType();
10187   unsigned NumBits = VT.getSizeInBits();
10188   DebugLoc dl = Op.getDebugLoc();
10189   Op = Op.getOperand(0);
10190
10191   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10192   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10193   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10194
10195   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10196   SDValue Ops[] = {
10197     Op,
10198     DAG.getConstant(NumBits, VT),
10199     DAG.getConstant(X86::COND_E, MVT::i8),
10200     Op.getValue(1)
10201   };
10202   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10203 }
10204
10205 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10206 // ones, and then concatenate the result back.
10207 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10208   EVT VT = Op.getValueType();
10209
10210   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10211          "Unsupported value type for operation");
10212
10213   unsigned NumElems = VT.getVectorNumElements();
10214   DebugLoc dl = Op.getDebugLoc();
10215
10216   // Extract the LHS vectors
10217   SDValue LHS = Op.getOperand(0);
10218   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10219   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10220
10221   // Extract the RHS vectors
10222   SDValue RHS = Op.getOperand(1);
10223   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10224   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10225
10226   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10227   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10228
10229   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10230                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10231                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10232 }
10233
10234 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10235   assert(Op.getValueType().getSizeInBits() == 256 &&
10236          Op.getValueType().isInteger() &&
10237          "Only handle AVX 256-bit vector integer operation");
10238   return Lower256IntArith(Op, DAG);
10239 }
10240
10241 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10242   assert(Op.getValueType().getSizeInBits() == 256 &&
10243          Op.getValueType().isInteger() &&
10244          "Only handle AVX 256-bit vector integer operation");
10245   return Lower256IntArith(Op, DAG);
10246 }
10247
10248 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10249   EVT VT = Op.getValueType();
10250
10251   // Decompose 256-bit ops into smaller 128-bit ops.
10252   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10253     return Lower256IntArith(Op, DAG);
10254
10255   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10256          "Only know how to lower V2I64/V4I64 multiply");
10257
10258   DebugLoc dl = Op.getDebugLoc();
10259
10260   //  Ahi = psrlqi(a, 32);
10261   //  Bhi = psrlqi(b, 32);
10262   //
10263   //  AloBlo = pmuludq(a, b);
10264   //  AloBhi = pmuludq(a, Bhi);
10265   //  AhiBlo = pmuludq(Ahi, b);
10266
10267   //  AloBhi = psllqi(AloBhi, 32);
10268   //  AhiBlo = psllqi(AhiBlo, 32);
10269   //  return AloBlo + AloBhi + AhiBlo;
10270
10271   SDValue A = Op.getOperand(0);
10272   SDValue B = Op.getOperand(1);
10273
10274   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10275
10276   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10277   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10278
10279   // Bit cast to 32-bit vectors for MULUDQ
10280   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10281   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10282   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10283   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10284   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10285
10286   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10287   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10288   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10289
10290   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10291   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10292
10293   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10294   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10295 }
10296
10297 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10298
10299   EVT VT = Op.getValueType();
10300   DebugLoc dl = Op.getDebugLoc();
10301   SDValue R = Op.getOperand(0);
10302   SDValue Amt = Op.getOperand(1);
10303   LLVMContext *Context = DAG.getContext();
10304
10305   if (!Subtarget->hasSSE2())
10306     return SDValue();
10307
10308   // Optimize shl/srl/sra with constant shift amount.
10309   if (isSplatVector(Amt.getNode())) {
10310     SDValue SclrAmt = Amt->getOperand(0);
10311     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10312       uint64_t ShiftAmt = C->getZExtValue();
10313
10314       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10315           (Subtarget->hasAVX2() &&
10316            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10317         if (Op.getOpcode() == ISD::SHL)
10318           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10319                              DAG.getConstant(ShiftAmt, MVT::i32));
10320         if (Op.getOpcode() == ISD::SRL)
10321           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10322                              DAG.getConstant(ShiftAmt, MVT::i32));
10323         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10324           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10325                              DAG.getConstant(ShiftAmt, MVT::i32));
10326       }
10327
10328       if (VT == MVT::v16i8) {
10329         if (Op.getOpcode() == ISD::SHL) {
10330           // Make a large shift.
10331           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10332                                     DAG.getConstant(ShiftAmt, MVT::i32));
10333           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10334           // Zero out the rightmost bits.
10335           SmallVector<SDValue, 16> V(16,
10336                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10337                                                      MVT::i8));
10338           return DAG.getNode(ISD::AND, dl, VT, SHL,
10339                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10340         }
10341         if (Op.getOpcode() == ISD::SRL) {
10342           // Make a large shift.
10343           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10344                                     DAG.getConstant(ShiftAmt, MVT::i32));
10345           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10346           // Zero out the leftmost bits.
10347           SmallVector<SDValue, 16> V(16,
10348                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10349                                                      MVT::i8));
10350           return DAG.getNode(ISD::AND, dl, VT, SRL,
10351                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10352         }
10353         if (Op.getOpcode() == ISD::SRA) {
10354           if (ShiftAmt == 7) {
10355             // R s>> 7  ===  R s< 0
10356             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10357             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10358           }
10359
10360           // R s>> a === ((R u>> a) ^ m) - m
10361           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10362           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10363                                                          MVT::i8));
10364           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10365           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10366           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10367           return Res;
10368         }
10369         llvm_unreachable("Unknown shift opcode.");
10370       }
10371
10372       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10373         if (Op.getOpcode() == ISD::SHL) {
10374           // Make a large shift.
10375           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10376                                     DAG.getConstant(ShiftAmt, MVT::i32));
10377           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10378           // Zero out the rightmost bits.
10379           SmallVector<SDValue, 32> V(32,
10380                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10381                                                      MVT::i8));
10382           return DAG.getNode(ISD::AND, dl, VT, SHL,
10383                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10384         }
10385         if (Op.getOpcode() == ISD::SRL) {
10386           // Make a large shift.
10387           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10388                                     DAG.getConstant(ShiftAmt, MVT::i32));
10389           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10390           // Zero out the leftmost bits.
10391           SmallVector<SDValue, 32> V(32,
10392                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10393                                                      MVT::i8));
10394           return DAG.getNode(ISD::AND, dl, VT, SRL,
10395                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10396         }
10397         if (Op.getOpcode() == ISD::SRA) {
10398           if (ShiftAmt == 7) {
10399             // R s>> 7  ===  R s< 0
10400             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10401             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10402           }
10403
10404           // R s>> a === ((R u>> a) ^ m) - m
10405           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10406           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10407                                                          MVT::i8));
10408           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10409           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10410           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10411           return Res;
10412         }
10413         llvm_unreachable("Unknown shift opcode.");
10414       }
10415     }
10416   }
10417
10418   // Lower SHL with variable shift amount.
10419   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10420     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10421                      DAG.getConstant(23, MVT::i32));
10422
10423     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10424     Constant *C = ConstantDataVector::get(*Context, CV);
10425     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10426     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10427                                  MachinePointerInfo::getConstantPool(),
10428                                  false, false, false, 16);
10429
10430     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10431     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10432     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10433     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10434   }
10435   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10436     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10437
10438     // a = a << 5;
10439     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10440                      DAG.getConstant(5, MVT::i32));
10441     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10442
10443     // Turn 'a' into a mask suitable for VSELECT
10444     SDValue VSelM = DAG.getConstant(0x80, VT);
10445     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10446     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10447
10448     SDValue CM1 = DAG.getConstant(0x0f, VT);
10449     SDValue CM2 = DAG.getConstant(0x3f, VT);
10450
10451     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10452     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10453     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10454                             DAG.getConstant(4, MVT::i32), DAG);
10455     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10456     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10457
10458     // a += a
10459     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10460     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10461     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10462
10463     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10464     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10465     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10466                             DAG.getConstant(2, MVT::i32), DAG);
10467     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10468     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10469
10470     // a += a
10471     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10472     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10473     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10474
10475     // return VSELECT(r, r+r, a);
10476     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10477                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10478     return R;
10479   }
10480
10481   // Decompose 256-bit shifts into smaller 128-bit shifts.
10482   if (VT.getSizeInBits() == 256) {
10483     unsigned NumElems = VT.getVectorNumElements();
10484     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10485     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10486
10487     // Extract the two vectors
10488     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10489     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10490
10491     // Recreate the shift amount vectors
10492     SDValue Amt1, Amt2;
10493     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10494       // Constant shift amount
10495       SmallVector<SDValue, 4> Amt1Csts;
10496       SmallVector<SDValue, 4> Amt2Csts;
10497       for (unsigned i = 0; i != NumElems/2; ++i)
10498         Amt1Csts.push_back(Amt->getOperand(i));
10499       for (unsigned i = NumElems/2; i != NumElems; ++i)
10500         Amt2Csts.push_back(Amt->getOperand(i));
10501
10502       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10503                                  &Amt1Csts[0], NumElems/2);
10504       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10505                                  &Amt2Csts[0], NumElems/2);
10506     } else {
10507       // Variable shift amount
10508       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10509       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10510     }
10511
10512     // Issue new vector shifts for the smaller types
10513     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10514     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10515
10516     // Concatenate the result back
10517     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10518   }
10519
10520   return SDValue();
10521 }
10522
10523 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10524   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10525   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10526   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10527   // has only one use.
10528   SDNode *N = Op.getNode();
10529   SDValue LHS = N->getOperand(0);
10530   SDValue RHS = N->getOperand(1);
10531   unsigned BaseOp = 0;
10532   unsigned Cond = 0;
10533   DebugLoc DL = Op.getDebugLoc();
10534   switch (Op.getOpcode()) {
10535   default: llvm_unreachable("Unknown ovf instruction!");
10536   case ISD::SADDO:
10537     // A subtract of one will be selected as a INC. Note that INC doesn't
10538     // set CF, so we can't do this for UADDO.
10539     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10540       if (C->isOne()) {
10541         BaseOp = X86ISD::INC;
10542         Cond = X86::COND_O;
10543         break;
10544       }
10545     BaseOp = X86ISD::ADD;
10546     Cond = X86::COND_O;
10547     break;
10548   case ISD::UADDO:
10549     BaseOp = X86ISD::ADD;
10550     Cond = X86::COND_B;
10551     break;
10552   case ISD::SSUBO:
10553     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10554     // set CF, so we can't do this for USUBO.
10555     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10556       if (C->isOne()) {
10557         BaseOp = X86ISD::DEC;
10558         Cond = X86::COND_O;
10559         break;
10560       }
10561     BaseOp = X86ISD::SUB;
10562     Cond = X86::COND_O;
10563     break;
10564   case ISD::USUBO:
10565     BaseOp = X86ISD::SUB;
10566     Cond = X86::COND_B;
10567     break;
10568   case ISD::SMULO:
10569     BaseOp = X86ISD::SMUL;
10570     Cond = X86::COND_O;
10571     break;
10572   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10573     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10574                                  MVT::i32);
10575     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10576
10577     SDValue SetCC =
10578       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10579                   DAG.getConstant(X86::COND_O, MVT::i32),
10580                   SDValue(Sum.getNode(), 2));
10581
10582     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10583   }
10584   }
10585
10586   // Also sets EFLAGS.
10587   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10588   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10589
10590   SDValue SetCC =
10591     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10592                 DAG.getConstant(Cond, MVT::i32),
10593                 SDValue(Sum.getNode(), 1));
10594
10595   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10596 }
10597
10598 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10599                                                   SelectionDAG &DAG) const {
10600   DebugLoc dl = Op.getDebugLoc();
10601   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10602   EVT VT = Op.getValueType();
10603
10604   if (!Subtarget->hasSSE2() || !VT.isVector())
10605     return SDValue();
10606
10607   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10608                       ExtraVT.getScalarType().getSizeInBits();
10609   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10610
10611   switch (VT.getSimpleVT().SimpleTy) {
10612     default: return SDValue();
10613     case MVT::v8i32:
10614     case MVT::v16i16:
10615       if (!Subtarget->hasAVX())
10616         return SDValue();
10617       if (!Subtarget->hasAVX2()) {
10618         // needs to be split
10619         unsigned NumElems = VT.getVectorNumElements();
10620
10621         // Extract the LHS vectors
10622         SDValue LHS = Op.getOperand(0);
10623         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10624         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10625
10626         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10627         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10628
10629         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10630         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10631         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10632                                    ExtraNumElems/2);
10633         SDValue Extra = DAG.getValueType(ExtraVT);
10634
10635         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10636         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10637
10638         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10639       }
10640       // fall through
10641     case MVT::v4i32:
10642     case MVT::v8i16: {
10643       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10644                                          Op.getOperand(0), ShAmt, DAG);
10645       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10646     }
10647   }
10648 }
10649
10650
10651 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10652   DebugLoc dl = Op.getDebugLoc();
10653
10654   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10655   // There isn't any reason to disable it if the target processor supports it.
10656   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10657     SDValue Chain = Op.getOperand(0);
10658     SDValue Zero = DAG.getConstant(0, MVT::i32);
10659     SDValue Ops[] = {
10660       DAG.getRegister(X86::ESP, MVT::i32), // Base
10661       DAG.getTargetConstant(1, MVT::i8),   // Scale
10662       DAG.getRegister(0, MVT::i32),        // Index
10663       DAG.getTargetConstant(0, MVT::i32),  // Disp
10664       DAG.getRegister(0, MVT::i32),        // Segment.
10665       Zero,
10666       Chain
10667     };
10668     SDNode *Res =
10669       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10670                           array_lengthof(Ops));
10671     return SDValue(Res, 0);
10672   }
10673
10674   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10675   if (!isDev)
10676     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10677
10678   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10679   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10680   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10681   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10682
10683   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10684   if (!Op1 && !Op2 && !Op3 && Op4)
10685     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10686
10687   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10688   if (Op1 && !Op2 && !Op3 && !Op4)
10689     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10690
10691   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10692   //           (MFENCE)>;
10693   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10694 }
10695
10696 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10697                                              SelectionDAG &DAG) const {
10698   DebugLoc dl = Op.getDebugLoc();
10699   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10700     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10701   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10702     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10703
10704   // The only fence that needs an instruction is a sequentially-consistent
10705   // cross-thread fence.
10706   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10707     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10708     // no-sse2). There isn't any reason to disable it if the target processor
10709     // supports it.
10710     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10711       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10712
10713     SDValue Chain = Op.getOperand(0);
10714     SDValue Zero = DAG.getConstant(0, MVT::i32);
10715     SDValue Ops[] = {
10716       DAG.getRegister(X86::ESP, MVT::i32), // Base
10717       DAG.getTargetConstant(1, MVT::i8),   // Scale
10718       DAG.getRegister(0, MVT::i32),        // Index
10719       DAG.getTargetConstant(0, MVT::i32),  // Disp
10720       DAG.getRegister(0, MVT::i32),        // Segment.
10721       Zero,
10722       Chain
10723     };
10724     SDNode *Res =
10725       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10726                          array_lengthof(Ops));
10727     return SDValue(Res, 0);
10728   }
10729
10730   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10731   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10732 }
10733
10734
10735 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10736   EVT T = Op.getValueType();
10737   DebugLoc DL = Op.getDebugLoc();
10738   unsigned Reg = 0;
10739   unsigned size = 0;
10740   switch(T.getSimpleVT().SimpleTy) {
10741   default: llvm_unreachable("Invalid value type!");
10742   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10743   case MVT::i16: Reg = X86::AX;  size = 2; break;
10744   case MVT::i32: Reg = X86::EAX; size = 4; break;
10745   case MVT::i64:
10746     assert(Subtarget->is64Bit() && "Node not type legal!");
10747     Reg = X86::RAX; size = 8;
10748     break;
10749   }
10750   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10751                                     Op.getOperand(2), SDValue());
10752   SDValue Ops[] = { cpIn.getValue(0),
10753                     Op.getOperand(1),
10754                     Op.getOperand(3),
10755                     DAG.getTargetConstant(size, MVT::i8),
10756                     cpIn.getValue(1) };
10757   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10758   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10759   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10760                                            Ops, 5, T, MMO);
10761   SDValue cpOut =
10762     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10763   return cpOut;
10764 }
10765
10766 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10767                                                  SelectionDAG &DAG) const {
10768   assert(Subtarget->is64Bit() && "Result not type legalized?");
10769   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10770   SDValue TheChain = Op.getOperand(0);
10771   DebugLoc dl = Op.getDebugLoc();
10772   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10773   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10774   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10775                                    rax.getValue(2));
10776   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10777                             DAG.getConstant(32, MVT::i8));
10778   SDValue Ops[] = {
10779     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10780     rdx.getValue(1)
10781   };
10782   return DAG.getMergeValues(Ops, 2, dl);
10783 }
10784
10785 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10786                                             SelectionDAG &DAG) const {
10787   EVT SrcVT = Op.getOperand(0).getValueType();
10788   EVT DstVT = Op.getValueType();
10789   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10790          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10791   assert((DstVT == MVT::i64 ||
10792           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10793          "Unexpected custom BITCAST");
10794   // i64 <=> MMX conversions are Legal.
10795   if (SrcVT==MVT::i64 && DstVT.isVector())
10796     return Op;
10797   if (DstVT==MVT::i64 && SrcVT.isVector())
10798     return Op;
10799   // MMX <=> MMX conversions are Legal.
10800   if (SrcVT.isVector() && DstVT.isVector())
10801     return Op;
10802   // All other conversions need to be expanded.
10803   return SDValue();
10804 }
10805
10806 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10807   SDNode *Node = Op.getNode();
10808   DebugLoc dl = Node->getDebugLoc();
10809   EVT T = Node->getValueType(0);
10810   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10811                               DAG.getConstant(0, T), Node->getOperand(2));
10812   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10813                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10814                        Node->getOperand(0),
10815                        Node->getOperand(1), negOp,
10816                        cast<AtomicSDNode>(Node)->getSrcValue(),
10817                        cast<AtomicSDNode>(Node)->getAlignment(),
10818                        cast<AtomicSDNode>(Node)->getOrdering(),
10819                        cast<AtomicSDNode>(Node)->getSynchScope());
10820 }
10821
10822 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10823   SDNode *Node = Op.getNode();
10824   DebugLoc dl = Node->getDebugLoc();
10825   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10826
10827   // Convert seq_cst store -> xchg
10828   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10829   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10830   //        (The only way to get a 16-byte store is cmpxchg16b)
10831   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10832   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10833       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10834     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10835                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10836                                  Node->getOperand(0),
10837                                  Node->getOperand(1), Node->getOperand(2),
10838                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10839                                  cast<AtomicSDNode>(Node)->getOrdering(),
10840                                  cast<AtomicSDNode>(Node)->getSynchScope());
10841     return Swap.getValue(1);
10842   }
10843   // Other atomic stores have a simple pattern.
10844   return Op;
10845 }
10846
10847 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10848   EVT VT = Op.getNode()->getValueType(0);
10849
10850   // Let legalize expand this if it isn't a legal type yet.
10851   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10852     return SDValue();
10853
10854   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10855
10856   unsigned Opc;
10857   bool ExtraOp = false;
10858   switch (Op.getOpcode()) {
10859   default: llvm_unreachable("Invalid code");
10860   case ISD::ADDC: Opc = X86ISD::ADD; break;
10861   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10862   case ISD::SUBC: Opc = X86ISD::SUB; break;
10863   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10864   }
10865
10866   if (!ExtraOp)
10867     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10868                        Op.getOperand(1));
10869   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10870                      Op.getOperand(1), Op.getOperand(2));
10871 }
10872
10873 /// LowerOperation - Provide custom lowering hooks for some operations.
10874 ///
10875 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10876   switch (Op.getOpcode()) {
10877   default: llvm_unreachable("Should not custom lower this!");
10878   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10879   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10880   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10881   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10882   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10883   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10884   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10885   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10886   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10887   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10888   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10889   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10890   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10891   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10892   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10893   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10894   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10895   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10896   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10897   case ISD::SHL_PARTS:
10898   case ISD::SRA_PARTS:
10899   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10900   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10901   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10902   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10903   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10904   case ISD::FABS:               return LowerFABS(Op, DAG);
10905   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10906   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10907   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10908   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10909   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10910   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10911   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10912   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10913   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10914   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10915   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10916   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10917   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10918   case ISD::FRAME_TO_ARGS_OFFSET:
10919                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10920   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10921   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10922   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10923   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10924   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10925   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10926   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
10927   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10928   case ISD::MUL:                return LowerMUL(Op, DAG);
10929   case ISD::SRA:
10930   case ISD::SRL:
10931   case ISD::SHL:                return LowerShift(Op, DAG);
10932   case ISD::SADDO:
10933   case ISD::UADDO:
10934   case ISD::SSUBO:
10935   case ISD::USUBO:
10936   case ISD::SMULO:
10937   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10938   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10939   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10940   case ISD::ADDC:
10941   case ISD::ADDE:
10942   case ISD::SUBC:
10943   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10944   case ISD::ADD:                return LowerADD(Op, DAG);
10945   case ISD::SUB:                return LowerSUB(Op, DAG);
10946   }
10947 }
10948
10949 static void ReplaceATOMIC_LOAD(SDNode *Node,
10950                                   SmallVectorImpl<SDValue> &Results,
10951                                   SelectionDAG &DAG) {
10952   DebugLoc dl = Node->getDebugLoc();
10953   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10954
10955   // Convert wide load -> cmpxchg8b/cmpxchg16b
10956   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10957   //        (The only way to get a 16-byte load is cmpxchg16b)
10958   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10959   SDValue Zero = DAG.getConstant(0, VT);
10960   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10961                                Node->getOperand(0),
10962                                Node->getOperand(1), Zero, Zero,
10963                                cast<AtomicSDNode>(Node)->getMemOperand(),
10964                                cast<AtomicSDNode>(Node)->getOrdering(),
10965                                cast<AtomicSDNode>(Node)->getSynchScope());
10966   Results.push_back(Swap.getValue(0));
10967   Results.push_back(Swap.getValue(1));
10968 }
10969
10970 void X86TargetLowering::
10971 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10972                         SelectionDAG &DAG, unsigned NewOp) const {
10973   DebugLoc dl = Node->getDebugLoc();
10974   assert (Node->getValueType(0) == MVT::i64 &&
10975           "Only know how to expand i64 atomics");
10976
10977   SDValue Chain = Node->getOperand(0);
10978   SDValue In1 = Node->getOperand(1);
10979   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10980                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10981   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10982                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10983   SDValue Ops[] = { Chain, In1, In2L, In2H };
10984   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10985   SDValue Result =
10986     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10987                             cast<MemSDNode>(Node)->getMemOperand());
10988   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10989   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10990   Results.push_back(Result.getValue(2));
10991 }
10992
10993 /// ReplaceNodeResults - Replace a node with an illegal result type
10994 /// with a new node built out of custom code.
10995 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10996                                            SmallVectorImpl<SDValue>&Results,
10997                                            SelectionDAG &DAG) const {
10998   DebugLoc dl = N->getDebugLoc();
10999   switch (N->getOpcode()) {
11000   default:
11001     llvm_unreachable("Do not know how to custom type legalize this operation!");
11002   case ISD::SIGN_EXTEND_INREG:
11003   case ISD::ADDC:
11004   case ISD::ADDE:
11005   case ISD::SUBC:
11006   case ISD::SUBE:
11007     // We don't want to expand or promote these.
11008     return;
11009   case ISD::FP_TO_SINT:
11010   case ISD::FP_TO_UINT: {
11011     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11012
11013     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11014       return;
11015
11016     std::pair<SDValue,SDValue> Vals =
11017         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11018     SDValue FIST = Vals.first, StackSlot = Vals.second;
11019     if (FIST.getNode() != 0) {
11020       EVT VT = N->getValueType(0);
11021       // Return a load from the stack slot.
11022       if (StackSlot.getNode() != 0)
11023         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11024                                       MachinePointerInfo(),
11025                                       false, false, false, 0));
11026       else
11027         Results.push_back(FIST);
11028     }
11029     return;
11030   }
11031   case ISD::READCYCLECOUNTER: {
11032     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11033     SDValue TheChain = N->getOperand(0);
11034     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11035     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11036                                      rd.getValue(1));
11037     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11038                                      eax.getValue(2));
11039     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11040     SDValue Ops[] = { eax, edx };
11041     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11042     Results.push_back(edx.getValue(1));
11043     return;
11044   }
11045   case ISD::ATOMIC_CMP_SWAP: {
11046     EVT T = N->getValueType(0);
11047     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11048     bool Regs64bit = T == MVT::i128;
11049     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11050     SDValue cpInL, cpInH;
11051     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11052                         DAG.getConstant(0, HalfT));
11053     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11054                         DAG.getConstant(1, HalfT));
11055     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11056                              Regs64bit ? X86::RAX : X86::EAX,
11057                              cpInL, SDValue());
11058     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11059                              Regs64bit ? X86::RDX : X86::EDX,
11060                              cpInH, cpInL.getValue(1));
11061     SDValue swapInL, swapInH;
11062     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11063                           DAG.getConstant(0, HalfT));
11064     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11065                           DAG.getConstant(1, HalfT));
11066     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11067                                Regs64bit ? X86::RBX : X86::EBX,
11068                                swapInL, cpInH.getValue(1));
11069     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11070                                Regs64bit ? X86::RCX : X86::ECX, 
11071                                swapInH, swapInL.getValue(1));
11072     SDValue Ops[] = { swapInH.getValue(0),
11073                       N->getOperand(1),
11074                       swapInH.getValue(1) };
11075     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11076     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11077     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11078                                   X86ISD::LCMPXCHG8_DAG;
11079     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11080                                              Ops, 3, T, MMO);
11081     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11082                                         Regs64bit ? X86::RAX : X86::EAX,
11083                                         HalfT, Result.getValue(1));
11084     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11085                                         Regs64bit ? X86::RDX : X86::EDX,
11086                                         HalfT, cpOutL.getValue(2));
11087     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11088     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11089     Results.push_back(cpOutH.getValue(1));
11090     return;
11091   }
11092   case ISD::ATOMIC_LOAD_ADD:
11093     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11094     return;
11095   case ISD::ATOMIC_LOAD_AND:
11096     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11097     return;
11098   case ISD::ATOMIC_LOAD_NAND:
11099     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11100     return;
11101   case ISD::ATOMIC_LOAD_OR:
11102     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11103     return;
11104   case ISD::ATOMIC_LOAD_SUB:
11105     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11106     return;
11107   case ISD::ATOMIC_LOAD_XOR:
11108     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11109     return;
11110   case ISD::ATOMIC_SWAP:
11111     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11112     return;
11113   case ISD::ATOMIC_LOAD:
11114     ReplaceATOMIC_LOAD(N, Results, DAG);
11115   }
11116 }
11117
11118 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11119   switch (Opcode) {
11120   default: return NULL;
11121   case X86ISD::BSF:                return "X86ISD::BSF";
11122   case X86ISD::BSR:                return "X86ISD::BSR";
11123   case X86ISD::SHLD:               return "X86ISD::SHLD";
11124   case X86ISD::SHRD:               return "X86ISD::SHRD";
11125   case X86ISD::FAND:               return "X86ISD::FAND";
11126   case X86ISD::FOR:                return "X86ISD::FOR";
11127   case X86ISD::FXOR:               return "X86ISD::FXOR";
11128   case X86ISD::FSRL:               return "X86ISD::FSRL";
11129   case X86ISD::FILD:               return "X86ISD::FILD";
11130   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11131   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11132   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11133   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11134   case X86ISD::FLD:                return "X86ISD::FLD";
11135   case X86ISD::FST:                return "X86ISD::FST";
11136   case X86ISD::CALL:               return "X86ISD::CALL";
11137   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11138   case X86ISD::BT:                 return "X86ISD::BT";
11139   case X86ISD::CMP:                return "X86ISD::CMP";
11140   case X86ISD::COMI:               return "X86ISD::COMI";
11141   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11142   case X86ISD::SETCC:              return "X86ISD::SETCC";
11143   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11144   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11145   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11146   case X86ISD::CMOV:               return "X86ISD::CMOV";
11147   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11148   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11149   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11150   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11151   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11152   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11153   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11154   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11155   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11156   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11157   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11158   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11159   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11160   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11161   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11162   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11163   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11164   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11165   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11166   case X86ISD::HADD:               return "X86ISD::HADD";
11167   case X86ISD::HSUB:               return "X86ISD::HSUB";
11168   case X86ISD::FHADD:              return "X86ISD::FHADD";
11169   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11170   case X86ISD::FMAX:               return "X86ISD::FMAX";
11171   case X86ISD::FMIN:               return "X86ISD::FMIN";
11172   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11173   case X86ISD::FRCP:               return "X86ISD::FRCP";
11174   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11175   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11176   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11177   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11178   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11179   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11180   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11181   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11182   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11183   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11184   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11185   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11186   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11187   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11188   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11189   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11190   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11191   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11192   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11193   case X86ISD::VSHL:               return "X86ISD::VSHL";
11194   case X86ISD::VSRL:               return "X86ISD::VSRL";
11195   case X86ISD::VSRA:               return "X86ISD::VSRA";
11196   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11197   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11198   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11199   case X86ISD::CMPP:               return "X86ISD::CMPP";
11200   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11201   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11202   case X86ISD::ADD:                return "X86ISD::ADD";
11203   case X86ISD::SUB:                return "X86ISD::SUB";
11204   case X86ISD::ADC:                return "X86ISD::ADC";
11205   case X86ISD::SBB:                return "X86ISD::SBB";
11206   case X86ISD::SMUL:               return "X86ISD::SMUL";
11207   case X86ISD::UMUL:               return "X86ISD::UMUL";
11208   case X86ISD::INC:                return "X86ISD::INC";
11209   case X86ISD::DEC:                return "X86ISD::DEC";
11210   case X86ISD::OR:                 return "X86ISD::OR";
11211   case X86ISD::XOR:                return "X86ISD::XOR";
11212   case X86ISD::AND:                return "X86ISD::AND";
11213   case X86ISD::ANDN:               return "X86ISD::ANDN";
11214   case X86ISD::BLSI:               return "X86ISD::BLSI";
11215   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11216   case X86ISD::BLSR:               return "X86ISD::BLSR";
11217   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11218   case X86ISD::PTEST:              return "X86ISD::PTEST";
11219   case X86ISD::TESTP:              return "X86ISD::TESTP";
11220   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11221   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11222   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11223   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11224   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11225   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11226   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11227   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11228   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11229   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11230   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11231   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11232   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11233   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11234   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11235   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11236   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11237   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11238   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11239   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11240   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11241   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11242   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11243   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11244   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11245   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11246   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11247   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11248   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11249   case X86ISD::SAHF:               return "X86ISD::SAHF";
11250   }
11251 }
11252
11253 // isLegalAddressingMode - Return true if the addressing mode represented
11254 // by AM is legal for this target, for a load/store of the specified type.
11255 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11256                                               Type *Ty) const {
11257   // X86 supports extremely general addressing modes.
11258   CodeModel::Model M = getTargetMachine().getCodeModel();
11259   Reloc::Model R = getTargetMachine().getRelocationModel();
11260
11261   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11262   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11263     return false;
11264
11265   if (AM.BaseGV) {
11266     unsigned GVFlags =
11267       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11268
11269     // If a reference to this global requires an extra load, we can't fold it.
11270     if (isGlobalStubReference(GVFlags))
11271       return false;
11272
11273     // If BaseGV requires a register for the PIC base, we cannot also have a
11274     // BaseReg specified.
11275     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11276       return false;
11277
11278     // If lower 4G is not available, then we must use rip-relative addressing.
11279     if ((M != CodeModel::Small || R != Reloc::Static) &&
11280         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11281       return false;
11282   }
11283
11284   switch (AM.Scale) {
11285   case 0:
11286   case 1:
11287   case 2:
11288   case 4:
11289   case 8:
11290     // These scales always work.
11291     break;
11292   case 3:
11293   case 5:
11294   case 9:
11295     // These scales are formed with basereg+scalereg.  Only accept if there is
11296     // no basereg yet.
11297     if (AM.HasBaseReg)
11298       return false;
11299     break;
11300   default:  // Other stuff never works.
11301     return false;
11302   }
11303
11304   return true;
11305 }
11306
11307
11308 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11309   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11310     return false;
11311   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11312   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11313   if (NumBits1 <= NumBits2)
11314     return false;
11315   return true;
11316 }
11317
11318 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11319   if (!VT1.isInteger() || !VT2.isInteger())
11320     return false;
11321   unsigned NumBits1 = VT1.getSizeInBits();
11322   unsigned NumBits2 = VT2.getSizeInBits();
11323   if (NumBits1 <= NumBits2)
11324     return false;
11325   return true;
11326 }
11327
11328 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11329   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11330   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11331 }
11332
11333 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11334   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11335   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11336 }
11337
11338 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11339   // i16 instructions are longer (0x66 prefix) and potentially slower.
11340   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11341 }
11342
11343 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11344 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11345 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11346 /// are assumed to be legal.
11347 bool
11348 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11349                                       EVT VT) const {
11350   // Very little shuffling can be done for 64-bit vectors right now.
11351   if (VT.getSizeInBits() == 64)
11352     return false;
11353
11354   // FIXME: pshufb, blends, shifts.
11355   return (VT.getVectorNumElements() == 2 ||
11356           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11357           isMOVLMask(M, VT) ||
11358           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11359           isPSHUFDMask(M, VT) ||
11360           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11361           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11362           isPALIGNRMask(M, VT, Subtarget) ||
11363           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11364           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11365           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11366           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11367 }
11368
11369 bool
11370 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11371                                           EVT VT) const {
11372   unsigned NumElts = VT.getVectorNumElements();
11373   // FIXME: This collection of masks seems suspect.
11374   if (NumElts == 2)
11375     return true;
11376   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11377     return (isMOVLMask(Mask, VT)  ||
11378             isCommutedMOVLMask(Mask, VT, true) ||
11379             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11380             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11381   }
11382   return false;
11383 }
11384
11385 //===----------------------------------------------------------------------===//
11386 //                           X86 Scheduler Hooks
11387 //===----------------------------------------------------------------------===//
11388
11389 // private utility function
11390 MachineBasicBlock *
11391 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11392                                                        MachineBasicBlock *MBB,
11393                                                        unsigned regOpc,
11394                                                        unsigned immOpc,
11395                                                        unsigned LoadOpc,
11396                                                        unsigned CXchgOpc,
11397                                                        unsigned notOpc,
11398                                                        unsigned EAXreg,
11399                                                  const TargetRegisterClass *RC,
11400                                                        bool Invert) const {
11401   // For the atomic bitwise operator, we generate
11402   //   thisMBB:
11403   //   newMBB:
11404   //     ld  t1 = [bitinstr.addr]
11405   //     op  t2 = t1, [bitinstr.val]
11406   //     not t3 = t2  (if Invert)
11407   //     mov EAX = t1
11408   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11409   //     bz  newMBB
11410   //     fallthrough -->nextMBB
11411   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11412   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11413   MachineFunction::iterator MBBIter = MBB;
11414   ++MBBIter;
11415
11416   /// First build the CFG
11417   MachineFunction *F = MBB->getParent();
11418   MachineBasicBlock *thisMBB = MBB;
11419   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11420   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11421   F->insert(MBBIter, newMBB);
11422   F->insert(MBBIter, nextMBB);
11423
11424   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11425   nextMBB->splice(nextMBB->begin(), thisMBB,
11426                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11427                   thisMBB->end());
11428   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11429
11430   // Update thisMBB to fall through to newMBB
11431   thisMBB->addSuccessor(newMBB);
11432
11433   // newMBB jumps to itself and fall through to nextMBB
11434   newMBB->addSuccessor(nextMBB);
11435   newMBB->addSuccessor(newMBB);
11436
11437   // Insert instructions into newMBB based on incoming instruction
11438   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11439          "unexpected number of operands");
11440   DebugLoc dl = bInstr->getDebugLoc();
11441   MachineOperand& destOper = bInstr->getOperand(0);
11442   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11443   int numArgs = bInstr->getNumOperands() - 1;
11444   for (int i=0; i < numArgs; ++i)
11445     argOpers[i] = &bInstr->getOperand(i+1);
11446
11447   // x86 address has 4 operands: base, index, scale, and displacement
11448   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11449   int valArgIndx = lastAddrIndx + 1;
11450
11451   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11452   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11453   for (int i=0; i <= lastAddrIndx; ++i)
11454     (*MIB).addOperand(*argOpers[i]);
11455
11456   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11457   assert((argOpers[valArgIndx]->isReg() ||
11458           argOpers[valArgIndx]->isImm()) &&
11459          "invalid operand");
11460   if (argOpers[valArgIndx]->isReg())
11461     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11462   else
11463     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11464   MIB.addReg(t1);
11465   (*MIB).addOperand(*argOpers[valArgIndx]);
11466
11467   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11468   if (Invert) {
11469     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11470   }
11471   else
11472     t3 = t2;
11473
11474   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11475   MIB.addReg(t1);
11476
11477   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11478   for (int i=0; i <= lastAddrIndx; ++i)
11479     (*MIB).addOperand(*argOpers[i]);
11480   MIB.addReg(t3);
11481   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11482   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11483                     bInstr->memoperands_end());
11484
11485   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11486   MIB.addReg(EAXreg);
11487
11488   // insert branch
11489   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11490
11491   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11492   return nextMBB;
11493 }
11494
11495 // private utility function:  64 bit atomics on 32 bit host.
11496 MachineBasicBlock *
11497 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11498                                                        MachineBasicBlock *MBB,
11499                                                        unsigned regOpcL,
11500                                                        unsigned regOpcH,
11501                                                        unsigned immOpcL,
11502                                                        unsigned immOpcH,
11503                                                        bool Invert) const {
11504   // For the atomic bitwise operator, we generate
11505   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11506   //     ld t1,t2 = [bitinstr.addr]
11507   //   newMBB:
11508   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11509   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11510   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11511   //     neg t7, t8 < t5, t6  (if Invert)
11512   //     mov ECX, EBX <- t5, t6
11513   //     mov EAX, EDX <- t1, t2
11514   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11515   //     mov t3, t4 <- EAX, EDX
11516   //     bz  newMBB
11517   //     result in out1, out2
11518   //     fallthrough -->nextMBB
11519
11520   const TargetRegisterClass *RC = &X86::GR32RegClass;
11521   const unsigned LoadOpc = X86::MOV32rm;
11522   const unsigned NotOpc = X86::NOT32r;
11523   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11524   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11525   MachineFunction::iterator MBBIter = MBB;
11526   ++MBBIter;
11527
11528   /// First build the CFG
11529   MachineFunction *F = MBB->getParent();
11530   MachineBasicBlock *thisMBB = MBB;
11531   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11532   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11533   F->insert(MBBIter, newMBB);
11534   F->insert(MBBIter, nextMBB);
11535
11536   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11537   nextMBB->splice(nextMBB->begin(), thisMBB,
11538                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11539                   thisMBB->end());
11540   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11541
11542   // Update thisMBB to fall through to newMBB
11543   thisMBB->addSuccessor(newMBB);
11544
11545   // newMBB jumps to itself and fall through to nextMBB
11546   newMBB->addSuccessor(nextMBB);
11547   newMBB->addSuccessor(newMBB);
11548
11549   DebugLoc dl = bInstr->getDebugLoc();
11550   // Insert instructions into newMBB based on incoming instruction
11551   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11552   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11553          "unexpected number of operands");
11554   MachineOperand& dest1Oper = bInstr->getOperand(0);
11555   MachineOperand& dest2Oper = bInstr->getOperand(1);
11556   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11557   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11558     argOpers[i] = &bInstr->getOperand(i+2);
11559
11560     // We use some of the operands multiple times, so conservatively just
11561     // clear any kill flags that might be present.
11562     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11563       argOpers[i]->setIsKill(false);
11564   }
11565
11566   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11567   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11568
11569   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11570   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11571   for (int i=0; i <= lastAddrIndx; ++i)
11572     (*MIB).addOperand(*argOpers[i]);
11573   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11574   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11575   // add 4 to displacement.
11576   for (int i=0; i <= lastAddrIndx-2; ++i)
11577     (*MIB).addOperand(*argOpers[i]);
11578   MachineOperand newOp3 = *(argOpers[3]);
11579   if (newOp3.isImm())
11580     newOp3.setImm(newOp3.getImm()+4);
11581   else
11582     newOp3.setOffset(newOp3.getOffset()+4);
11583   (*MIB).addOperand(newOp3);
11584   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11585
11586   // t3/4 are defined later, at the bottom of the loop
11587   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11588   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11589   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11590     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11591   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11592     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11593
11594   // The subsequent operations should be using the destination registers of
11595   // the PHI instructions.
11596   t1 = dest1Oper.getReg();
11597   t2 = dest2Oper.getReg();
11598
11599   int valArgIndx = lastAddrIndx + 1;
11600   assert((argOpers[valArgIndx]->isReg() ||
11601           argOpers[valArgIndx]->isImm()) &&
11602          "invalid operand");
11603   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11604   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11605   if (argOpers[valArgIndx]->isReg())
11606     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11607   else
11608     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11609   if (regOpcL != X86::MOV32rr)
11610     MIB.addReg(t1);
11611   (*MIB).addOperand(*argOpers[valArgIndx]);
11612   assert(argOpers[valArgIndx + 1]->isReg() ==
11613          argOpers[valArgIndx]->isReg());
11614   assert(argOpers[valArgIndx + 1]->isImm() ==
11615          argOpers[valArgIndx]->isImm());
11616   if (argOpers[valArgIndx + 1]->isReg())
11617     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11618   else
11619     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11620   if (regOpcH != X86::MOV32rr)
11621     MIB.addReg(t2);
11622   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11623
11624   unsigned t7, t8;
11625   if (Invert) {
11626     t7 = F->getRegInfo().createVirtualRegister(RC);
11627     t8 = F->getRegInfo().createVirtualRegister(RC);
11628     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11629     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11630   } else {
11631     t7 = t5;
11632     t8 = t6;
11633   }
11634
11635   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11636   MIB.addReg(t1);
11637   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11638   MIB.addReg(t2);
11639
11640   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11641   MIB.addReg(t7);
11642   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11643   MIB.addReg(t8);
11644
11645   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11646   for (int i=0; i <= lastAddrIndx; ++i)
11647     (*MIB).addOperand(*argOpers[i]);
11648
11649   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11650   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11651                     bInstr->memoperands_end());
11652
11653   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11654   MIB.addReg(X86::EAX);
11655   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11656   MIB.addReg(X86::EDX);
11657
11658   // insert branch
11659   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11660
11661   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11662   return nextMBB;
11663 }
11664
11665 // private utility function
11666 MachineBasicBlock *
11667 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11668                                                       MachineBasicBlock *MBB,
11669                                                       unsigned cmovOpc) const {
11670   // For the atomic min/max operator, we generate
11671   //   thisMBB:
11672   //   newMBB:
11673   //     ld t1 = [min/max.addr]
11674   //     mov t2 = [min/max.val]
11675   //     cmp  t1, t2
11676   //     cmov[cond] t2 = t1
11677   //     mov EAX = t1
11678   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11679   //     bz   newMBB
11680   //     fallthrough -->nextMBB
11681   //
11682   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11683   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11684   MachineFunction::iterator MBBIter = MBB;
11685   ++MBBIter;
11686
11687   /// First build the CFG
11688   MachineFunction *F = MBB->getParent();
11689   MachineBasicBlock *thisMBB = MBB;
11690   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11691   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11692   F->insert(MBBIter, newMBB);
11693   F->insert(MBBIter, nextMBB);
11694
11695   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11696   nextMBB->splice(nextMBB->begin(), thisMBB,
11697                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11698                   thisMBB->end());
11699   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11700
11701   // Update thisMBB to fall through to newMBB
11702   thisMBB->addSuccessor(newMBB);
11703
11704   // newMBB jumps to newMBB and fall through to nextMBB
11705   newMBB->addSuccessor(nextMBB);
11706   newMBB->addSuccessor(newMBB);
11707
11708   DebugLoc dl = mInstr->getDebugLoc();
11709   // Insert instructions into newMBB based on incoming instruction
11710   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11711          "unexpected number of operands");
11712   MachineOperand& destOper = mInstr->getOperand(0);
11713   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11714   int numArgs = mInstr->getNumOperands() - 1;
11715   for (int i=0; i < numArgs; ++i)
11716     argOpers[i] = &mInstr->getOperand(i+1);
11717
11718   // x86 address has 4 operands: base, index, scale, and displacement
11719   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11720   int valArgIndx = lastAddrIndx + 1;
11721
11722   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11723   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11724   for (int i=0; i <= lastAddrIndx; ++i)
11725     (*MIB).addOperand(*argOpers[i]);
11726
11727   // We only support register and immediate values
11728   assert((argOpers[valArgIndx]->isReg() ||
11729           argOpers[valArgIndx]->isImm()) &&
11730          "invalid operand");
11731
11732   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11733   if (argOpers[valArgIndx]->isReg())
11734     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11735   else
11736     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11737   (*MIB).addOperand(*argOpers[valArgIndx]);
11738
11739   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11740   MIB.addReg(t1);
11741
11742   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11743   MIB.addReg(t1);
11744   MIB.addReg(t2);
11745
11746   // Generate movc
11747   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11748   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11749   MIB.addReg(t2);
11750   MIB.addReg(t1);
11751
11752   // Cmp and exchange if none has modified the memory location
11753   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11754   for (int i=0; i <= lastAddrIndx; ++i)
11755     (*MIB).addOperand(*argOpers[i]);
11756   MIB.addReg(t3);
11757   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11758   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11759                     mInstr->memoperands_end());
11760
11761   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11762   MIB.addReg(X86::EAX);
11763
11764   // insert branch
11765   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11766
11767   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11768   return nextMBB;
11769 }
11770
11771 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11772 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11773 // in the .td file.
11774 MachineBasicBlock *
11775 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11776                             unsigned numArgs, bool memArg) const {
11777   assert(Subtarget->hasSSE42() &&
11778          "Target must have SSE4.2 or AVX features enabled");
11779
11780   DebugLoc dl = MI->getDebugLoc();
11781   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11782   unsigned Opc;
11783   if (!Subtarget->hasAVX()) {
11784     if (memArg)
11785       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11786     else
11787       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11788   } else {
11789     if (memArg)
11790       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11791     else
11792       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11793   }
11794
11795   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11796   for (unsigned i = 0; i < numArgs; ++i) {
11797     MachineOperand &Op = MI->getOperand(i+1);
11798     if (!(Op.isReg() && Op.isImplicit()))
11799       MIB.addOperand(Op);
11800   }
11801   BuildMI(*BB, MI, dl,
11802     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11803              MI->getOperand(0).getReg())
11804     .addReg(X86::XMM0);
11805
11806   MI->eraseFromParent();
11807   return BB;
11808 }
11809
11810 MachineBasicBlock *
11811 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11812   DebugLoc dl = MI->getDebugLoc();
11813   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11814
11815   // Address into RAX/EAX, other two args into ECX, EDX.
11816   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11817   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11818   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11819   for (int i = 0; i < X86::AddrNumOperands; ++i)
11820     MIB.addOperand(MI->getOperand(i));
11821
11822   unsigned ValOps = X86::AddrNumOperands;
11823   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11824     .addReg(MI->getOperand(ValOps).getReg());
11825   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11826     .addReg(MI->getOperand(ValOps+1).getReg());
11827
11828   // The instruction doesn't actually take any operands though.
11829   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11830
11831   MI->eraseFromParent(); // The pseudo is gone now.
11832   return BB;
11833 }
11834
11835 MachineBasicBlock *
11836 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11837   DebugLoc dl = MI->getDebugLoc();
11838   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11839
11840   // First arg in ECX, the second in EAX.
11841   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11842     .addReg(MI->getOperand(0).getReg());
11843   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11844     .addReg(MI->getOperand(1).getReg());
11845
11846   // The instruction doesn't actually take any operands though.
11847   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11848
11849   MI->eraseFromParent(); // The pseudo is gone now.
11850   return BB;
11851 }
11852
11853 MachineBasicBlock *
11854 X86TargetLowering::EmitVAARG64WithCustomInserter(
11855                    MachineInstr *MI,
11856                    MachineBasicBlock *MBB) const {
11857   // Emit va_arg instruction on X86-64.
11858
11859   // Operands to this pseudo-instruction:
11860   // 0  ) Output        : destination address (reg)
11861   // 1-5) Input         : va_list address (addr, i64mem)
11862   // 6  ) ArgSize       : Size (in bytes) of vararg type
11863   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11864   // 8  ) Align         : Alignment of type
11865   // 9  ) EFLAGS (implicit-def)
11866
11867   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11868   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11869
11870   unsigned DestReg = MI->getOperand(0).getReg();
11871   MachineOperand &Base = MI->getOperand(1);
11872   MachineOperand &Scale = MI->getOperand(2);
11873   MachineOperand &Index = MI->getOperand(3);
11874   MachineOperand &Disp = MI->getOperand(4);
11875   MachineOperand &Segment = MI->getOperand(5);
11876   unsigned ArgSize = MI->getOperand(6).getImm();
11877   unsigned ArgMode = MI->getOperand(7).getImm();
11878   unsigned Align = MI->getOperand(8).getImm();
11879
11880   // Memory Reference
11881   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11882   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11883   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11884
11885   // Machine Information
11886   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11887   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11888   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11889   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11890   DebugLoc DL = MI->getDebugLoc();
11891
11892   // struct va_list {
11893   //   i32   gp_offset
11894   //   i32   fp_offset
11895   //   i64   overflow_area (address)
11896   //   i64   reg_save_area (address)
11897   // }
11898   // sizeof(va_list) = 24
11899   // alignment(va_list) = 8
11900
11901   unsigned TotalNumIntRegs = 6;
11902   unsigned TotalNumXMMRegs = 8;
11903   bool UseGPOffset = (ArgMode == 1);
11904   bool UseFPOffset = (ArgMode == 2);
11905   unsigned MaxOffset = TotalNumIntRegs * 8 +
11906                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11907
11908   /* Align ArgSize to a multiple of 8 */
11909   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11910   bool NeedsAlign = (Align > 8);
11911
11912   MachineBasicBlock *thisMBB = MBB;
11913   MachineBasicBlock *overflowMBB;
11914   MachineBasicBlock *offsetMBB;
11915   MachineBasicBlock *endMBB;
11916
11917   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11918   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11919   unsigned OffsetReg = 0;
11920
11921   if (!UseGPOffset && !UseFPOffset) {
11922     // If we only pull from the overflow region, we don't create a branch.
11923     // We don't need to alter control flow.
11924     OffsetDestReg = 0; // unused
11925     OverflowDestReg = DestReg;
11926
11927     offsetMBB = NULL;
11928     overflowMBB = thisMBB;
11929     endMBB = thisMBB;
11930   } else {
11931     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11932     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11933     // If not, pull from overflow_area. (branch to overflowMBB)
11934     //
11935     //       thisMBB
11936     //         |     .
11937     //         |        .
11938     //     offsetMBB   overflowMBB
11939     //         |        .
11940     //         |     .
11941     //        endMBB
11942
11943     // Registers for the PHI in endMBB
11944     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11945     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11946
11947     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11948     MachineFunction *MF = MBB->getParent();
11949     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11950     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11951     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11952
11953     MachineFunction::iterator MBBIter = MBB;
11954     ++MBBIter;
11955
11956     // Insert the new basic blocks
11957     MF->insert(MBBIter, offsetMBB);
11958     MF->insert(MBBIter, overflowMBB);
11959     MF->insert(MBBIter, endMBB);
11960
11961     // Transfer the remainder of MBB and its successor edges to endMBB.
11962     endMBB->splice(endMBB->begin(), thisMBB,
11963                     llvm::next(MachineBasicBlock::iterator(MI)),
11964                     thisMBB->end());
11965     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11966
11967     // Make offsetMBB and overflowMBB successors of thisMBB
11968     thisMBB->addSuccessor(offsetMBB);
11969     thisMBB->addSuccessor(overflowMBB);
11970
11971     // endMBB is a successor of both offsetMBB and overflowMBB
11972     offsetMBB->addSuccessor(endMBB);
11973     overflowMBB->addSuccessor(endMBB);
11974
11975     // Load the offset value into a register
11976     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11977     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11978       .addOperand(Base)
11979       .addOperand(Scale)
11980       .addOperand(Index)
11981       .addDisp(Disp, UseFPOffset ? 4 : 0)
11982       .addOperand(Segment)
11983       .setMemRefs(MMOBegin, MMOEnd);
11984
11985     // Check if there is enough room left to pull this argument.
11986     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11987       .addReg(OffsetReg)
11988       .addImm(MaxOffset + 8 - ArgSizeA8);
11989
11990     // Branch to "overflowMBB" if offset >= max
11991     // Fall through to "offsetMBB" otherwise
11992     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11993       .addMBB(overflowMBB);
11994   }
11995
11996   // In offsetMBB, emit code to use the reg_save_area.
11997   if (offsetMBB) {
11998     assert(OffsetReg != 0);
11999
12000     // Read the reg_save_area address.
12001     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12002     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12003       .addOperand(Base)
12004       .addOperand(Scale)
12005       .addOperand(Index)
12006       .addDisp(Disp, 16)
12007       .addOperand(Segment)
12008       .setMemRefs(MMOBegin, MMOEnd);
12009
12010     // Zero-extend the offset
12011     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12012       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12013         .addImm(0)
12014         .addReg(OffsetReg)
12015         .addImm(X86::sub_32bit);
12016
12017     // Add the offset to the reg_save_area to get the final address.
12018     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12019       .addReg(OffsetReg64)
12020       .addReg(RegSaveReg);
12021
12022     // Compute the offset for the next argument
12023     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12024     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12025       .addReg(OffsetReg)
12026       .addImm(UseFPOffset ? 16 : 8);
12027
12028     // Store it back into the va_list.
12029     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12030       .addOperand(Base)
12031       .addOperand(Scale)
12032       .addOperand(Index)
12033       .addDisp(Disp, UseFPOffset ? 4 : 0)
12034       .addOperand(Segment)
12035       .addReg(NextOffsetReg)
12036       .setMemRefs(MMOBegin, MMOEnd);
12037
12038     // Jump to endMBB
12039     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12040       .addMBB(endMBB);
12041   }
12042
12043   //
12044   // Emit code to use overflow area
12045   //
12046
12047   // Load the overflow_area address into a register.
12048   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12049   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12050     .addOperand(Base)
12051     .addOperand(Scale)
12052     .addOperand(Index)
12053     .addDisp(Disp, 8)
12054     .addOperand(Segment)
12055     .setMemRefs(MMOBegin, MMOEnd);
12056
12057   // If we need to align it, do so. Otherwise, just copy the address
12058   // to OverflowDestReg.
12059   if (NeedsAlign) {
12060     // Align the overflow address
12061     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12062     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12063
12064     // aligned_addr = (addr + (align-1)) & ~(align-1)
12065     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12066       .addReg(OverflowAddrReg)
12067       .addImm(Align-1);
12068
12069     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12070       .addReg(TmpReg)
12071       .addImm(~(uint64_t)(Align-1));
12072   } else {
12073     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12074       .addReg(OverflowAddrReg);
12075   }
12076
12077   // Compute the next overflow address after this argument.
12078   // (the overflow address should be kept 8-byte aligned)
12079   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12080   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12081     .addReg(OverflowDestReg)
12082     .addImm(ArgSizeA8);
12083
12084   // Store the new overflow address.
12085   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12086     .addOperand(Base)
12087     .addOperand(Scale)
12088     .addOperand(Index)
12089     .addDisp(Disp, 8)
12090     .addOperand(Segment)
12091     .addReg(NextAddrReg)
12092     .setMemRefs(MMOBegin, MMOEnd);
12093
12094   // If we branched, emit the PHI to the front of endMBB.
12095   if (offsetMBB) {
12096     BuildMI(*endMBB, endMBB->begin(), DL,
12097             TII->get(X86::PHI), DestReg)
12098       .addReg(OffsetDestReg).addMBB(offsetMBB)
12099       .addReg(OverflowDestReg).addMBB(overflowMBB);
12100   }
12101
12102   // Erase the pseudo instruction
12103   MI->eraseFromParent();
12104
12105   return endMBB;
12106 }
12107
12108 MachineBasicBlock *
12109 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12110                                                  MachineInstr *MI,
12111                                                  MachineBasicBlock *MBB) const {
12112   // Emit code to save XMM registers to the stack. The ABI says that the
12113   // number of registers to save is given in %al, so it's theoretically
12114   // possible to do an indirect jump trick to avoid saving all of them,
12115   // however this code takes a simpler approach and just executes all
12116   // of the stores if %al is non-zero. It's less code, and it's probably
12117   // easier on the hardware branch predictor, and stores aren't all that
12118   // expensive anyway.
12119
12120   // Create the new basic blocks. One block contains all the XMM stores,
12121   // and one block is the final destination regardless of whether any
12122   // stores were performed.
12123   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12124   MachineFunction *F = MBB->getParent();
12125   MachineFunction::iterator MBBIter = MBB;
12126   ++MBBIter;
12127   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12128   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12129   F->insert(MBBIter, XMMSaveMBB);
12130   F->insert(MBBIter, EndMBB);
12131
12132   // Transfer the remainder of MBB and its successor edges to EndMBB.
12133   EndMBB->splice(EndMBB->begin(), MBB,
12134                  llvm::next(MachineBasicBlock::iterator(MI)),
12135                  MBB->end());
12136   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12137
12138   // The original block will now fall through to the XMM save block.
12139   MBB->addSuccessor(XMMSaveMBB);
12140   // The XMMSaveMBB will fall through to the end block.
12141   XMMSaveMBB->addSuccessor(EndMBB);
12142
12143   // Now add the instructions.
12144   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12145   DebugLoc DL = MI->getDebugLoc();
12146
12147   unsigned CountReg = MI->getOperand(0).getReg();
12148   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12149   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12150
12151   if (!Subtarget->isTargetWin64()) {
12152     // If %al is 0, branch around the XMM save block.
12153     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12154     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12155     MBB->addSuccessor(EndMBB);
12156   }
12157
12158   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12159   // In the XMM save block, save all the XMM argument registers.
12160   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12161     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12162     MachineMemOperand *MMO =
12163       F->getMachineMemOperand(
12164           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12165         MachineMemOperand::MOStore,
12166         /*Size=*/16, /*Align=*/16);
12167     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12168       .addFrameIndex(RegSaveFrameIndex)
12169       .addImm(/*Scale=*/1)
12170       .addReg(/*IndexReg=*/0)
12171       .addImm(/*Disp=*/Offset)
12172       .addReg(/*Segment=*/0)
12173       .addReg(MI->getOperand(i).getReg())
12174       .addMemOperand(MMO);
12175   }
12176
12177   MI->eraseFromParent();   // The pseudo instruction is gone now.
12178
12179   return EndMBB;
12180 }
12181
12182 // The EFLAGS operand of SelectItr might be missing a kill marker
12183 // because there were multiple uses of EFLAGS, and ISel didn't know
12184 // which to mark. Figure out whether SelectItr should have had a
12185 // kill marker, and set it if it should. Returns the correct kill
12186 // marker value.
12187 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12188                                      MachineBasicBlock* BB,
12189                                      const TargetRegisterInfo* TRI) {
12190   // Scan forward through BB for a use/def of EFLAGS.
12191   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12192   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12193     const MachineInstr& mi = *miI;
12194     if (mi.readsRegister(X86::EFLAGS))
12195       return false;
12196     if (mi.definesRegister(X86::EFLAGS))
12197       break; // Should have kill-flag - update below.
12198   }
12199
12200   // If we hit the end of the block, check whether EFLAGS is live into a
12201   // successor.
12202   if (miI == BB->end()) {
12203     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12204                                           sEnd = BB->succ_end();
12205          sItr != sEnd; ++sItr) {
12206       MachineBasicBlock* succ = *sItr;
12207       if (succ->isLiveIn(X86::EFLAGS))
12208         return false;
12209     }
12210   }
12211
12212   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12213   // out. SelectMI should have a kill flag on EFLAGS.
12214   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12215   return true;
12216 }
12217
12218 MachineBasicBlock *
12219 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12220                                      MachineBasicBlock *BB) const {
12221   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12222   DebugLoc DL = MI->getDebugLoc();
12223
12224   // To "insert" a SELECT_CC instruction, we actually have to insert the
12225   // diamond control-flow pattern.  The incoming instruction knows the
12226   // destination vreg to set, the condition code register to branch on, the
12227   // true/false values to select between, and a branch opcode to use.
12228   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12229   MachineFunction::iterator It = BB;
12230   ++It;
12231
12232   //  thisMBB:
12233   //  ...
12234   //   TrueVal = ...
12235   //   cmpTY ccX, r1, r2
12236   //   bCC copy1MBB
12237   //   fallthrough --> copy0MBB
12238   MachineBasicBlock *thisMBB = BB;
12239   MachineFunction *F = BB->getParent();
12240   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12241   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12242   F->insert(It, copy0MBB);
12243   F->insert(It, sinkMBB);
12244
12245   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12246   // live into the sink and copy blocks.
12247   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12248   if (!MI->killsRegister(X86::EFLAGS) &&
12249       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12250     copy0MBB->addLiveIn(X86::EFLAGS);
12251     sinkMBB->addLiveIn(X86::EFLAGS);
12252   }
12253
12254   // Transfer the remainder of BB and its successor edges to sinkMBB.
12255   sinkMBB->splice(sinkMBB->begin(), BB,
12256                   llvm::next(MachineBasicBlock::iterator(MI)),
12257                   BB->end());
12258   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12259
12260   // Add the true and fallthrough blocks as its successors.
12261   BB->addSuccessor(copy0MBB);
12262   BB->addSuccessor(sinkMBB);
12263
12264   // Create the conditional branch instruction.
12265   unsigned Opc =
12266     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12267   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12268
12269   //  copy0MBB:
12270   //   %FalseValue = ...
12271   //   # fallthrough to sinkMBB
12272   copy0MBB->addSuccessor(sinkMBB);
12273
12274   //  sinkMBB:
12275   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12276   //  ...
12277   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12278           TII->get(X86::PHI), MI->getOperand(0).getReg())
12279     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12280     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12281
12282   MI->eraseFromParent();   // The pseudo instruction is gone now.
12283   return sinkMBB;
12284 }
12285
12286 MachineBasicBlock *
12287 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12288                                         bool Is64Bit) const {
12289   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12290   DebugLoc DL = MI->getDebugLoc();
12291   MachineFunction *MF = BB->getParent();
12292   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12293
12294   assert(getTargetMachine().Options.EnableSegmentedStacks);
12295
12296   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12297   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12298
12299   // BB:
12300   //  ... [Till the alloca]
12301   // If stacklet is not large enough, jump to mallocMBB
12302   //
12303   // bumpMBB:
12304   //  Allocate by subtracting from RSP
12305   //  Jump to continueMBB
12306   //
12307   // mallocMBB:
12308   //  Allocate by call to runtime
12309   //
12310   // continueMBB:
12311   //  ...
12312   //  [rest of original BB]
12313   //
12314
12315   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12316   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12317   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12318
12319   MachineRegisterInfo &MRI = MF->getRegInfo();
12320   const TargetRegisterClass *AddrRegClass =
12321     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12322
12323   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12324     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12325     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12326     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12327     sizeVReg = MI->getOperand(1).getReg(),
12328     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12329
12330   MachineFunction::iterator MBBIter = BB;
12331   ++MBBIter;
12332
12333   MF->insert(MBBIter, bumpMBB);
12334   MF->insert(MBBIter, mallocMBB);
12335   MF->insert(MBBIter, continueMBB);
12336
12337   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12338                       (MachineBasicBlock::iterator(MI)), BB->end());
12339   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12340
12341   // Add code to the main basic block to check if the stack limit has been hit,
12342   // and if so, jump to mallocMBB otherwise to bumpMBB.
12343   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12344   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12345     .addReg(tmpSPVReg).addReg(sizeVReg);
12346   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12347     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12348     .addReg(SPLimitVReg);
12349   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12350
12351   // bumpMBB simply decreases the stack pointer, since we know the current
12352   // stacklet has enough space.
12353   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12354     .addReg(SPLimitVReg);
12355   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12356     .addReg(SPLimitVReg);
12357   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12358
12359   // Calls into a routine in libgcc to allocate more space from the heap.
12360   const uint32_t *RegMask =
12361     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12362   if (Is64Bit) {
12363     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12364       .addReg(sizeVReg);
12365     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12366       .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI)
12367       .addRegMask(RegMask)
12368       .addReg(X86::RAX, RegState::ImplicitDefine);
12369   } else {
12370     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12371       .addImm(12);
12372     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12373     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12374       .addExternalSymbol("__morestack_allocate_stack_space")
12375       .addRegMask(RegMask)
12376       .addReg(X86::EAX, RegState::ImplicitDefine);
12377   }
12378
12379   if (!Is64Bit)
12380     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12381       .addImm(16);
12382
12383   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12384     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12385   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12386
12387   // Set up the CFG correctly.
12388   BB->addSuccessor(bumpMBB);
12389   BB->addSuccessor(mallocMBB);
12390   mallocMBB->addSuccessor(continueMBB);
12391   bumpMBB->addSuccessor(continueMBB);
12392
12393   // Take care of the PHI nodes.
12394   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12395           MI->getOperand(0).getReg())
12396     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12397     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12398
12399   // Delete the original pseudo instruction.
12400   MI->eraseFromParent();
12401
12402   // And we're done.
12403   return continueMBB;
12404 }
12405
12406 MachineBasicBlock *
12407 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12408                                           MachineBasicBlock *BB) const {
12409   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12410   DebugLoc DL = MI->getDebugLoc();
12411
12412   assert(!Subtarget->isTargetEnvMacho());
12413
12414   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12415   // non-trivial part is impdef of ESP.
12416
12417   if (Subtarget->isTargetWin64()) {
12418     if (Subtarget->isTargetCygMing()) {
12419       // ___chkstk(Mingw64):
12420       // Clobbers R10, R11, RAX and EFLAGS.
12421       // Updates RSP.
12422       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12423         .addExternalSymbol("___chkstk")
12424         .addReg(X86::RAX, RegState::Implicit)
12425         .addReg(X86::RSP, RegState::Implicit)
12426         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12427         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12428         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12429     } else {
12430       // __chkstk(MSVCRT): does not update stack pointer.
12431       // Clobbers R10, R11 and EFLAGS.
12432       // FIXME: RAX(allocated size) might be reused and not killed.
12433       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12434         .addExternalSymbol("__chkstk")
12435         .addReg(X86::RAX, RegState::Implicit)
12436         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12437       // RAX has the offset to subtracted from RSP.
12438       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12439         .addReg(X86::RSP)
12440         .addReg(X86::RAX);
12441     }
12442   } else {
12443     const char *StackProbeSymbol =
12444       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12445
12446     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12447       .addExternalSymbol(StackProbeSymbol)
12448       .addReg(X86::EAX, RegState::Implicit)
12449       .addReg(X86::ESP, RegState::Implicit)
12450       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12451       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12452       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12453   }
12454
12455   MI->eraseFromParent();   // The pseudo instruction is gone now.
12456   return BB;
12457 }
12458
12459 MachineBasicBlock *
12460 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12461                                       MachineBasicBlock *BB) const {
12462   // This is pretty easy.  We're taking the value that we received from
12463   // our load from the relocation, sticking it in either RDI (x86-64)
12464   // or EAX and doing an indirect call.  The return value will then
12465   // be in the normal return register.
12466   const X86InstrInfo *TII
12467     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12468   DebugLoc DL = MI->getDebugLoc();
12469   MachineFunction *F = BB->getParent();
12470
12471   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12472   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12473
12474   // Get a register mask for the lowered call.
12475   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12476   // proper register mask.
12477   const uint32_t *RegMask =
12478     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12479   if (Subtarget->is64Bit()) {
12480     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12481                                       TII->get(X86::MOV64rm), X86::RDI)
12482     .addReg(X86::RIP)
12483     .addImm(0).addReg(0)
12484     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12485                       MI->getOperand(3).getTargetFlags())
12486     .addReg(0);
12487     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12488     addDirectMem(MIB, X86::RDI);
12489     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12490   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12491     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12492                                       TII->get(X86::MOV32rm), X86::EAX)
12493     .addReg(0)
12494     .addImm(0).addReg(0)
12495     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12496                       MI->getOperand(3).getTargetFlags())
12497     .addReg(0);
12498     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12499     addDirectMem(MIB, X86::EAX);
12500     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12501   } else {
12502     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12503                                       TII->get(X86::MOV32rm), X86::EAX)
12504     .addReg(TII->getGlobalBaseReg(F))
12505     .addImm(0).addReg(0)
12506     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12507                       MI->getOperand(3).getTargetFlags())
12508     .addReg(0);
12509     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12510     addDirectMem(MIB, X86::EAX);
12511     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12512   }
12513
12514   MI->eraseFromParent(); // The pseudo instruction is gone now.
12515   return BB;
12516 }
12517
12518 MachineBasicBlock *
12519 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12520                                                MachineBasicBlock *BB) const {
12521   switch (MI->getOpcode()) {
12522   default: llvm_unreachable("Unexpected instr type to insert");
12523   case X86::TAILJMPd64:
12524   case X86::TAILJMPr64:
12525   case X86::TAILJMPm64:
12526     llvm_unreachable("TAILJMP64 would not be touched here.");
12527   case X86::TCRETURNdi64:
12528   case X86::TCRETURNri64:
12529   case X86::TCRETURNmi64:
12530     return BB;
12531   case X86::WIN_ALLOCA:
12532     return EmitLoweredWinAlloca(MI, BB);
12533   case X86::SEG_ALLOCA_32:
12534     return EmitLoweredSegAlloca(MI, BB, false);
12535   case X86::SEG_ALLOCA_64:
12536     return EmitLoweredSegAlloca(MI, BB, true);
12537   case X86::TLSCall_32:
12538   case X86::TLSCall_64:
12539     return EmitLoweredTLSCall(MI, BB);
12540   case X86::CMOV_GR8:
12541   case X86::CMOV_FR32:
12542   case X86::CMOV_FR64:
12543   case X86::CMOV_V4F32:
12544   case X86::CMOV_V2F64:
12545   case X86::CMOV_V2I64:
12546   case X86::CMOV_V8F32:
12547   case X86::CMOV_V4F64:
12548   case X86::CMOV_V4I64:
12549   case X86::CMOV_GR16:
12550   case X86::CMOV_GR32:
12551   case X86::CMOV_RFP32:
12552   case X86::CMOV_RFP64:
12553   case X86::CMOV_RFP80:
12554     return EmitLoweredSelect(MI, BB);
12555
12556   case X86::FP32_TO_INT16_IN_MEM:
12557   case X86::FP32_TO_INT32_IN_MEM:
12558   case X86::FP32_TO_INT64_IN_MEM:
12559   case X86::FP64_TO_INT16_IN_MEM:
12560   case X86::FP64_TO_INT32_IN_MEM:
12561   case X86::FP64_TO_INT64_IN_MEM:
12562   case X86::FP80_TO_INT16_IN_MEM:
12563   case X86::FP80_TO_INT32_IN_MEM:
12564   case X86::FP80_TO_INT64_IN_MEM: {
12565     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12566     DebugLoc DL = MI->getDebugLoc();
12567
12568     // Change the floating point control register to use "round towards zero"
12569     // mode when truncating to an integer value.
12570     MachineFunction *F = BB->getParent();
12571     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12572     addFrameReference(BuildMI(*BB, MI, DL,
12573                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12574
12575     // Load the old value of the high byte of the control word...
12576     unsigned OldCW =
12577       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12578     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12579                       CWFrameIdx);
12580
12581     // Set the high part to be round to zero...
12582     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12583       .addImm(0xC7F);
12584
12585     // Reload the modified control word now...
12586     addFrameReference(BuildMI(*BB, MI, DL,
12587                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12588
12589     // Restore the memory image of control word to original value
12590     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12591       .addReg(OldCW);
12592
12593     // Get the X86 opcode to use.
12594     unsigned Opc;
12595     switch (MI->getOpcode()) {
12596     default: llvm_unreachable("illegal opcode!");
12597     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12598     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12599     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12600     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12601     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12602     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12603     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12604     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12605     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12606     }
12607
12608     X86AddressMode AM;
12609     MachineOperand &Op = MI->getOperand(0);
12610     if (Op.isReg()) {
12611       AM.BaseType = X86AddressMode::RegBase;
12612       AM.Base.Reg = Op.getReg();
12613     } else {
12614       AM.BaseType = X86AddressMode::FrameIndexBase;
12615       AM.Base.FrameIndex = Op.getIndex();
12616     }
12617     Op = MI->getOperand(1);
12618     if (Op.isImm())
12619       AM.Scale = Op.getImm();
12620     Op = MI->getOperand(2);
12621     if (Op.isImm())
12622       AM.IndexReg = Op.getImm();
12623     Op = MI->getOperand(3);
12624     if (Op.isGlobal()) {
12625       AM.GV = Op.getGlobal();
12626     } else {
12627       AM.Disp = Op.getImm();
12628     }
12629     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12630                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12631
12632     // Reload the original control word now.
12633     addFrameReference(BuildMI(*BB, MI, DL,
12634                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12635
12636     MI->eraseFromParent();   // The pseudo instruction is gone now.
12637     return BB;
12638   }
12639     // String/text processing lowering.
12640   case X86::PCMPISTRM128REG:
12641   case X86::VPCMPISTRM128REG:
12642     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12643   case X86::PCMPISTRM128MEM:
12644   case X86::VPCMPISTRM128MEM:
12645     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12646   case X86::PCMPESTRM128REG:
12647   case X86::VPCMPESTRM128REG:
12648     return EmitPCMP(MI, BB, 5, false /* in mem */);
12649   case X86::PCMPESTRM128MEM:
12650   case X86::VPCMPESTRM128MEM:
12651     return EmitPCMP(MI, BB, 5, true /* in mem */);
12652
12653     // Thread synchronization.
12654   case X86::MONITOR:
12655     return EmitMonitor(MI, BB);
12656   case X86::MWAIT:
12657     return EmitMwait(MI, BB);
12658
12659     // Atomic Lowering.
12660   case X86::ATOMAND32:
12661     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12662                                                X86::AND32ri, X86::MOV32rm,
12663                                                X86::LCMPXCHG32,
12664                                                X86::NOT32r, X86::EAX,
12665                                                &X86::GR32RegClass);
12666   case X86::ATOMOR32:
12667     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12668                                                X86::OR32ri, X86::MOV32rm,
12669                                                X86::LCMPXCHG32,
12670                                                X86::NOT32r, X86::EAX,
12671                                                &X86::GR32RegClass);
12672   case X86::ATOMXOR32:
12673     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12674                                                X86::XOR32ri, X86::MOV32rm,
12675                                                X86::LCMPXCHG32,
12676                                                X86::NOT32r, X86::EAX,
12677                                                &X86::GR32RegClass);
12678   case X86::ATOMNAND32:
12679     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12680                                                X86::AND32ri, X86::MOV32rm,
12681                                                X86::LCMPXCHG32,
12682                                                X86::NOT32r, X86::EAX,
12683                                                &X86::GR32RegClass, true);
12684   case X86::ATOMMIN32:
12685     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12686   case X86::ATOMMAX32:
12687     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12688   case X86::ATOMUMIN32:
12689     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12690   case X86::ATOMUMAX32:
12691     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12692
12693   case X86::ATOMAND16:
12694     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12695                                                X86::AND16ri, X86::MOV16rm,
12696                                                X86::LCMPXCHG16,
12697                                                X86::NOT16r, X86::AX,
12698                                                &X86::GR16RegClass);
12699   case X86::ATOMOR16:
12700     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12701                                                X86::OR16ri, X86::MOV16rm,
12702                                                X86::LCMPXCHG16,
12703                                                X86::NOT16r, X86::AX,
12704                                                &X86::GR16RegClass);
12705   case X86::ATOMXOR16:
12706     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12707                                                X86::XOR16ri, X86::MOV16rm,
12708                                                X86::LCMPXCHG16,
12709                                                X86::NOT16r, X86::AX,
12710                                                &X86::GR16RegClass);
12711   case X86::ATOMNAND16:
12712     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12713                                                X86::AND16ri, X86::MOV16rm,
12714                                                X86::LCMPXCHG16,
12715                                                X86::NOT16r, X86::AX,
12716                                                &X86::GR16RegClass, true);
12717   case X86::ATOMMIN16:
12718     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12719   case X86::ATOMMAX16:
12720     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12721   case X86::ATOMUMIN16:
12722     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12723   case X86::ATOMUMAX16:
12724     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12725
12726   case X86::ATOMAND8:
12727     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12728                                                X86::AND8ri, X86::MOV8rm,
12729                                                X86::LCMPXCHG8,
12730                                                X86::NOT8r, X86::AL,
12731                                                &X86::GR8RegClass);
12732   case X86::ATOMOR8:
12733     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12734                                                X86::OR8ri, X86::MOV8rm,
12735                                                X86::LCMPXCHG8,
12736                                                X86::NOT8r, X86::AL,
12737                                                &X86::GR8RegClass);
12738   case X86::ATOMXOR8:
12739     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12740                                                X86::XOR8ri, X86::MOV8rm,
12741                                                X86::LCMPXCHG8,
12742                                                X86::NOT8r, X86::AL,
12743                                                &X86::GR8RegClass);
12744   case X86::ATOMNAND8:
12745     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12746                                                X86::AND8ri, X86::MOV8rm,
12747                                                X86::LCMPXCHG8,
12748                                                X86::NOT8r, X86::AL,
12749                                                &X86::GR8RegClass, true);
12750   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12751   // This group is for 64-bit host.
12752   case X86::ATOMAND64:
12753     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12754                                                X86::AND64ri32, X86::MOV64rm,
12755                                                X86::LCMPXCHG64,
12756                                                X86::NOT64r, X86::RAX,
12757                                                &X86::GR64RegClass);
12758   case X86::ATOMOR64:
12759     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12760                                                X86::OR64ri32, X86::MOV64rm,
12761                                                X86::LCMPXCHG64,
12762                                                X86::NOT64r, X86::RAX,
12763                                                &X86::GR64RegClass);
12764   case X86::ATOMXOR64:
12765     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12766                                                X86::XOR64ri32, X86::MOV64rm,
12767                                                X86::LCMPXCHG64,
12768                                                X86::NOT64r, X86::RAX,
12769                                                &X86::GR64RegClass);
12770   case X86::ATOMNAND64:
12771     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12772                                                X86::AND64ri32, X86::MOV64rm,
12773                                                X86::LCMPXCHG64,
12774                                                X86::NOT64r, X86::RAX,
12775                                                &X86::GR64RegClass, true);
12776   case X86::ATOMMIN64:
12777     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12778   case X86::ATOMMAX64:
12779     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12780   case X86::ATOMUMIN64:
12781     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12782   case X86::ATOMUMAX64:
12783     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12784
12785   // This group does 64-bit operations on a 32-bit host.
12786   case X86::ATOMAND6432:
12787     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12788                                                X86::AND32rr, X86::AND32rr,
12789                                                X86::AND32ri, X86::AND32ri,
12790                                                false);
12791   case X86::ATOMOR6432:
12792     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12793                                                X86::OR32rr, X86::OR32rr,
12794                                                X86::OR32ri, X86::OR32ri,
12795                                                false);
12796   case X86::ATOMXOR6432:
12797     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12798                                                X86::XOR32rr, X86::XOR32rr,
12799                                                X86::XOR32ri, X86::XOR32ri,
12800                                                false);
12801   case X86::ATOMNAND6432:
12802     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12803                                                X86::AND32rr, X86::AND32rr,
12804                                                X86::AND32ri, X86::AND32ri,
12805                                                true);
12806   case X86::ATOMADD6432:
12807     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12808                                                X86::ADD32rr, X86::ADC32rr,
12809                                                X86::ADD32ri, X86::ADC32ri,
12810                                                false);
12811   case X86::ATOMSUB6432:
12812     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12813                                                X86::SUB32rr, X86::SBB32rr,
12814                                                X86::SUB32ri, X86::SBB32ri,
12815                                                false);
12816   case X86::ATOMSWAP6432:
12817     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12818                                                X86::MOV32rr, X86::MOV32rr,
12819                                                X86::MOV32ri, X86::MOV32ri,
12820                                                false);
12821   case X86::VASTART_SAVE_XMM_REGS:
12822     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12823
12824   case X86::VAARG_64:
12825     return EmitVAARG64WithCustomInserter(MI, BB);
12826   }
12827 }
12828
12829 //===----------------------------------------------------------------------===//
12830 //                           X86 Optimization Hooks
12831 //===----------------------------------------------------------------------===//
12832
12833 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12834                                                        APInt &KnownZero,
12835                                                        APInt &KnownOne,
12836                                                        const SelectionDAG &DAG,
12837                                                        unsigned Depth) const {
12838   unsigned BitWidth = KnownZero.getBitWidth();
12839   unsigned Opc = Op.getOpcode();
12840   assert((Opc >= ISD::BUILTIN_OP_END ||
12841           Opc == ISD::INTRINSIC_WO_CHAIN ||
12842           Opc == ISD::INTRINSIC_W_CHAIN ||
12843           Opc == ISD::INTRINSIC_VOID) &&
12844          "Should use MaskedValueIsZero if you don't know whether Op"
12845          " is a target node!");
12846
12847   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
12848   switch (Opc) {
12849   default: break;
12850   case X86ISD::ADD:
12851   case X86ISD::SUB:
12852   case X86ISD::ADC:
12853   case X86ISD::SBB:
12854   case X86ISD::SMUL:
12855   case X86ISD::UMUL:
12856   case X86ISD::INC:
12857   case X86ISD::DEC:
12858   case X86ISD::OR:
12859   case X86ISD::XOR:
12860   case X86ISD::AND:
12861     // These nodes' second result is a boolean.
12862     if (Op.getResNo() == 0)
12863       break;
12864     // Fallthrough
12865   case X86ISD::SETCC:
12866     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12867     break;
12868   case ISD::INTRINSIC_WO_CHAIN: {
12869     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12870     unsigned NumLoBits = 0;
12871     switch (IntId) {
12872     default: break;
12873     case Intrinsic::x86_sse_movmsk_ps:
12874     case Intrinsic::x86_avx_movmsk_ps_256:
12875     case Intrinsic::x86_sse2_movmsk_pd:
12876     case Intrinsic::x86_avx_movmsk_pd_256:
12877     case Intrinsic::x86_mmx_pmovmskb:
12878     case Intrinsic::x86_sse2_pmovmskb_128:
12879     case Intrinsic::x86_avx2_pmovmskb: {
12880       // High bits of movmskp{s|d}, pmovmskb are known zero.
12881       switch (IntId) {
12882         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12883         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12884         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12885         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12886         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12887         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12888         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12889         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
12890       }
12891       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
12892       break;
12893     }
12894     }
12895     break;
12896   }
12897   }
12898 }
12899
12900 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12901                                                          unsigned Depth) const {
12902   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12903   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12904     return Op.getValueType().getScalarType().getSizeInBits();
12905
12906   // Fallback case.
12907   return 1;
12908 }
12909
12910 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12911 /// node is a GlobalAddress + offset.
12912 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12913                                        const GlobalValue* &GA,
12914                                        int64_t &Offset) const {
12915   if (N->getOpcode() == X86ISD::Wrapper) {
12916     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12917       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12918       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12919       return true;
12920     }
12921   }
12922   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12923 }
12924
12925 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12926 /// same as extracting the high 128-bit part of 256-bit vector and then
12927 /// inserting the result into the low part of a new 256-bit vector
12928 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12929   EVT VT = SVOp->getValueType(0);
12930   unsigned NumElems = VT.getVectorNumElements();
12931
12932   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12933   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
12934     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12935         SVOp->getMaskElt(j) >= 0)
12936       return false;
12937
12938   return true;
12939 }
12940
12941 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12942 /// same as extracting the low 128-bit part of 256-bit vector and then
12943 /// inserting the result into the high part of a new 256-bit vector
12944 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12945   EVT VT = SVOp->getValueType(0);
12946   unsigned NumElems = VT.getVectorNumElements();
12947
12948   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12949   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
12950     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12951         SVOp->getMaskElt(j) >= 0)
12952       return false;
12953
12954   return true;
12955 }
12956
12957 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12958 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12959                                         TargetLowering::DAGCombinerInfo &DCI,
12960                                         const X86Subtarget* Subtarget) {
12961   DebugLoc dl = N->getDebugLoc();
12962   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12963   SDValue V1 = SVOp->getOperand(0);
12964   SDValue V2 = SVOp->getOperand(1);
12965   EVT VT = SVOp->getValueType(0);
12966   unsigned NumElems = VT.getVectorNumElements();
12967
12968   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12969       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12970     //
12971     //                   0,0,0,...
12972     //                      |
12973     //    V      UNDEF    BUILD_VECTOR    UNDEF
12974     //     \      /           \           /
12975     //  CONCAT_VECTOR         CONCAT_VECTOR
12976     //         \                  /
12977     //          \                /
12978     //          RESULT: V + zero extended
12979     //
12980     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12981         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12982         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12983       return SDValue();
12984
12985     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12986       return SDValue();
12987
12988     // To match the shuffle mask, the first half of the mask should
12989     // be exactly the first vector, and all the rest a splat with the
12990     // first element of the second one.
12991     for (unsigned i = 0; i != NumElems/2; ++i)
12992       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12993           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12994         return SDValue();
12995
12996     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
12997     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
12998       if (Ld->hasNUsesOfValue(1, 0)) {
12999         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13000         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13001         SDValue ResNode =
13002           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13003                                   Ld->getMemoryVT(),
13004                                   Ld->getPointerInfo(),
13005                                   Ld->getAlignment(),
13006                                   false/*isVolatile*/, true/*ReadMem*/,
13007                                   false/*WriteMem*/);
13008         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13009       }
13010     } 
13011
13012     // Emit a zeroed vector and insert the desired subvector on its
13013     // first half.
13014     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13015     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13016     return DCI.CombineTo(N, InsV);
13017   }
13018
13019   //===--------------------------------------------------------------------===//
13020   // Combine some shuffles into subvector extracts and inserts:
13021   //
13022
13023   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13024   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13025     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13026     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13027     return DCI.CombineTo(N, InsV);
13028   }
13029
13030   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13031   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13032     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13033     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13034     return DCI.CombineTo(N, InsV);
13035   }
13036
13037   return SDValue();
13038 }
13039
13040 /// PerformShuffleCombine - Performs several different shuffle combines.
13041 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13042                                      TargetLowering::DAGCombinerInfo &DCI,
13043                                      const X86Subtarget *Subtarget) {
13044   DebugLoc dl = N->getDebugLoc();
13045   EVT VT = N->getValueType(0);
13046
13047   // Don't create instructions with illegal types after legalize types has run.
13048   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13049   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13050     return SDValue();
13051
13052   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13053   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13054       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13055     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13056
13057   // Only handle 128 wide vector from here on.
13058   if (VT.getSizeInBits() != 128)
13059     return SDValue();
13060
13061   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13062   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13063   // consecutive, non-overlapping, and in the right order.
13064   SmallVector<SDValue, 16> Elts;
13065   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13066     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13067
13068   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13069 }
13070
13071
13072 /// DCI, PerformTruncateCombine - Converts truncate operation to
13073 /// a sequence of vector shuffle operations.
13074 /// It is possible when we truncate 256-bit vector to 128-bit vector
13075
13076 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG, 
13077                                                   DAGCombinerInfo &DCI) const {
13078   if (!DCI.isBeforeLegalizeOps())
13079     return SDValue();
13080
13081   if (!Subtarget->hasAVX())
13082     return SDValue();
13083
13084   EVT VT = N->getValueType(0);
13085   SDValue Op = N->getOperand(0);
13086   EVT OpVT = Op.getValueType();
13087   DebugLoc dl = N->getDebugLoc();
13088
13089   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13090
13091     if (Subtarget->hasAVX2()) {
13092       // AVX2: v4i64 -> v4i32
13093
13094       // VPERMD
13095       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13096
13097       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13098       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13099                                 ShufMask);
13100
13101       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13102                          DAG.getIntPtrConstant(0));
13103     }
13104
13105     // AVX: v4i64 -> v4i32
13106     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13107                                DAG.getIntPtrConstant(0));
13108
13109     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13110                                DAG.getIntPtrConstant(2));
13111
13112     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13113     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13114
13115     // PSHUFD
13116     static const int ShufMask1[] = {0, 2, 0, 0};
13117
13118     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1);
13119     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1);
13120
13121     // MOVLHPS
13122     static const int ShufMask2[] = {0, 1, 4, 5};
13123
13124     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13125   }
13126
13127   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13128
13129     if (Subtarget->hasAVX2()) {
13130       // AVX2: v8i32 -> v8i16
13131
13132       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13133
13134       // PSHUFB
13135       SmallVector<SDValue,32> pshufbMask;
13136       for (unsigned i = 0; i < 2; ++i) {
13137         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13138         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13139         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13140         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13141         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13142         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13143         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13144         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13145         for (unsigned j = 0; j < 8; ++j)
13146           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13147       }
13148       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13149                                &pshufbMask[0], 32);
13150       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13151
13152       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13153
13154       static const int ShufMask[] = {0,  2,  -1,  -1};
13155       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13156                                 &ShufMask[0]);
13157
13158       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13159                        DAG.getIntPtrConstant(0));
13160
13161       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13162     }
13163
13164     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13165                                DAG.getIntPtrConstant(0));
13166
13167     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13168                                DAG.getIntPtrConstant(4));
13169
13170     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13171     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13172
13173     // PSHUFB
13174     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13175                                    -1, -1, -1, -1, -1, -1, -1, -1};
13176
13177     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8),
13178                                 ShufMask1);
13179     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8),
13180                                 ShufMask1);
13181
13182     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13183     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13184
13185     // MOVLHPS
13186     static const int ShufMask2[] = {0, 1, 4, 5};
13187
13188     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13189     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13190   }
13191
13192   return SDValue();
13193 }
13194
13195 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13196 /// specific shuffle of a load can be folded into a single element load.
13197 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13198 /// shuffles have been customed lowered so we need to handle those here.
13199 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13200                                          TargetLowering::DAGCombinerInfo &DCI) {
13201   if (DCI.isBeforeLegalizeOps())
13202     return SDValue();
13203
13204   SDValue InVec = N->getOperand(0);
13205   SDValue EltNo = N->getOperand(1);
13206
13207   if (!isa<ConstantSDNode>(EltNo))
13208     return SDValue();
13209
13210   EVT VT = InVec.getValueType();
13211
13212   bool HasShuffleIntoBitcast = false;
13213   if (InVec.getOpcode() == ISD::BITCAST) {
13214     // Don't duplicate a load with other uses.
13215     if (!InVec.hasOneUse())
13216       return SDValue();
13217     EVT BCVT = InVec.getOperand(0).getValueType();
13218     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13219       return SDValue();
13220     InVec = InVec.getOperand(0);
13221     HasShuffleIntoBitcast = true;
13222   }
13223
13224   if (!isTargetShuffle(InVec.getOpcode()))
13225     return SDValue();
13226
13227   // Don't duplicate a load with other uses.
13228   if (!InVec.hasOneUse())
13229     return SDValue();
13230
13231   SmallVector<int, 16> ShuffleMask;
13232   bool UnaryShuffle;
13233   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13234                             UnaryShuffle))
13235     return SDValue();
13236
13237   // Select the input vector, guarding against out of range extract vector.
13238   unsigned NumElems = VT.getVectorNumElements();
13239   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13240   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13241   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13242                                          : InVec.getOperand(1);
13243
13244   // If inputs to shuffle are the same for both ops, then allow 2 uses
13245   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13246
13247   if (LdNode.getOpcode() == ISD::BITCAST) {
13248     // Don't duplicate a load with other uses.
13249     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13250       return SDValue();
13251
13252     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13253     LdNode = LdNode.getOperand(0);
13254   }
13255
13256   if (!ISD::isNormalLoad(LdNode.getNode()))
13257     return SDValue();
13258
13259   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13260
13261   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13262     return SDValue();
13263
13264   if (HasShuffleIntoBitcast) {
13265     // If there's a bitcast before the shuffle, check if the load type and
13266     // alignment is valid.
13267     unsigned Align = LN0->getAlignment();
13268     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13269     unsigned NewAlign = TLI.getTargetData()->
13270       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13271
13272     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13273       return SDValue();
13274   }
13275
13276   // All checks match so transform back to vector_shuffle so that DAG combiner
13277   // can finish the job
13278   DebugLoc dl = N->getDebugLoc();
13279
13280   // Create shuffle node taking into account the case that its a unary shuffle
13281   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13282   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13283                                  InVec.getOperand(0), Shuffle,
13284                                  &ShuffleMask[0]);
13285   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13286   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13287                      EltNo);
13288 }
13289
13290 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13291 /// generation and convert it from being a bunch of shuffles and extracts
13292 /// to a simple store and scalar loads to extract the elements.
13293 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13294                                          TargetLowering::DAGCombinerInfo &DCI) {
13295   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13296   if (NewOp.getNode())
13297     return NewOp;
13298
13299   SDValue InputVector = N->getOperand(0);
13300
13301   // Only operate on vectors of 4 elements, where the alternative shuffling
13302   // gets to be more expensive.
13303   if (InputVector.getValueType() != MVT::v4i32)
13304     return SDValue();
13305
13306   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13307   // single use which is a sign-extend or zero-extend, and all elements are
13308   // used.
13309   SmallVector<SDNode *, 4> Uses;
13310   unsigned ExtractedElements = 0;
13311   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13312        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13313     if (UI.getUse().getResNo() != InputVector.getResNo())
13314       return SDValue();
13315
13316     SDNode *Extract = *UI;
13317     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13318       return SDValue();
13319
13320     if (Extract->getValueType(0) != MVT::i32)
13321       return SDValue();
13322     if (!Extract->hasOneUse())
13323       return SDValue();
13324     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13325         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13326       return SDValue();
13327     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13328       return SDValue();
13329
13330     // Record which element was extracted.
13331     ExtractedElements |=
13332       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13333
13334     Uses.push_back(Extract);
13335   }
13336
13337   // If not all the elements were used, this may not be worthwhile.
13338   if (ExtractedElements != 15)
13339     return SDValue();
13340
13341   // Ok, we've now decided to do the transformation.
13342   DebugLoc dl = InputVector.getDebugLoc();
13343
13344   // Store the value to a temporary stack slot.
13345   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13346   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13347                             MachinePointerInfo(), false, false, 0);
13348
13349   // Replace each use (extract) with a load of the appropriate element.
13350   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13351        UE = Uses.end(); UI != UE; ++UI) {
13352     SDNode *Extract = *UI;
13353
13354     // cOMpute the element's address.
13355     SDValue Idx = Extract->getOperand(1);
13356     unsigned EltSize =
13357         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13358     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13359     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13360     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13361
13362     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13363                                      StackPtr, OffsetVal);
13364
13365     // Load the scalar.
13366     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13367                                      ScalarAddr, MachinePointerInfo(),
13368                                      false, false, false, 0);
13369
13370     // Replace the exact with the load.
13371     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13372   }
13373
13374   // The replacement was made in place; don't return anything.
13375   return SDValue();
13376 }
13377
13378 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13379 /// nodes.
13380 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13381                                     TargetLowering::DAGCombinerInfo &DCI,
13382                                     const X86Subtarget *Subtarget) {
13383   DebugLoc DL = N->getDebugLoc();
13384   SDValue Cond = N->getOperand(0);
13385   // Get the LHS/RHS of the select.
13386   SDValue LHS = N->getOperand(1);
13387   SDValue RHS = N->getOperand(2);
13388   EVT VT = LHS.getValueType();
13389
13390   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13391   // instructions match the semantics of the common C idiom x<y?x:y but not
13392   // x<=y?x:y, because of how they handle negative zero (which can be
13393   // ignored in unsafe-math mode).
13394   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13395       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13396       (Subtarget->hasSSE2() ||
13397        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13398     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13399
13400     unsigned Opcode = 0;
13401     // Check for x CC y ? x : y.
13402     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13403         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13404       switch (CC) {
13405       default: break;
13406       case ISD::SETULT:
13407         // Converting this to a min would handle NaNs incorrectly, and swapping
13408         // the operands would cause it to handle comparisons between positive
13409         // and negative zero incorrectly.
13410         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13411           if (!DAG.getTarget().Options.UnsafeFPMath &&
13412               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13413             break;
13414           std::swap(LHS, RHS);
13415         }
13416         Opcode = X86ISD::FMIN;
13417         break;
13418       case ISD::SETOLE:
13419         // Converting this to a min would handle comparisons between positive
13420         // and negative zero incorrectly.
13421         if (!DAG.getTarget().Options.UnsafeFPMath &&
13422             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13423           break;
13424         Opcode = X86ISD::FMIN;
13425         break;
13426       case ISD::SETULE:
13427         // Converting this to a min would handle both negative zeros and NaNs
13428         // incorrectly, but we can swap the operands to fix both.
13429         std::swap(LHS, RHS);
13430       case ISD::SETOLT:
13431       case ISD::SETLT:
13432       case ISD::SETLE:
13433         Opcode = X86ISD::FMIN;
13434         break;
13435
13436       case ISD::SETOGE:
13437         // Converting this to a max would handle comparisons between positive
13438         // and negative zero incorrectly.
13439         if (!DAG.getTarget().Options.UnsafeFPMath &&
13440             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13441           break;
13442         Opcode = X86ISD::FMAX;
13443         break;
13444       case ISD::SETUGT:
13445         // Converting this to a max would handle NaNs incorrectly, and swapping
13446         // the operands would cause it to handle comparisons between positive
13447         // and negative zero incorrectly.
13448         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13449           if (!DAG.getTarget().Options.UnsafeFPMath &&
13450               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13451             break;
13452           std::swap(LHS, RHS);
13453         }
13454         Opcode = X86ISD::FMAX;
13455         break;
13456       case ISD::SETUGE:
13457         // Converting this to a max would handle both negative zeros and NaNs
13458         // incorrectly, but we can swap the operands to fix both.
13459         std::swap(LHS, RHS);
13460       case ISD::SETOGT:
13461       case ISD::SETGT:
13462       case ISD::SETGE:
13463         Opcode = X86ISD::FMAX;
13464         break;
13465       }
13466     // Check for x CC y ? y : x -- a min/max with reversed arms.
13467     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13468                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13469       switch (CC) {
13470       default: break;
13471       case ISD::SETOGE:
13472         // Converting this to a min would handle comparisons between positive
13473         // and negative zero incorrectly, and swapping the operands would
13474         // cause it to handle NaNs incorrectly.
13475         if (!DAG.getTarget().Options.UnsafeFPMath &&
13476             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13477           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13478             break;
13479           std::swap(LHS, RHS);
13480         }
13481         Opcode = X86ISD::FMIN;
13482         break;
13483       case ISD::SETUGT:
13484         // Converting this to a min would handle NaNs incorrectly.
13485         if (!DAG.getTarget().Options.UnsafeFPMath &&
13486             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13487           break;
13488         Opcode = X86ISD::FMIN;
13489         break;
13490       case ISD::SETUGE:
13491         // Converting this to a min would handle both negative zeros and NaNs
13492         // incorrectly, but we can swap the operands to fix both.
13493         std::swap(LHS, RHS);
13494       case ISD::SETOGT:
13495       case ISD::SETGT:
13496       case ISD::SETGE:
13497         Opcode = X86ISD::FMIN;
13498         break;
13499
13500       case ISD::SETULT:
13501         // Converting this to a max would handle NaNs incorrectly.
13502         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13503           break;
13504         Opcode = X86ISD::FMAX;
13505         break;
13506       case ISD::SETOLE:
13507         // Converting this to a max would handle comparisons between positive
13508         // and negative zero incorrectly, and swapping the operands would
13509         // cause it to handle NaNs incorrectly.
13510         if (!DAG.getTarget().Options.UnsafeFPMath &&
13511             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13512           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13513             break;
13514           std::swap(LHS, RHS);
13515         }
13516         Opcode = X86ISD::FMAX;
13517         break;
13518       case ISD::SETULE:
13519         // Converting this to a max would handle both negative zeros and NaNs
13520         // incorrectly, but we can swap the operands to fix both.
13521         std::swap(LHS, RHS);
13522       case ISD::SETOLT:
13523       case ISD::SETLT:
13524       case ISD::SETLE:
13525         Opcode = X86ISD::FMAX;
13526         break;
13527       }
13528     }
13529
13530     if (Opcode)
13531       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13532   }
13533
13534   // If this is a select between two integer constants, try to do some
13535   // optimizations.
13536   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13537     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13538       // Don't do this for crazy integer types.
13539       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13540         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13541         // so that TrueC (the true value) is larger than FalseC.
13542         bool NeedsCondInvert = false;
13543
13544         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13545             // Efficiently invertible.
13546             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13547              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13548               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13549           NeedsCondInvert = true;
13550           std::swap(TrueC, FalseC);
13551         }
13552
13553         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13554         if (FalseC->getAPIntValue() == 0 &&
13555             TrueC->getAPIntValue().isPowerOf2()) {
13556           if (NeedsCondInvert) // Invert the condition if needed.
13557             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13558                                DAG.getConstant(1, Cond.getValueType()));
13559
13560           // Zero extend the condition if needed.
13561           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13562
13563           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13564           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13565                              DAG.getConstant(ShAmt, MVT::i8));
13566         }
13567
13568         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13569         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13570           if (NeedsCondInvert) // Invert the condition if needed.
13571             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13572                                DAG.getConstant(1, Cond.getValueType()));
13573
13574           // Zero extend the condition if needed.
13575           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13576                              FalseC->getValueType(0), Cond);
13577           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13578                              SDValue(FalseC, 0));
13579         }
13580
13581         // Optimize cases that will turn into an LEA instruction.  This requires
13582         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13583         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13584           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13585           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13586
13587           bool isFastMultiplier = false;
13588           if (Diff < 10) {
13589             switch ((unsigned char)Diff) {
13590               default: break;
13591               case 1:  // result = add base, cond
13592               case 2:  // result = lea base(    , cond*2)
13593               case 3:  // result = lea base(cond, cond*2)
13594               case 4:  // result = lea base(    , cond*4)
13595               case 5:  // result = lea base(cond, cond*4)
13596               case 8:  // result = lea base(    , cond*8)
13597               case 9:  // result = lea base(cond, cond*8)
13598                 isFastMultiplier = true;
13599                 break;
13600             }
13601           }
13602
13603           if (isFastMultiplier) {
13604             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13605             if (NeedsCondInvert) // Invert the condition if needed.
13606               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13607                                  DAG.getConstant(1, Cond.getValueType()));
13608
13609             // Zero extend the condition if needed.
13610             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13611                                Cond);
13612             // Scale the condition by the difference.
13613             if (Diff != 1)
13614               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13615                                  DAG.getConstant(Diff, Cond.getValueType()));
13616
13617             // Add the base if non-zero.
13618             if (FalseC->getAPIntValue() != 0)
13619               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13620                                  SDValue(FalseC, 0));
13621             return Cond;
13622           }
13623         }
13624       }
13625   }
13626
13627   // Canonicalize max and min:
13628   // (x > y) ? x : y -> (x >= y) ? x : y
13629   // (x < y) ? x : y -> (x <= y) ? x : y
13630   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13631   // the need for an extra compare
13632   // against zero. e.g.
13633   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13634   // subl   %esi, %edi
13635   // testl  %edi, %edi
13636   // movl   $0, %eax
13637   // cmovgl %edi, %eax
13638   // =>
13639   // xorl   %eax, %eax
13640   // subl   %esi, $edi
13641   // cmovsl %eax, %edi
13642   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13643       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13644       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13645     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13646     switch (CC) {
13647     default: break;
13648     case ISD::SETLT:
13649     case ISD::SETGT: {
13650       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13651       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13652                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
13653       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13654     }
13655     }
13656   }
13657
13658   // If we know that this node is legal then we know that it is going to be
13659   // matched by one of the SSE/AVX BLEND instructions. These instructions only
13660   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13661   // to simplify previous instructions.
13662   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13663   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13664       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
13665     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13666
13667     // Don't optimize vector selects that map to mask-registers.
13668     if (BitWidth == 1)
13669       return SDValue();
13670
13671     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13672     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13673
13674     APInt KnownZero, KnownOne;
13675     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13676                                           DCI.isBeforeLegalizeOps());
13677     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13678         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13679       DCI.CommitTargetLoweringOpt(TLO);
13680   }
13681
13682   return SDValue();
13683 }
13684
13685 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13686 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13687                                   TargetLowering::DAGCombinerInfo &DCI) {
13688   DebugLoc DL = N->getDebugLoc();
13689
13690   // If the flag operand isn't dead, don't touch this CMOV.
13691   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13692     return SDValue();
13693
13694   SDValue FalseOp = N->getOperand(0);
13695   SDValue TrueOp = N->getOperand(1);
13696   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13697   SDValue Cond = N->getOperand(3);
13698   if (CC == X86::COND_E || CC == X86::COND_NE) {
13699     switch (Cond.getOpcode()) {
13700     default: break;
13701     case X86ISD::BSR:
13702     case X86ISD::BSF:
13703       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13704       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13705         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13706     }
13707   }
13708
13709   // If this is a select between two integer constants, try to do some
13710   // optimizations.  Note that the operands are ordered the opposite of SELECT
13711   // operands.
13712   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13713     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13714       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13715       // larger than FalseC (the false value).
13716       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13717         CC = X86::GetOppositeBranchCondition(CC);
13718         std::swap(TrueC, FalseC);
13719       }
13720
13721       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13722       // This is efficient for any integer data type (including i8/i16) and
13723       // shift amount.
13724       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13725         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13726                            DAG.getConstant(CC, MVT::i8), Cond);
13727
13728         // Zero extend the condition if needed.
13729         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13730
13731         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13732         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13733                            DAG.getConstant(ShAmt, MVT::i8));
13734         if (N->getNumValues() == 2)  // Dead flag value?
13735           return DCI.CombineTo(N, Cond, SDValue());
13736         return Cond;
13737       }
13738
13739       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13740       // for any integer data type, including i8/i16.
13741       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13742         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13743                            DAG.getConstant(CC, MVT::i8), Cond);
13744
13745         // Zero extend the condition if needed.
13746         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13747                            FalseC->getValueType(0), Cond);
13748         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13749                            SDValue(FalseC, 0));
13750
13751         if (N->getNumValues() == 2)  // Dead flag value?
13752           return DCI.CombineTo(N, Cond, SDValue());
13753         return Cond;
13754       }
13755
13756       // Optimize cases that will turn into an LEA instruction.  This requires
13757       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13758       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13759         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13760         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13761
13762         bool isFastMultiplier = false;
13763         if (Diff < 10) {
13764           switch ((unsigned char)Diff) {
13765           default: break;
13766           case 1:  // result = add base, cond
13767           case 2:  // result = lea base(    , cond*2)
13768           case 3:  // result = lea base(cond, cond*2)
13769           case 4:  // result = lea base(    , cond*4)
13770           case 5:  // result = lea base(cond, cond*4)
13771           case 8:  // result = lea base(    , cond*8)
13772           case 9:  // result = lea base(cond, cond*8)
13773             isFastMultiplier = true;
13774             break;
13775           }
13776         }
13777
13778         if (isFastMultiplier) {
13779           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13780           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13781                              DAG.getConstant(CC, MVT::i8), Cond);
13782           // Zero extend the condition if needed.
13783           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13784                              Cond);
13785           // Scale the condition by the difference.
13786           if (Diff != 1)
13787             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13788                                DAG.getConstant(Diff, Cond.getValueType()));
13789
13790           // Add the base if non-zero.
13791           if (FalseC->getAPIntValue() != 0)
13792             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13793                                SDValue(FalseC, 0));
13794           if (N->getNumValues() == 2)  // Dead flag value?
13795             return DCI.CombineTo(N, Cond, SDValue());
13796           return Cond;
13797         }
13798       }
13799     }
13800   }
13801   return SDValue();
13802 }
13803
13804
13805 /// PerformMulCombine - Optimize a single multiply with constant into two
13806 /// in order to implement it with two cheaper instructions, e.g.
13807 /// LEA + SHL, LEA + LEA.
13808 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13809                                  TargetLowering::DAGCombinerInfo &DCI) {
13810   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13811     return SDValue();
13812
13813   EVT VT = N->getValueType(0);
13814   if (VT != MVT::i64)
13815     return SDValue();
13816
13817   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13818   if (!C)
13819     return SDValue();
13820   uint64_t MulAmt = C->getZExtValue();
13821   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13822     return SDValue();
13823
13824   uint64_t MulAmt1 = 0;
13825   uint64_t MulAmt2 = 0;
13826   if ((MulAmt % 9) == 0) {
13827     MulAmt1 = 9;
13828     MulAmt2 = MulAmt / 9;
13829   } else if ((MulAmt % 5) == 0) {
13830     MulAmt1 = 5;
13831     MulAmt2 = MulAmt / 5;
13832   } else if ((MulAmt % 3) == 0) {
13833     MulAmt1 = 3;
13834     MulAmt2 = MulAmt / 3;
13835   }
13836   if (MulAmt2 &&
13837       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13838     DebugLoc DL = N->getDebugLoc();
13839
13840     if (isPowerOf2_64(MulAmt2) &&
13841         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13842       // If second multiplifer is pow2, issue it first. We want the multiply by
13843       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13844       // is an add.
13845       std::swap(MulAmt1, MulAmt2);
13846
13847     SDValue NewMul;
13848     if (isPowerOf2_64(MulAmt1))
13849       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13850                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13851     else
13852       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13853                            DAG.getConstant(MulAmt1, VT));
13854
13855     if (isPowerOf2_64(MulAmt2))
13856       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13857                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13858     else
13859       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13860                            DAG.getConstant(MulAmt2, VT));
13861
13862     // Do not add new nodes to DAG combiner worklist.
13863     DCI.CombineTo(N, NewMul, false);
13864   }
13865   return SDValue();
13866 }
13867
13868 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13869   SDValue N0 = N->getOperand(0);
13870   SDValue N1 = N->getOperand(1);
13871   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13872   EVT VT = N0.getValueType();
13873
13874   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13875   // since the result of setcc_c is all zero's or all ones.
13876   if (VT.isInteger() && !VT.isVector() &&
13877       N1C && N0.getOpcode() == ISD::AND &&
13878       N0.getOperand(1).getOpcode() == ISD::Constant) {
13879     SDValue N00 = N0.getOperand(0);
13880     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13881         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13882           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13883          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13884       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13885       APInt ShAmt = N1C->getAPIntValue();
13886       Mask = Mask.shl(ShAmt);
13887       if (Mask != 0)
13888         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13889                            N00, DAG.getConstant(Mask, VT));
13890     }
13891   }
13892
13893
13894   // Hardware support for vector shifts is sparse which makes us scalarize the
13895   // vector operations in many cases. Also, on sandybridge ADD is faster than
13896   // shl.
13897   // (shl V, 1) -> add V,V
13898   if (isSplatVector(N1.getNode())) {
13899     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13900     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13901     // We shift all of the values by one. In many cases we do not have
13902     // hardware support for this operation. This is better expressed as an ADD
13903     // of two values.
13904     if (N1C && (1 == N1C->getZExtValue())) {
13905       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13906     }
13907   }
13908
13909   return SDValue();
13910 }
13911
13912 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13913 ///                       when possible.
13914 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13915                                    TargetLowering::DAGCombinerInfo &DCI,
13916                                    const X86Subtarget *Subtarget) {
13917   EVT VT = N->getValueType(0);
13918   if (N->getOpcode() == ISD::SHL) {
13919     SDValue V = PerformSHLCombine(N, DAG);
13920     if (V.getNode()) return V;
13921   }
13922
13923   // On X86 with SSE2 support, we can transform this to a vector shift if
13924   // all elements are shifted by the same amount.  We can't do this in legalize
13925   // because the a constant vector is typically transformed to a constant pool
13926   // so we have no knowledge of the shift amount.
13927   if (!Subtarget->hasSSE2())
13928     return SDValue();
13929
13930   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13931       (!Subtarget->hasAVX2() ||
13932        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13933     return SDValue();
13934
13935   SDValue ShAmtOp = N->getOperand(1);
13936   EVT EltVT = VT.getVectorElementType();
13937   DebugLoc DL = N->getDebugLoc();
13938   SDValue BaseShAmt = SDValue();
13939   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13940     unsigned NumElts = VT.getVectorNumElements();
13941     unsigned i = 0;
13942     for (; i != NumElts; ++i) {
13943       SDValue Arg = ShAmtOp.getOperand(i);
13944       if (Arg.getOpcode() == ISD::UNDEF) continue;
13945       BaseShAmt = Arg;
13946       break;
13947     }
13948     // Handle the case where the build_vector is all undef
13949     // FIXME: Should DAG allow this?
13950     if (i == NumElts)
13951       return SDValue();
13952
13953     for (; i != NumElts; ++i) {
13954       SDValue Arg = ShAmtOp.getOperand(i);
13955       if (Arg.getOpcode() == ISD::UNDEF) continue;
13956       if (Arg != BaseShAmt) {
13957         return SDValue();
13958       }
13959     }
13960   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13961              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13962     SDValue InVec = ShAmtOp.getOperand(0);
13963     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13964       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13965       unsigned i = 0;
13966       for (; i != NumElts; ++i) {
13967         SDValue Arg = InVec.getOperand(i);
13968         if (Arg.getOpcode() == ISD::UNDEF) continue;
13969         BaseShAmt = Arg;
13970         break;
13971       }
13972     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13973        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13974          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13975          if (C->getZExtValue() == SplatIdx)
13976            BaseShAmt = InVec.getOperand(1);
13977        }
13978     }
13979     if (BaseShAmt.getNode() == 0) {
13980       // Don't create instructions with illegal types after legalize
13981       // types has run.
13982       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
13983           !DCI.isBeforeLegalize())
13984         return SDValue();
13985
13986       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13987                               DAG.getIntPtrConstant(0));
13988     }
13989   } else
13990     return SDValue();
13991
13992   // The shift amount is an i32.
13993   if (EltVT.bitsGT(MVT::i32))
13994     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13995   else if (EltVT.bitsLT(MVT::i32))
13996     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13997
13998   // The shift amount is identical so we can do a vector shift.
13999   SDValue  ValOp = N->getOperand(0);
14000   switch (N->getOpcode()) {
14001   default:
14002     llvm_unreachable("Unknown shift opcode!");
14003   case ISD::SHL:
14004     switch (VT.getSimpleVT().SimpleTy) {
14005     default: return SDValue();
14006     case MVT::v2i64:
14007     case MVT::v4i32:
14008     case MVT::v8i16:
14009     case MVT::v4i64:
14010     case MVT::v8i32:
14011     case MVT::v16i16:
14012       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14013     }
14014   case ISD::SRA:
14015     switch (VT.getSimpleVT().SimpleTy) {
14016     default: return SDValue();
14017     case MVT::v4i32:
14018     case MVT::v8i16:
14019     case MVT::v8i32:
14020     case MVT::v16i16:
14021       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14022     }
14023   case ISD::SRL:
14024     switch (VT.getSimpleVT().SimpleTy) {
14025     default: return SDValue();
14026     case MVT::v2i64:
14027     case MVT::v4i32:
14028     case MVT::v8i16:
14029     case MVT::v4i64:
14030     case MVT::v8i32:
14031     case MVT::v16i16:
14032       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14033     }
14034   }
14035 }
14036
14037
14038 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14039 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14040 // and friends.  Likewise for OR -> CMPNEQSS.
14041 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14042                             TargetLowering::DAGCombinerInfo &DCI,
14043                             const X86Subtarget *Subtarget) {
14044   unsigned opcode;
14045
14046   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14047   // we're requiring SSE2 for both.
14048   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14049     SDValue N0 = N->getOperand(0);
14050     SDValue N1 = N->getOperand(1);
14051     SDValue CMP0 = N0->getOperand(1);
14052     SDValue CMP1 = N1->getOperand(1);
14053     DebugLoc DL = N->getDebugLoc();
14054
14055     // The SETCCs should both refer to the same CMP.
14056     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14057       return SDValue();
14058
14059     SDValue CMP00 = CMP0->getOperand(0);
14060     SDValue CMP01 = CMP0->getOperand(1);
14061     EVT     VT    = CMP00.getValueType();
14062
14063     if (VT == MVT::f32 || VT == MVT::f64) {
14064       bool ExpectingFlags = false;
14065       // Check for any users that want flags:
14066       for (SDNode::use_iterator UI = N->use_begin(),
14067              UE = N->use_end();
14068            !ExpectingFlags && UI != UE; ++UI)
14069         switch (UI->getOpcode()) {
14070         default:
14071         case ISD::BR_CC:
14072         case ISD::BRCOND:
14073         case ISD::SELECT:
14074           ExpectingFlags = true;
14075           break;
14076         case ISD::CopyToReg:
14077         case ISD::SIGN_EXTEND:
14078         case ISD::ZERO_EXTEND:
14079         case ISD::ANY_EXTEND:
14080           break;
14081         }
14082
14083       if (!ExpectingFlags) {
14084         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14085         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14086
14087         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14088           X86::CondCode tmp = cc0;
14089           cc0 = cc1;
14090           cc1 = tmp;
14091         }
14092
14093         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14094             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14095           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14096           X86ISD::NodeType NTOperator = is64BitFP ?
14097             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14098           // FIXME: need symbolic constants for these magic numbers.
14099           // See X86ATTInstPrinter.cpp:printSSECC().
14100           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14101           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14102                                               DAG.getConstant(x86cc, MVT::i8));
14103           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14104                                               OnesOrZeroesF);
14105           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14106                                       DAG.getConstant(1, MVT::i32));
14107           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14108           return OneBitOfTruth;
14109         }
14110       }
14111     }
14112   }
14113   return SDValue();
14114 }
14115
14116 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14117 /// so it can be folded inside ANDNP.
14118 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14119   EVT VT = N->getValueType(0);
14120
14121   // Match direct AllOnes for 128 and 256-bit vectors
14122   if (ISD::isBuildVectorAllOnes(N))
14123     return true;
14124
14125   // Look through a bit convert.
14126   if (N->getOpcode() == ISD::BITCAST)
14127     N = N->getOperand(0).getNode();
14128
14129   // Sometimes the operand may come from a insert_subvector building a 256-bit
14130   // allones vector
14131   if (VT.getSizeInBits() == 256 &&
14132       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14133     SDValue V1 = N->getOperand(0);
14134     SDValue V2 = N->getOperand(1);
14135
14136     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14137         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14138         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14139         ISD::isBuildVectorAllOnes(V2.getNode()))
14140       return true;
14141   }
14142
14143   return false;
14144 }
14145
14146 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14147                                  TargetLowering::DAGCombinerInfo &DCI,
14148                                  const X86Subtarget *Subtarget) {
14149   if (DCI.isBeforeLegalizeOps())
14150     return SDValue();
14151
14152   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14153   if (R.getNode())
14154     return R;
14155
14156   EVT VT = N->getValueType(0);
14157
14158   // Create ANDN, BLSI, and BLSR instructions
14159   // BLSI is X & (-X)
14160   // BLSR is X & (X-1)
14161   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14162     SDValue N0 = N->getOperand(0);
14163     SDValue N1 = N->getOperand(1);
14164     DebugLoc DL = N->getDebugLoc();
14165
14166     // Check LHS for not
14167     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14168       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14169     // Check RHS for not
14170     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14171       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14172
14173     // Check LHS for neg
14174     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14175         isZero(N0.getOperand(0)))
14176       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14177
14178     // Check RHS for neg
14179     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14180         isZero(N1.getOperand(0)))
14181       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14182
14183     // Check LHS for X-1
14184     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14185         isAllOnes(N0.getOperand(1)))
14186       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14187
14188     // Check RHS for X-1
14189     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14190         isAllOnes(N1.getOperand(1)))
14191       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14192
14193     return SDValue();
14194   }
14195
14196   // Want to form ANDNP nodes:
14197   // 1) In the hopes of then easily combining them with OR and AND nodes
14198   //    to form PBLEND/PSIGN.
14199   // 2) To match ANDN packed intrinsics
14200   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14201     return SDValue();
14202
14203   SDValue N0 = N->getOperand(0);
14204   SDValue N1 = N->getOperand(1);
14205   DebugLoc DL = N->getDebugLoc();
14206
14207   // Check LHS for vnot
14208   if (N0.getOpcode() == ISD::XOR &&
14209       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14210       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14211     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14212
14213   // Check RHS for vnot
14214   if (N1.getOpcode() == ISD::XOR &&
14215       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14216       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14217     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14218
14219   return SDValue();
14220 }
14221
14222 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14223                                 TargetLowering::DAGCombinerInfo &DCI,
14224                                 const X86Subtarget *Subtarget) {
14225   if (DCI.isBeforeLegalizeOps())
14226     return SDValue();
14227
14228   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14229   if (R.getNode())
14230     return R;
14231
14232   EVT VT = N->getValueType(0);
14233
14234   SDValue N0 = N->getOperand(0);
14235   SDValue N1 = N->getOperand(1);
14236
14237   // look for psign/blend
14238   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14239     if (!Subtarget->hasSSSE3() ||
14240         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14241       return SDValue();
14242
14243     // Canonicalize pandn to RHS
14244     if (N0.getOpcode() == X86ISD::ANDNP)
14245       std::swap(N0, N1);
14246     // or (and (m, y), (pandn m, x))
14247     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14248       SDValue Mask = N1.getOperand(0);
14249       SDValue X    = N1.getOperand(1);
14250       SDValue Y;
14251       if (N0.getOperand(0) == Mask)
14252         Y = N0.getOperand(1);
14253       if (N0.getOperand(1) == Mask)
14254         Y = N0.getOperand(0);
14255
14256       // Check to see if the mask appeared in both the AND and ANDNP and
14257       if (!Y.getNode())
14258         return SDValue();
14259
14260       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14261       // Look through mask bitcast.
14262       if (Mask.getOpcode() == ISD::BITCAST)
14263         Mask = Mask.getOperand(0);
14264       if (X.getOpcode() == ISD::BITCAST)
14265         X = X.getOperand(0);
14266       if (Y.getOpcode() == ISD::BITCAST)
14267         Y = Y.getOperand(0);
14268
14269       EVT MaskVT = Mask.getValueType();
14270
14271       // Validate that the Mask operand is a vector sra node.
14272       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14273       // there is no psrai.b
14274       if (Mask.getOpcode() != X86ISD::VSRAI)
14275         return SDValue();
14276
14277       // Check that the SRA is all signbits.
14278       SDValue SraC = Mask.getOperand(1);
14279       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14280       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14281       if ((SraAmt + 1) != EltBits)
14282         return SDValue();
14283
14284       DebugLoc DL = N->getDebugLoc();
14285
14286       // Now we know we at least have a plendvb with the mask val.  See if
14287       // we can form a psignb/w/d.
14288       // psign = x.type == y.type == mask.type && y = sub(0, x);
14289       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14290           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14291           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14292         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14293                "Unsupported VT for PSIGN");
14294         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14295         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14296       }
14297       // PBLENDVB only available on SSE 4.1
14298       if (!Subtarget->hasSSE41())
14299         return SDValue();
14300
14301       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14302
14303       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14304       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14305       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14306       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14307       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14308     }
14309   }
14310
14311   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14312     return SDValue();
14313
14314   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14315   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14316     std::swap(N0, N1);
14317   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14318     return SDValue();
14319   if (!N0.hasOneUse() || !N1.hasOneUse())
14320     return SDValue();
14321
14322   SDValue ShAmt0 = N0.getOperand(1);
14323   if (ShAmt0.getValueType() != MVT::i8)
14324     return SDValue();
14325   SDValue ShAmt1 = N1.getOperand(1);
14326   if (ShAmt1.getValueType() != MVT::i8)
14327     return SDValue();
14328   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14329     ShAmt0 = ShAmt0.getOperand(0);
14330   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14331     ShAmt1 = ShAmt1.getOperand(0);
14332
14333   DebugLoc DL = N->getDebugLoc();
14334   unsigned Opc = X86ISD::SHLD;
14335   SDValue Op0 = N0.getOperand(0);
14336   SDValue Op1 = N1.getOperand(0);
14337   if (ShAmt0.getOpcode() == ISD::SUB) {
14338     Opc = X86ISD::SHRD;
14339     std::swap(Op0, Op1);
14340     std::swap(ShAmt0, ShAmt1);
14341   }
14342
14343   unsigned Bits = VT.getSizeInBits();
14344   if (ShAmt1.getOpcode() == ISD::SUB) {
14345     SDValue Sum = ShAmt1.getOperand(0);
14346     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14347       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14348       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14349         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14350       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14351         return DAG.getNode(Opc, DL, VT,
14352                            Op0, Op1,
14353                            DAG.getNode(ISD::TRUNCATE, DL,
14354                                        MVT::i8, ShAmt0));
14355     }
14356   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14357     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14358     if (ShAmt0C &&
14359         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14360       return DAG.getNode(Opc, DL, VT,
14361                          N0.getOperand(0), N1.getOperand(0),
14362                          DAG.getNode(ISD::TRUNCATE, DL,
14363                                        MVT::i8, ShAmt0));
14364   }
14365
14366   return SDValue();
14367 }
14368
14369 // Generate NEG and CMOV for integer abs.
14370 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14371   EVT VT = N->getValueType(0);
14372
14373   // Since X86 does not have CMOV for 8-bit integer, we don't convert
14374   // 8-bit integer abs to NEG and CMOV.
14375   if (VT.isInteger() && VT.getSizeInBits() == 8)
14376     return SDValue();
14377
14378   SDValue N0 = N->getOperand(0);
14379   SDValue N1 = N->getOperand(1);
14380   DebugLoc DL = N->getDebugLoc();
14381
14382   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14383   // and change it to SUB and CMOV.
14384   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14385       N0.getOpcode() == ISD::ADD &&
14386       N0.getOperand(1) == N1 &&
14387       N1.getOpcode() == ISD::SRA &&
14388       N1.getOperand(0) == N0.getOperand(0))
14389     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14390       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14391         // Generate SUB & CMOV.
14392         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14393                                   DAG.getConstant(0, VT), N0.getOperand(0));
14394
14395         SDValue Ops[] = { N0.getOperand(0), Neg,
14396                           DAG.getConstant(X86::COND_GE, MVT::i8),
14397                           SDValue(Neg.getNode(), 1) };
14398         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14399                            Ops, array_lengthof(Ops));
14400       }
14401   return SDValue();
14402 }
14403
14404 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14405 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14406                                  TargetLowering::DAGCombinerInfo &DCI,
14407                                  const X86Subtarget *Subtarget) {
14408   if (DCI.isBeforeLegalizeOps())
14409     return SDValue();
14410
14411   if (Subtarget->hasCMov()) {
14412     SDValue RV = performIntegerAbsCombine(N, DAG);
14413     if (RV.getNode())
14414       return RV;
14415   }
14416
14417   // Try forming BMI if it is available.
14418   if (!Subtarget->hasBMI())
14419     return SDValue();
14420
14421   EVT VT = N->getValueType(0);
14422
14423   if (VT != MVT::i32 && VT != MVT::i64)
14424     return SDValue();
14425
14426   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14427
14428   // Create BLSMSK instructions by finding X ^ (X-1)
14429   SDValue N0 = N->getOperand(0);
14430   SDValue N1 = N->getOperand(1);
14431   DebugLoc DL = N->getDebugLoc();
14432
14433   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14434       isAllOnes(N0.getOperand(1)))
14435     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14436
14437   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14438       isAllOnes(N1.getOperand(1)))
14439     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14440
14441   return SDValue();
14442 }
14443
14444 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14445 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14446                                    const X86Subtarget *Subtarget) {
14447   LoadSDNode *Ld = cast<LoadSDNode>(N);
14448   EVT RegVT = Ld->getValueType(0);
14449   EVT MemVT = Ld->getMemoryVT();
14450   DebugLoc dl = Ld->getDebugLoc();
14451   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14452
14453   ISD::LoadExtType Ext = Ld->getExtensionType();
14454
14455   // If this is a vector EXT Load then attempt to optimize it using a
14456   // shuffle. We need SSE4 for the shuffles.
14457   // TODO: It is possible to support ZExt by zeroing the undef values
14458   // during the shuffle phase or after the shuffle.
14459   if (RegVT.isVector() && RegVT.isInteger() &&
14460       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14461     assert(MemVT != RegVT && "Cannot extend to the same type");
14462     assert(MemVT.isVector() && "Must load a vector from memory");
14463
14464     unsigned NumElems = RegVT.getVectorNumElements();
14465     unsigned RegSz = RegVT.getSizeInBits();
14466     unsigned MemSz = MemVT.getSizeInBits();
14467     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14468     // All sizes must be a power of two
14469     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14470
14471     // Attempt to load the original value using a single load op.
14472     // Find a scalar type which is equal to the loaded word size.
14473     MVT SclrLoadTy = MVT::i8;
14474     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14475          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14476       MVT Tp = (MVT::SimpleValueType)tp;
14477       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
14478         SclrLoadTy = Tp;
14479         break;
14480       }
14481     }
14482
14483     // Proceed if a load word is found.
14484     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14485
14486     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14487       RegSz/SclrLoadTy.getSizeInBits());
14488
14489     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14490                                   RegSz/MemVT.getScalarType().getSizeInBits());
14491     // Can't shuffle using an illegal type.
14492     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14493
14494     // Perform a single load.
14495     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14496                                   Ld->getBasePtr(),
14497                                   Ld->getPointerInfo(), Ld->isVolatile(),
14498                                   Ld->isNonTemporal(), Ld->isInvariant(),
14499                                   Ld->getAlignment());
14500
14501     // Insert the word loaded into a vector.
14502     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14503       LoadUnitVecVT, ScalarLoad);
14504
14505     // Bitcast the loaded value to a vector of the original element type, in
14506     // the size of the target vector type.
14507     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT,
14508                                     ScalarInVector);
14509     unsigned SizeRatio = RegSz/MemSz;
14510
14511     // Redistribute the loaded elements into the different locations.
14512     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14513     for (unsigned i = 0; i != NumElems; ++i)
14514       ShuffleVec[i*SizeRatio] = i;
14515
14516     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14517                                          DAG.getUNDEF(WideVecVT),
14518                                          &ShuffleVec[0]);
14519
14520     // Bitcast to the requested type.
14521     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14522     // Replace the original load with the new sequence
14523     // and return the new chain.
14524     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14525     return SDValue(ScalarLoad.getNode(), 1);
14526   }
14527
14528   return SDValue();
14529 }
14530
14531 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14532 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14533                                    const X86Subtarget *Subtarget) {
14534   StoreSDNode *St = cast<StoreSDNode>(N);
14535   EVT VT = St->getValue().getValueType();
14536   EVT StVT = St->getMemoryVT();
14537   DebugLoc dl = St->getDebugLoc();
14538   SDValue StoredVal = St->getOperand(1);
14539   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14540
14541   // If we are saving a concatenation of two XMM registers, perform two stores.
14542   // On Sandy Bridge, 256-bit memory operations are executed by two
14543   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
14544   // memory  operation.
14545   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2() &&
14546       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14547       StoredVal.getNumOperands() == 2) {
14548     SDValue Value0 = StoredVal.getOperand(0);
14549     SDValue Value1 = StoredVal.getOperand(1);
14550
14551     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14552     SDValue Ptr0 = St->getBasePtr();
14553     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14554
14555     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14556                                 St->getPointerInfo(), St->isVolatile(),
14557                                 St->isNonTemporal(), St->getAlignment());
14558     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14559                                 St->getPointerInfo(), St->isVolatile(),
14560                                 St->isNonTemporal(), St->getAlignment());
14561     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14562   }
14563
14564   // Optimize trunc store (of multiple scalars) to shuffle and store.
14565   // First, pack all of the elements in one place. Next, store to memory
14566   // in fewer chunks.
14567   if (St->isTruncatingStore() && VT.isVector()) {
14568     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14569     unsigned NumElems = VT.getVectorNumElements();
14570     assert(StVT != VT && "Cannot truncate to the same type");
14571     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14572     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14573
14574     // From, To sizes and ElemCount must be pow of two
14575     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14576     // We are going to use the original vector elt for storing.
14577     // Accumulated smaller vector elements must be a multiple of the store size.
14578     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14579
14580     unsigned SizeRatio  = FromSz / ToSz;
14581
14582     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14583
14584     // Create a type on which we perform the shuffle
14585     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14586             StVT.getScalarType(), NumElems*SizeRatio);
14587
14588     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14589
14590     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14591     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14592     for (unsigned i = 0; i != NumElems; ++i)
14593       ShuffleVec[i] = i * SizeRatio;
14594
14595     // Can't shuffle using an illegal type
14596     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14597
14598     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14599                                          DAG.getUNDEF(WideVecVT),
14600                                          &ShuffleVec[0]);
14601     // At this point all of the data is stored at the bottom of the
14602     // register. We now need to save it to mem.
14603
14604     // Find the largest store unit
14605     MVT StoreType = MVT::i8;
14606     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14607          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14608       MVT Tp = (MVT::SimpleValueType)tp;
14609       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14610         StoreType = Tp;
14611     }
14612
14613     // Bitcast the original vector into a vector of store-size units
14614     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14615             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14616     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14617     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14618     SmallVector<SDValue, 8> Chains;
14619     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14620                                         TLI.getPointerTy());
14621     SDValue Ptr = St->getBasePtr();
14622
14623     // Perform one or more big stores into memory.
14624     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
14625       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14626                                    StoreType, ShuffWide,
14627                                    DAG.getIntPtrConstant(i));
14628       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14629                                 St->getPointerInfo(), St->isVolatile(),
14630                                 St->isNonTemporal(), St->getAlignment());
14631       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14632       Chains.push_back(Ch);
14633     }
14634
14635     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14636                                Chains.size());
14637   }
14638
14639
14640   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14641   // the FP state in cases where an emms may be missing.
14642   // A preferable solution to the general problem is to figure out the right
14643   // places to insert EMMS.  This qualifies as a quick hack.
14644
14645   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14646   if (VT.getSizeInBits() != 64)
14647     return SDValue();
14648
14649   const Function *F = DAG.getMachineFunction().getFunction();
14650   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14651   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14652                      && Subtarget->hasSSE2();
14653   if ((VT.isVector() ||
14654        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14655       isa<LoadSDNode>(St->getValue()) &&
14656       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14657       St->getChain().hasOneUse() && !St->isVolatile()) {
14658     SDNode* LdVal = St->getValue().getNode();
14659     LoadSDNode *Ld = 0;
14660     int TokenFactorIndex = -1;
14661     SmallVector<SDValue, 8> Ops;
14662     SDNode* ChainVal = St->getChain().getNode();
14663     // Must be a store of a load.  We currently handle two cases:  the load
14664     // is a direct child, and it's under an intervening TokenFactor.  It is
14665     // possible to dig deeper under nested TokenFactors.
14666     if (ChainVal == LdVal)
14667       Ld = cast<LoadSDNode>(St->getChain());
14668     else if (St->getValue().hasOneUse() &&
14669              ChainVal->getOpcode() == ISD::TokenFactor) {
14670       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14671         if (ChainVal->getOperand(i).getNode() == LdVal) {
14672           TokenFactorIndex = i;
14673           Ld = cast<LoadSDNode>(St->getValue());
14674         } else
14675           Ops.push_back(ChainVal->getOperand(i));
14676       }
14677     }
14678
14679     if (!Ld || !ISD::isNormalLoad(Ld))
14680       return SDValue();
14681
14682     // If this is not the MMX case, i.e. we are just turning i64 load/store
14683     // into f64 load/store, avoid the transformation if there are multiple
14684     // uses of the loaded value.
14685     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14686       return SDValue();
14687
14688     DebugLoc LdDL = Ld->getDebugLoc();
14689     DebugLoc StDL = N->getDebugLoc();
14690     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14691     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14692     // pair instead.
14693     if (Subtarget->is64Bit() || F64IsLegal) {
14694       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14695       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14696                                   Ld->getPointerInfo(), Ld->isVolatile(),
14697                                   Ld->isNonTemporal(), Ld->isInvariant(),
14698                                   Ld->getAlignment());
14699       SDValue NewChain = NewLd.getValue(1);
14700       if (TokenFactorIndex != -1) {
14701         Ops.push_back(NewChain);
14702         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14703                                Ops.size());
14704       }
14705       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14706                           St->getPointerInfo(),
14707                           St->isVolatile(), St->isNonTemporal(),
14708                           St->getAlignment());
14709     }
14710
14711     // Otherwise, lower to two pairs of 32-bit loads / stores.
14712     SDValue LoAddr = Ld->getBasePtr();
14713     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14714                                  DAG.getConstant(4, MVT::i32));
14715
14716     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14717                                Ld->getPointerInfo(),
14718                                Ld->isVolatile(), Ld->isNonTemporal(),
14719                                Ld->isInvariant(), Ld->getAlignment());
14720     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14721                                Ld->getPointerInfo().getWithOffset(4),
14722                                Ld->isVolatile(), Ld->isNonTemporal(),
14723                                Ld->isInvariant(),
14724                                MinAlign(Ld->getAlignment(), 4));
14725
14726     SDValue NewChain = LoLd.getValue(1);
14727     if (TokenFactorIndex != -1) {
14728       Ops.push_back(LoLd);
14729       Ops.push_back(HiLd);
14730       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14731                              Ops.size());
14732     }
14733
14734     LoAddr = St->getBasePtr();
14735     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14736                          DAG.getConstant(4, MVT::i32));
14737
14738     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14739                                 St->getPointerInfo(),
14740                                 St->isVolatile(), St->isNonTemporal(),
14741                                 St->getAlignment());
14742     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14743                                 St->getPointerInfo().getWithOffset(4),
14744                                 St->isVolatile(),
14745                                 St->isNonTemporal(),
14746                                 MinAlign(St->getAlignment(), 4));
14747     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14748   }
14749   return SDValue();
14750 }
14751
14752 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14753 /// and return the operands for the horizontal operation in LHS and RHS.  A
14754 /// horizontal operation performs the binary operation on successive elements
14755 /// of its first operand, then on successive elements of its second operand,
14756 /// returning the resulting values in a vector.  For example, if
14757 ///   A = < float a0, float a1, float a2, float a3 >
14758 /// and
14759 ///   B = < float b0, float b1, float b2, float b3 >
14760 /// then the result of doing a horizontal operation on A and B is
14761 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14762 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14763 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14764 /// set to A, RHS to B, and the routine returns 'true'.
14765 /// Note that the binary operation should have the property that if one of the
14766 /// operands is UNDEF then the result is UNDEF.
14767 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14768   // Look for the following pattern: if
14769   //   A = < float a0, float a1, float a2, float a3 >
14770   //   B = < float b0, float b1, float b2, float b3 >
14771   // and
14772   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14773   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14774   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14775   // which is A horizontal-op B.
14776
14777   // At least one of the operands should be a vector shuffle.
14778   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14779       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14780     return false;
14781
14782   EVT VT = LHS.getValueType();
14783
14784   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14785          "Unsupported vector type for horizontal add/sub");
14786
14787   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14788   // operate independently on 128-bit lanes.
14789   unsigned NumElts = VT.getVectorNumElements();
14790   unsigned NumLanes = VT.getSizeInBits()/128;
14791   unsigned NumLaneElts = NumElts / NumLanes;
14792   assert((NumLaneElts % 2 == 0) &&
14793          "Vector type should have an even number of elements in each lane");
14794   unsigned HalfLaneElts = NumLaneElts/2;
14795
14796   // View LHS in the form
14797   //   LHS = VECTOR_SHUFFLE A, B, LMask
14798   // If LHS is not a shuffle then pretend it is the shuffle
14799   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14800   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14801   // type VT.
14802   SDValue A, B;
14803   SmallVector<int, 16> LMask(NumElts);
14804   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14805     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14806       A = LHS.getOperand(0);
14807     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14808       B = LHS.getOperand(1);
14809     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
14810     std::copy(Mask.begin(), Mask.end(), LMask.begin());
14811   } else {
14812     if (LHS.getOpcode() != ISD::UNDEF)
14813       A = LHS;
14814     for (unsigned i = 0; i != NumElts; ++i)
14815       LMask[i] = i;
14816   }
14817
14818   // Likewise, view RHS in the form
14819   //   RHS = VECTOR_SHUFFLE C, D, RMask
14820   SDValue C, D;
14821   SmallVector<int, 16> RMask(NumElts);
14822   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14823     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14824       C = RHS.getOperand(0);
14825     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14826       D = RHS.getOperand(1);
14827     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
14828     std::copy(Mask.begin(), Mask.end(), RMask.begin());
14829   } else {
14830     if (RHS.getOpcode() != ISD::UNDEF)
14831       C = RHS;
14832     for (unsigned i = 0; i != NumElts; ++i)
14833       RMask[i] = i;
14834   }
14835
14836   // Check that the shuffles are both shuffling the same vectors.
14837   if (!(A == C && B == D) && !(A == D && B == C))
14838     return false;
14839
14840   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14841   if (!A.getNode() && !B.getNode())
14842     return false;
14843
14844   // If A and B occur in reverse order in RHS, then "swap" them (which means
14845   // rewriting the mask).
14846   if (A != C)
14847     CommuteVectorShuffleMask(RMask, NumElts);
14848
14849   // At this point LHS and RHS are equivalent to
14850   //   LHS = VECTOR_SHUFFLE A, B, LMask
14851   //   RHS = VECTOR_SHUFFLE A, B, RMask
14852   // Check that the masks correspond to performing a horizontal operation.
14853   for (unsigned i = 0; i != NumElts; ++i) {
14854     int LIdx = LMask[i], RIdx = RMask[i];
14855
14856     // Ignore any UNDEF components.
14857     if (LIdx < 0 || RIdx < 0 ||
14858         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14859         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14860       continue;
14861
14862     // Check that successive elements are being operated on.  If not, this is
14863     // not a horizontal operation.
14864     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14865     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14866     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14867     if (!(LIdx == Index && RIdx == Index + 1) &&
14868         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14869       return false;
14870   }
14871
14872   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14873   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14874   return true;
14875 }
14876
14877 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14878 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14879                                   const X86Subtarget *Subtarget) {
14880   EVT VT = N->getValueType(0);
14881   SDValue LHS = N->getOperand(0);
14882   SDValue RHS = N->getOperand(1);
14883
14884   // Try to synthesize horizontal adds from adds of shuffles.
14885   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14886        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14887       isHorizontalBinOp(LHS, RHS, true))
14888     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14889   return SDValue();
14890 }
14891
14892 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14893 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14894                                   const X86Subtarget *Subtarget) {
14895   EVT VT = N->getValueType(0);
14896   SDValue LHS = N->getOperand(0);
14897   SDValue RHS = N->getOperand(1);
14898
14899   // Try to synthesize horizontal subs from subs of shuffles.
14900   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14901        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14902       isHorizontalBinOp(LHS, RHS, false))
14903     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14904   return SDValue();
14905 }
14906
14907 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14908 /// X86ISD::FXOR nodes.
14909 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14910   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14911   // F[X]OR(0.0, x) -> x
14912   // F[X]OR(x, 0.0) -> x
14913   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14914     if (C->getValueAPF().isPosZero())
14915       return N->getOperand(1);
14916   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14917     if (C->getValueAPF().isPosZero())
14918       return N->getOperand(0);
14919   return SDValue();
14920 }
14921
14922 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14923 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14924   // FAND(0.0, x) -> 0.0
14925   // FAND(x, 0.0) -> 0.0
14926   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14927     if (C->getValueAPF().isPosZero())
14928       return N->getOperand(0);
14929   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14930     if (C->getValueAPF().isPosZero())
14931       return N->getOperand(1);
14932   return SDValue();
14933 }
14934
14935 static SDValue PerformBTCombine(SDNode *N,
14936                                 SelectionDAG &DAG,
14937                                 TargetLowering::DAGCombinerInfo &DCI) {
14938   // BT ignores high bits in the bit index operand.
14939   SDValue Op1 = N->getOperand(1);
14940   if (Op1.hasOneUse()) {
14941     unsigned BitWidth = Op1.getValueSizeInBits();
14942     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14943     APInt KnownZero, KnownOne;
14944     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14945                                           !DCI.isBeforeLegalizeOps());
14946     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14947     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14948         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14949       DCI.CommitTargetLoweringOpt(TLO);
14950   }
14951   return SDValue();
14952 }
14953
14954 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14955   SDValue Op = N->getOperand(0);
14956   if (Op.getOpcode() == ISD::BITCAST)
14957     Op = Op.getOperand(0);
14958   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14959   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14960       VT.getVectorElementType().getSizeInBits() ==
14961       OpVT.getVectorElementType().getSizeInBits()) {
14962     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14963   }
14964   return SDValue();
14965 }
14966
14967 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
14968                                   TargetLowering::DAGCombinerInfo &DCI,
14969                                   const X86Subtarget *Subtarget) {
14970   if (!DCI.isBeforeLegalizeOps())
14971     return SDValue();
14972
14973   if (!Subtarget->hasAVX())
14974     return SDValue();
14975
14976   EVT VT = N->getValueType(0);
14977   SDValue Op = N->getOperand(0);
14978   EVT OpVT = Op.getValueType();
14979   DebugLoc dl = N->getDebugLoc();
14980
14981   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
14982       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
14983
14984     if (Subtarget->hasAVX2())
14985       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
14986
14987     // Optimize vectors in AVX mode
14988     // Sign extend  v8i16 to v8i32 and
14989     //              v4i32 to v4i64
14990     //
14991     // Divide input vector into two parts
14992     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14993     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14994     // concat the vectors to original VT
14995
14996     unsigned NumElems = OpVT.getVectorNumElements();
14997     SmallVector<int,8> ShufMask1(NumElems, -1);
14998     for (unsigned i = 0; i != NumElems/2; ++i)
14999       ShufMask1[i] = i;
15000
15001     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15002                                         &ShufMask1[0]);
15003
15004     SmallVector<int,8> ShufMask2(NumElems, -1);
15005     for (unsigned i = 0; i != NumElems/2; ++i)
15006       ShufMask2[i] = i + NumElems/2;
15007
15008     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15009                                         &ShufMask2[0]);
15010
15011     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15012                                   VT.getVectorNumElements()/2);
15013
15014     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15015     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15016
15017     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15018   }
15019   return SDValue();
15020 }
15021
15022 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15023                                   TargetLowering::DAGCombinerInfo &DCI,
15024                                   const X86Subtarget *Subtarget) {
15025   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15026   //           (and (i32 x86isd::setcc_carry), 1)
15027   // This eliminates the zext. This transformation is necessary because
15028   // ISD::SETCC is always legalized to i8.
15029   DebugLoc dl = N->getDebugLoc();
15030   SDValue N0 = N->getOperand(0);
15031   EVT VT = N->getValueType(0);
15032   EVT OpVT = N0.getValueType();
15033
15034   if (N0.getOpcode() == ISD::AND &&
15035       N0.hasOneUse() &&
15036       N0.getOperand(0).hasOneUse()) {
15037     SDValue N00 = N0.getOperand(0);
15038     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15039       return SDValue();
15040     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15041     if (!C || C->getZExtValue() != 1)
15042       return SDValue();
15043     return DAG.getNode(ISD::AND, dl, VT,
15044                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15045                                    N00.getOperand(0), N00.getOperand(1)),
15046                        DAG.getConstant(1, VT));
15047   }
15048
15049   // Optimize vectors in AVX mode:
15050   //
15051   //   v8i16 -> v8i32
15052   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15053   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15054   //   Concat upper and lower parts.
15055   //
15056   //   v4i32 -> v4i64
15057   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15058   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15059   //   Concat upper and lower parts.
15060   //
15061   if (!DCI.isBeforeLegalizeOps())
15062     return SDValue();
15063
15064   if (!Subtarget->hasAVX())
15065     return SDValue();
15066
15067   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15068       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15069
15070     if (Subtarget->hasAVX2())
15071       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15072
15073     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15074     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15075     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15076
15077     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15078                                VT.getVectorNumElements()/2);
15079
15080     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15081     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15082
15083     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15084   }
15085
15086   return SDValue();
15087 }
15088
15089 // Optimize x == -y --> x+y == 0
15090 //          x != -y --> x+y != 0
15091 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15092   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15093   SDValue LHS = N->getOperand(0);
15094   SDValue RHS = N->getOperand(1); 
15095
15096   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15097     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15098       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15099         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15100                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15101         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15102                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15103       }
15104   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15105     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15106       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15107         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15108                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15109         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15110                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15111       }
15112   return SDValue();
15113 }
15114
15115 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15116 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15117   unsigned X86CC = N->getConstantOperandVal(0);
15118   SDValue EFLAG = N->getOperand(1);
15119   DebugLoc DL = N->getDebugLoc();
15120
15121   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15122   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15123   // cases.
15124   if (X86CC == X86::COND_B)
15125     return DAG.getNode(ISD::AND, DL, MVT::i8,
15126                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15127                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
15128                        DAG.getConstant(1, MVT::i8));
15129
15130   return SDValue();
15131 }
15132
15133 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15134   SDValue Op0 = N->getOperand(0);
15135   EVT InVT = Op0->getValueType(0);
15136
15137   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15138   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15139     DebugLoc dl = N->getDebugLoc();
15140     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15141     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15142     // Notice that we use SINT_TO_FP because we know that the high bits
15143     // are zero and SINT_TO_FP is better supported by the hardware.
15144     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15145   }
15146
15147   return SDValue();
15148 }
15149
15150 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15151                                         const X86TargetLowering *XTLI) {
15152   SDValue Op0 = N->getOperand(0);
15153   EVT InVT = Op0->getValueType(0);
15154
15155   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15156   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15157     DebugLoc dl = N->getDebugLoc();
15158     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15159     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15160     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15161   }
15162
15163   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15164   // a 32-bit target where SSE doesn't support i64->FP operations.
15165   if (Op0.getOpcode() == ISD::LOAD) {
15166     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15167     EVT VT = Ld->getValueType(0);
15168     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15169         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15170         !XTLI->getSubtarget()->is64Bit() &&
15171         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15172       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15173                                           Ld->getChain(), Op0, DAG);
15174       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15175       return FILDChain;
15176     }
15177   }
15178   return SDValue();
15179 }
15180
15181 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15182   EVT VT = N->getValueType(0);
15183
15184   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15185   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15186     DebugLoc dl = N->getDebugLoc();
15187     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15188     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15189     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15190   }
15191
15192   return SDValue();
15193 }
15194
15195 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15196 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15197                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15198   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15199   // the result is either zero or one (depending on the input carry bit).
15200   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15201   if (X86::isZeroNode(N->getOperand(0)) &&
15202       X86::isZeroNode(N->getOperand(1)) &&
15203       // We don't have a good way to replace an EFLAGS use, so only do this when
15204       // dead right now.
15205       SDValue(N, 1).use_empty()) {
15206     DebugLoc DL = N->getDebugLoc();
15207     EVT VT = N->getValueType(0);
15208     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15209     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15210                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15211                                            DAG.getConstant(X86::COND_B,MVT::i8),
15212                                            N->getOperand(2)),
15213                                DAG.getConstant(1, VT));
15214     return DCI.CombineTo(N, Res1, CarryOut);
15215   }
15216
15217   return SDValue();
15218 }
15219
15220 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15221 //      (add Y, (setne X, 0)) -> sbb -1, Y
15222 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15223 //      (sub (setne X, 0), Y) -> adc -1, Y
15224 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15225   DebugLoc DL = N->getDebugLoc();
15226
15227   // Look through ZExts.
15228   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15229   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15230     return SDValue();
15231
15232   SDValue SetCC = Ext.getOperand(0);
15233   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15234     return SDValue();
15235
15236   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15237   if (CC != X86::COND_E && CC != X86::COND_NE)
15238     return SDValue();
15239
15240   SDValue Cmp = SetCC.getOperand(1);
15241   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15242       !X86::isZeroNode(Cmp.getOperand(1)) ||
15243       !Cmp.getOperand(0).getValueType().isInteger())
15244     return SDValue();
15245
15246   SDValue CmpOp0 = Cmp.getOperand(0);
15247   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15248                                DAG.getConstant(1, CmpOp0.getValueType()));
15249
15250   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15251   if (CC == X86::COND_NE)
15252     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15253                        DL, OtherVal.getValueType(), OtherVal,
15254                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15255   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15256                      DL, OtherVal.getValueType(), OtherVal,
15257                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15258 }
15259
15260 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15261 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15262                                  const X86Subtarget *Subtarget) {
15263   EVT VT = N->getValueType(0);
15264   SDValue Op0 = N->getOperand(0);
15265   SDValue Op1 = N->getOperand(1);
15266
15267   // Try to synthesize horizontal adds from adds of shuffles.
15268   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15269        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15270       isHorizontalBinOp(Op0, Op1, true))
15271     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15272
15273   return OptimizeConditionalInDecrement(N, DAG);
15274 }
15275
15276 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15277                                  const X86Subtarget *Subtarget) {
15278   SDValue Op0 = N->getOperand(0);
15279   SDValue Op1 = N->getOperand(1);
15280
15281   // X86 can't encode an immediate LHS of a sub. See if we can push the
15282   // negation into a preceding instruction.
15283   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15284     // If the RHS of the sub is a XOR with one use and a constant, invert the
15285     // immediate. Then add one to the LHS of the sub so we can turn
15286     // X-Y -> X+~Y+1, saving one register.
15287     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15288         isa<ConstantSDNode>(Op1.getOperand(1))) {
15289       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15290       EVT VT = Op0.getValueType();
15291       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15292                                    Op1.getOperand(0),
15293                                    DAG.getConstant(~XorC, VT));
15294       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15295                          DAG.getConstant(C->getAPIntValue()+1, VT));
15296     }
15297   }
15298
15299   // Try to synthesize horizontal adds from adds of shuffles.
15300   EVT VT = N->getValueType(0);
15301   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15302        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15303       isHorizontalBinOp(Op0, Op1, true))
15304     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15305
15306   return OptimizeConditionalInDecrement(N, DAG);
15307 }
15308
15309 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15310                                              DAGCombinerInfo &DCI) const {
15311   SelectionDAG &DAG = DCI.DAG;
15312   switch (N->getOpcode()) {
15313   default: break;
15314   case ISD::EXTRACT_VECTOR_ELT:
15315     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15316   case ISD::VSELECT:
15317   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15318   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
15319   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
15320   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
15321   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
15322   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
15323   case ISD::SHL:
15324   case ISD::SRA:
15325   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
15326   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
15327   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
15328   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
15329   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
15330   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
15331   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
15332   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
15333   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
15334   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
15335   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
15336   case X86ISD::FXOR:
15337   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
15338   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
15339   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
15340   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
15341   case ISD::ANY_EXTEND:
15342   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
15343   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
15344   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
15345   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
15346   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
15347   case X86ISD::SHUFP:       // Handle all target specific shuffles
15348   case X86ISD::PALIGN:
15349   case X86ISD::UNPCKH:
15350   case X86ISD::UNPCKL:
15351   case X86ISD::MOVHLPS:
15352   case X86ISD::MOVLHPS:
15353   case X86ISD::PSHUFD:
15354   case X86ISD::PSHUFHW:
15355   case X86ISD::PSHUFLW:
15356   case X86ISD::MOVSS:
15357   case X86ISD::MOVSD:
15358   case X86ISD::VPERMILP:
15359   case X86ISD::VPERM2X128:
15360   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
15361   }
15362
15363   return SDValue();
15364 }
15365
15366 /// isTypeDesirableForOp - Return true if the target has native support for
15367 /// the specified value type and it is 'desirable' to use the type for the
15368 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
15369 /// instruction encodings are longer and some i16 instructions are slow.
15370 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
15371   if (!isTypeLegal(VT))
15372     return false;
15373   if (VT != MVT::i16)
15374     return true;
15375
15376   switch (Opc) {
15377   default:
15378     return true;
15379   case ISD::LOAD:
15380   case ISD::SIGN_EXTEND:
15381   case ISD::ZERO_EXTEND:
15382   case ISD::ANY_EXTEND:
15383   case ISD::SHL:
15384   case ISD::SRL:
15385   case ISD::SUB:
15386   case ISD::ADD:
15387   case ISD::MUL:
15388   case ISD::AND:
15389   case ISD::OR:
15390   case ISD::XOR:
15391     return false;
15392   }
15393 }
15394
15395 /// IsDesirableToPromoteOp - This method query the target whether it is
15396 /// beneficial for dag combiner to promote the specified node. If true, it
15397 /// should return the desired promotion type by reference.
15398 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
15399   EVT VT = Op.getValueType();
15400   if (VT != MVT::i16)
15401     return false;
15402
15403   bool Promote = false;
15404   bool Commute = false;
15405   switch (Op.getOpcode()) {
15406   default: break;
15407   case ISD::LOAD: {
15408     LoadSDNode *LD = cast<LoadSDNode>(Op);
15409     // If the non-extending load has a single use and it's not live out, then it
15410     // might be folded.
15411     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
15412                                                      Op.hasOneUse()*/) {
15413       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15414              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
15415         // The only case where we'd want to promote LOAD (rather then it being
15416         // promoted as an operand is when it's only use is liveout.
15417         if (UI->getOpcode() != ISD::CopyToReg)
15418           return false;
15419       }
15420     }
15421     Promote = true;
15422     break;
15423   }
15424   case ISD::SIGN_EXTEND:
15425   case ISD::ZERO_EXTEND:
15426   case ISD::ANY_EXTEND:
15427     Promote = true;
15428     break;
15429   case ISD::SHL:
15430   case ISD::SRL: {
15431     SDValue N0 = Op.getOperand(0);
15432     // Look out for (store (shl (load), x)).
15433     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15434       return false;
15435     Promote = true;
15436     break;
15437   }
15438   case ISD::ADD:
15439   case ISD::MUL:
15440   case ISD::AND:
15441   case ISD::OR:
15442   case ISD::XOR:
15443     Commute = true;
15444     // fallthrough
15445   case ISD::SUB: {
15446     SDValue N0 = Op.getOperand(0);
15447     SDValue N1 = Op.getOperand(1);
15448     if (!Commute && MayFoldLoad(N1))
15449       return false;
15450     // Avoid disabling potential load folding opportunities.
15451     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15452       return false;
15453     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15454       return false;
15455     Promote = true;
15456   }
15457   }
15458
15459   PVT = MVT::i32;
15460   return Promote;
15461 }
15462
15463 //===----------------------------------------------------------------------===//
15464 //                           X86 Inline Assembly Support
15465 //===----------------------------------------------------------------------===//
15466
15467 namespace {
15468   // Helper to match a string separated by whitespace.
15469   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15470     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15471
15472     for (unsigned i = 0, e = args.size(); i != e; ++i) {
15473       StringRef piece(*args[i]);
15474       if (!s.startswith(piece)) // Check if the piece matches.
15475         return false;
15476
15477       s = s.substr(piece.size());
15478       StringRef::size_type pos = s.find_first_not_of(" \t");
15479       if (pos == 0) // We matched a prefix.
15480         return false;
15481
15482       s = s.substr(pos);
15483     }
15484
15485     return s.empty();
15486   }
15487   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15488 }
15489
15490 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15491   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15492
15493   std::string AsmStr = IA->getAsmString();
15494
15495   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15496   if (!Ty || Ty->getBitWidth() % 16 != 0)
15497     return false;
15498
15499   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15500   SmallVector<StringRef, 4> AsmPieces;
15501   SplitString(AsmStr, AsmPieces, ";\n");
15502
15503   switch (AsmPieces.size()) {
15504   default: return false;
15505   case 1:
15506     // FIXME: this should verify that we are targeting a 486 or better.  If not,
15507     // we will turn this bswap into something that will be lowered to logical
15508     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
15509     // lower so don't worry about this.
15510     // bswap $0
15511     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15512         matchAsm(AsmPieces[0], "bswapl", "$0") ||
15513         matchAsm(AsmPieces[0], "bswapq", "$0") ||
15514         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15515         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15516         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15517       // No need to check constraints, nothing other than the equivalent of
15518       // "=r,0" would be valid here.
15519       return IntrinsicLowering::LowerToByteSwap(CI);
15520     }
15521
15522     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15523     if (CI->getType()->isIntegerTy(16) &&
15524         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15525         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15526          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15527       AsmPieces.clear();
15528       const std::string &ConstraintsStr = IA->getConstraintString();
15529       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15530       std::sort(AsmPieces.begin(), AsmPieces.end());
15531       if (AsmPieces.size() == 4 &&
15532           AsmPieces[0] == "~{cc}" &&
15533           AsmPieces[1] == "~{dirflag}" &&
15534           AsmPieces[2] == "~{flags}" &&
15535           AsmPieces[3] == "~{fpsr}")
15536       return IntrinsicLowering::LowerToByteSwap(CI);
15537     }
15538     break;
15539   case 3:
15540     if (CI->getType()->isIntegerTy(32) &&
15541         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15542         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15543         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15544         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15545       AsmPieces.clear();
15546       const std::string &ConstraintsStr = IA->getConstraintString();
15547       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15548       std::sort(AsmPieces.begin(), AsmPieces.end());
15549       if (AsmPieces.size() == 4 &&
15550           AsmPieces[0] == "~{cc}" &&
15551           AsmPieces[1] == "~{dirflag}" &&
15552           AsmPieces[2] == "~{flags}" &&
15553           AsmPieces[3] == "~{fpsr}")
15554         return IntrinsicLowering::LowerToByteSwap(CI);
15555     }
15556
15557     if (CI->getType()->isIntegerTy(64)) {
15558       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15559       if (Constraints.size() >= 2 &&
15560           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15561           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15562         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15563         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15564             matchAsm(AsmPieces[1], "bswap", "%edx") &&
15565             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15566           return IntrinsicLowering::LowerToByteSwap(CI);
15567       }
15568     }
15569     break;
15570   }
15571   return false;
15572 }
15573
15574
15575
15576 /// getConstraintType - Given a constraint letter, return the type of
15577 /// constraint it is for this target.
15578 X86TargetLowering::ConstraintType
15579 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15580   if (Constraint.size() == 1) {
15581     switch (Constraint[0]) {
15582     case 'R':
15583     case 'q':
15584     case 'Q':
15585     case 'f':
15586     case 't':
15587     case 'u':
15588     case 'y':
15589     case 'x':
15590     case 'Y':
15591     case 'l':
15592       return C_RegisterClass;
15593     case 'a':
15594     case 'b':
15595     case 'c':
15596     case 'd':
15597     case 'S':
15598     case 'D':
15599     case 'A':
15600       return C_Register;
15601     case 'I':
15602     case 'J':
15603     case 'K':
15604     case 'L':
15605     case 'M':
15606     case 'N':
15607     case 'G':
15608     case 'C':
15609     case 'e':
15610     case 'Z':
15611       return C_Other;
15612     default:
15613       break;
15614     }
15615   }
15616   return TargetLowering::getConstraintType(Constraint);
15617 }
15618
15619 /// Examine constraint type and operand type and determine a weight value.
15620 /// This object must already have been set up with the operand type
15621 /// and the current alternative constraint selected.
15622 TargetLowering::ConstraintWeight
15623   X86TargetLowering::getSingleConstraintMatchWeight(
15624     AsmOperandInfo &info, const char *constraint) const {
15625   ConstraintWeight weight = CW_Invalid;
15626   Value *CallOperandVal = info.CallOperandVal;
15627     // If we don't have a value, we can't do a match,
15628     // but allow it at the lowest weight.
15629   if (CallOperandVal == NULL)
15630     return CW_Default;
15631   Type *type = CallOperandVal->getType();
15632   // Look at the constraint type.
15633   switch (*constraint) {
15634   default:
15635     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15636   case 'R':
15637   case 'q':
15638   case 'Q':
15639   case 'a':
15640   case 'b':
15641   case 'c':
15642   case 'd':
15643   case 'S':
15644   case 'D':
15645   case 'A':
15646     if (CallOperandVal->getType()->isIntegerTy())
15647       weight = CW_SpecificReg;
15648     break;
15649   case 'f':
15650   case 't':
15651   case 'u':
15652       if (type->isFloatingPointTy())
15653         weight = CW_SpecificReg;
15654       break;
15655   case 'y':
15656       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15657         weight = CW_SpecificReg;
15658       break;
15659   case 'x':
15660   case 'Y':
15661     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15662         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15663       weight = CW_Register;
15664     break;
15665   case 'I':
15666     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15667       if (C->getZExtValue() <= 31)
15668         weight = CW_Constant;
15669     }
15670     break;
15671   case 'J':
15672     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15673       if (C->getZExtValue() <= 63)
15674         weight = CW_Constant;
15675     }
15676     break;
15677   case 'K':
15678     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15679       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15680         weight = CW_Constant;
15681     }
15682     break;
15683   case 'L':
15684     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15685       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15686         weight = CW_Constant;
15687     }
15688     break;
15689   case 'M':
15690     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15691       if (C->getZExtValue() <= 3)
15692         weight = CW_Constant;
15693     }
15694     break;
15695   case 'N':
15696     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15697       if (C->getZExtValue() <= 0xff)
15698         weight = CW_Constant;
15699     }
15700     break;
15701   case 'G':
15702   case 'C':
15703     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15704       weight = CW_Constant;
15705     }
15706     break;
15707   case 'e':
15708     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15709       if ((C->getSExtValue() >= -0x80000000LL) &&
15710           (C->getSExtValue() <= 0x7fffffffLL))
15711         weight = CW_Constant;
15712     }
15713     break;
15714   case 'Z':
15715     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15716       if (C->getZExtValue() <= 0xffffffff)
15717         weight = CW_Constant;
15718     }
15719     break;
15720   }
15721   return weight;
15722 }
15723
15724 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15725 /// with another that has more specific requirements based on the type of the
15726 /// corresponding operand.
15727 const char *X86TargetLowering::
15728 LowerXConstraint(EVT ConstraintVT) const {
15729   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15730   // 'f' like normal targets.
15731   if (ConstraintVT.isFloatingPoint()) {
15732     if (Subtarget->hasSSE2())
15733       return "Y";
15734     if (Subtarget->hasSSE1())
15735       return "x";
15736   }
15737
15738   return TargetLowering::LowerXConstraint(ConstraintVT);
15739 }
15740
15741 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15742 /// vector.  If it is invalid, don't add anything to Ops.
15743 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15744                                                      std::string &Constraint,
15745                                                      std::vector<SDValue>&Ops,
15746                                                      SelectionDAG &DAG) const {
15747   SDValue Result(0, 0);
15748
15749   // Only support length 1 constraints for now.
15750   if (Constraint.length() > 1) return;
15751
15752   char ConstraintLetter = Constraint[0];
15753   switch (ConstraintLetter) {
15754   default: break;
15755   case 'I':
15756     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15757       if (C->getZExtValue() <= 31) {
15758         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15759         break;
15760       }
15761     }
15762     return;
15763   case 'J':
15764     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15765       if (C->getZExtValue() <= 63) {
15766         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15767         break;
15768       }
15769     }
15770     return;
15771   case 'K':
15772     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15773       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15774         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15775         break;
15776       }
15777     }
15778     return;
15779   case 'N':
15780     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15781       if (C->getZExtValue() <= 255) {
15782         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15783         break;
15784       }
15785     }
15786     return;
15787   case 'e': {
15788     // 32-bit signed value
15789     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15790       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15791                                            C->getSExtValue())) {
15792         // Widen to 64 bits here to get it sign extended.
15793         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15794         break;
15795       }
15796     // FIXME gcc accepts some relocatable values here too, but only in certain
15797     // memory models; it's complicated.
15798     }
15799     return;
15800   }
15801   case 'Z': {
15802     // 32-bit unsigned value
15803     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15804       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15805                                            C->getZExtValue())) {
15806         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15807         break;
15808       }
15809     }
15810     // FIXME gcc accepts some relocatable values here too, but only in certain
15811     // memory models; it's complicated.
15812     return;
15813   }
15814   case 'i': {
15815     // Literal immediates are always ok.
15816     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15817       // Widen to 64 bits here to get it sign extended.
15818       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15819       break;
15820     }
15821
15822     // In any sort of PIC mode addresses need to be computed at runtime by
15823     // adding in a register or some sort of table lookup.  These can't
15824     // be used as immediates.
15825     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15826       return;
15827
15828     // If we are in non-pic codegen mode, we allow the address of a global (with
15829     // an optional displacement) to be used with 'i'.
15830     GlobalAddressSDNode *GA = 0;
15831     int64_t Offset = 0;
15832
15833     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15834     while (1) {
15835       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15836         Offset += GA->getOffset();
15837         break;
15838       } else if (Op.getOpcode() == ISD::ADD) {
15839         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15840           Offset += C->getZExtValue();
15841           Op = Op.getOperand(0);
15842           continue;
15843         }
15844       } else if (Op.getOpcode() == ISD::SUB) {
15845         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15846           Offset += -C->getZExtValue();
15847           Op = Op.getOperand(0);
15848           continue;
15849         }
15850       }
15851
15852       // Otherwise, this isn't something we can handle, reject it.
15853       return;
15854     }
15855
15856     const GlobalValue *GV = GA->getGlobal();
15857     // If we require an extra load to get this address, as in PIC mode, we
15858     // can't accept it.
15859     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15860                                                         getTargetMachine())))
15861       return;
15862
15863     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15864                                         GA->getValueType(0), Offset);
15865     break;
15866   }
15867   }
15868
15869   if (Result.getNode()) {
15870     Ops.push_back(Result);
15871     return;
15872   }
15873   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15874 }
15875
15876 std::pair<unsigned, const TargetRegisterClass*>
15877 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15878                                                 EVT VT) const {
15879   // First, see if this is a constraint that directly corresponds to an LLVM
15880   // register class.
15881   if (Constraint.size() == 1) {
15882     // GCC Constraint Letters
15883     switch (Constraint[0]) {
15884     default: break;
15885       // TODO: Slight differences here in allocation order and leaving
15886       // RIP in the class. Do they matter any more here than they do
15887       // in the normal allocation?
15888     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15889       if (Subtarget->is64Bit()) {
15890         if (VT == MVT::i32 || VT == MVT::f32)
15891           return std::make_pair(0U, &X86::GR32RegClass);
15892         if (VT == MVT::i16)
15893           return std::make_pair(0U, &X86::GR16RegClass);
15894         if (VT == MVT::i8 || VT == MVT::i1)
15895           return std::make_pair(0U, &X86::GR8RegClass);
15896         if (VT == MVT::i64 || VT == MVT::f64)
15897           return std::make_pair(0U, &X86::GR64RegClass);
15898         break;
15899       }
15900       // 32-bit fallthrough
15901     case 'Q':   // Q_REGS
15902       if (VT == MVT::i32 || VT == MVT::f32)
15903         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
15904       if (VT == MVT::i16)
15905         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
15906       if (VT == MVT::i8 || VT == MVT::i1)
15907         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
15908       if (VT == MVT::i64)
15909         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
15910       break;
15911     case 'r':   // GENERAL_REGS
15912     case 'l':   // INDEX_REGS
15913       if (VT == MVT::i8 || VT == MVT::i1)
15914         return std::make_pair(0U, &X86::GR8RegClass);
15915       if (VT == MVT::i16)
15916         return std::make_pair(0U, &X86::GR16RegClass);
15917       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15918         return std::make_pair(0U, &X86::GR32RegClass);
15919       return std::make_pair(0U, &X86::GR64RegClass);
15920     case 'R':   // LEGACY_REGS
15921       if (VT == MVT::i8 || VT == MVT::i1)
15922         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
15923       if (VT == MVT::i16)
15924         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
15925       if (VT == MVT::i32 || !Subtarget->is64Bit())
15926         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
15927       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
15928     case 'f':  // FP Stack registers.
15929       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15930       // value to the correct fpstack register class.
15931       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15932         return std::make_pair(0U, &X86::RFP32RegClass);
15933       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15934         return std::make_pair(0U, &X86::RFP64RegClass);
15935       return std::make_pair(0U, &X86::RFP80RegClass);
15936     case 'y':   // MMX_REGS if MMX allowed.
15937       if (!Subtarget->hasMMX()) break;
15938       return std::make_pair(0U, &X86::VR64RegClass);
15939     case 'Y':   // SSE_REGS if SSE2 allowed
15940       if (!Subtarget->hasSSE2()) break;
15941       // FALL THROUGH.
15942     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
15943       if (!Subtarget->hasSSE1()) break;
15944
15945       switch (VT.getSimpleVT().SimpleTy) {
15946       default: break;
15947       // Scalar SSE types.
15948       case MVT::f32:
15949       case MVT::i32:
15950         return std::make_pair(0U, &X86::FR32RegClass);
15951       case MVT::f64:
15952       case MVT::i64:
15953         return std::make_pair(0U, &X86::FR64RegClass);
15954       // Vector types.
15955       case MVT::v16i8:
15956       case MVT::v8i16:
15957       case MVT::v4i32:
15958       case MVT::v2i64:
15959       case MVT::v4f32:
15960       case MVT::v2f64:
15961         return std::make_pair(0U, &X86::VR128RegClass);
15962       // AVX types.
15963       case MVT::v32i8:
15964       case MVT::v16i16:
15965       case MVT::v8i32:
15966       case MVT::v4i64:
15967       case MVT::v8f32:
15968       case MVT::v4f64:
15969         return std::make_pair(0U, &X86::VR256RegClass);
15970       }
15971       break;
15972     }
15973   }
15974
15975   // Use the default implementation in TargetLowering to convert the register
15976   // constraint into a member of a register class.
15977   std::pair<unsigned, const TargetRegisterClass*> Res;
15978   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15979
15980   // Not found as a standard register?
15981   if (Res.second == 0) {
15982     // Map st(0) -> st(7) -> ST0
15983     if (Constraint.size() == 7 && Constraint[0] == '{' &&
15984         tolower(Constraint[1]) == 's' &&
15985         tolower(Constraint[2]) == 't' &&
15986         Constraint[3] == '(' &&
15987         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15988         Constraint[5] == ')' &&
15989         Constraint[6] == '}') {
15990
15991       Res.first = X86::ST0+Constraint[4]-'0';
15992       Res.second = &X86::RFP80RegClass;
15993       return Res;
15994     }
15995
15996     // GCC allows "st(0)" to be called just plain "st".
15997     if (StringRef("{st}").equals_lower(Constraint)) {
15998       Res.first = X86::ST0;
15999       Res.second = &X86::RFP80RegClass;
16000       return Res;
16001     }
16002
16003     // flags -> EFLAGS
16004     if (StringRef("{flags}").equals_lower(Constraint)) {
16005       Res.first = X86::EFLAGS;
16006       Res.second = &X86::CCRRegClass;
16007       return Res;
16008     }
16009
16010     // 'A' means EAX + EDX.
16011     if (Constraint == "A") {
16012       Res.first = X86::EAX;
16013       Res.second = &X86::GR32_ADRegClass;
16014       return Res;
16015     }
16016     return Res;
16017   }
16018
16019   // Otherwise, check to see if this is a register class of the wrong value
16020   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16021   // turn into {ax},{dx}.
16022   if (Res.second->hasType(VT))
16023     return Res;   // Correct type already, nothing to do.
16024
16025   // All of the single-register GCC register classes map their values onto
16026   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16027   // really want an 8-bit or 32-bit register, map to the appropriate register
16028   // class and return the appropriate register.
16029   if (Res.second == &X86::GR16RegClass) {
16030     if (VT == MVT::i8) {
16031       unsigned DestReg = 0;
16032       switch (Res.first) {
16033       default: break;
16034       case X86::AX: DestReg = X86::AL; break;
16035       case X86::DX: DestReg = X86::DL; break;
16036       case X86::CX: DestReg = X86::CL; break;
16037       case X86::BX: DestReg = X86::BL; break;
16038       }
16039       if (DestReg) {
16040         Res.first = DestReg;
16041         Res.second = &X86::GR8RegClass;
16042       }
16043     } else if (VT == MVT::i32) {
16044       unsigned DestReg = 0;
16045       switch (Res.first) {
16046       default: break;
16047       case X86::AX: DestReg = X86::EAX; break;
16048       case X86::DX: DestReg = X86::EDX; break;
16049       case X86::CX: DestReg = X86::ECX; break;
16050       case X86::BX: DestReg = X86::EBX; break;
16051       case X86::SI: DestReg = X86::ESI; break;
16052       case X86::DI: DestReg = X86::EDI; break;
16053       case X86::BP: DestReg = X86::EBP; break;
16054       case X86::SP: DestReg = X86::ESP; break;
16055       }
16056       if (DestReg) {
16057         Res.first = DestReg;
16058         Res.second = &X86::GR32RegClass;
16059       }
16060     } else if (VT == MVT::i64) {
16061       unsigned DestReg = 0;
16062       switch (Res.first) {
16063       default: break;
16064       case X86::AX: DestReg = X86::RAX; break;
16065       case X86::DX: DestReg = X86::RDX; break;
16066       case X86::CX: DestReg = X86::RCX; break;
16067       case X86::BX: DestReg = X86::RBX; break;
16068       case X86::SI: DestReg = X86::RSI; break;
16069       case X86::DI: DestReg = X86::RDI; break;
16070       case X86::BP: DestReg = X86::RBP; break;
16071       case X86::SP: DestReg = X86::RSP; break;
16072       }
16073       if (DestReg) {
16074         Res.first = DestReg;
16075         Res.second = &X86::GR64RegClass;
16076       }
16077     }
16078   } else if (Res.second == &X86::FR32RegClass ||
16079              Res.second == &X86::FR64RegClass ||
16080              Res.second == &X86::VR128RegClass) {
16081     // Handle references to XMM physical registers that got mapped into the
16082     // wrong class.  This can happen with constraints like {xmm0} where the
16083     // target independent register mapper will just pick the first match it can
16084     // find, ignoring the required type.
16085
16086     if (VT == MVT::f32 || VT == MVT::i32)
16087       Res.second = &X86::FR32RegClass;
16088     else if (VT == MVT::f64 || VT == MVT::i64)
16089       Res.second = &X86::FR64RegClass;
16090     else if (X86::VR128RegClass.hasType(VT))
16091       Res.second = &X86::VR128RegClass;
16092     else if (X86::VR256RegClass.hasType(VT))
16093       Res.second = &X86::VR256RegClass;
16094   }
16095
16096   return Res;
16097 }