When ext-loading and trunc-storing vectors to memory, on x86 32bit systems, allow...
[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 X86_64MachoTargetObjectFile();
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   if (Subtarget->isPICStyleGOT()) {
2308     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2309     // GOT pointer.
2310     if (!isTailCall) {
2311       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2312                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2313     } else {
2314       // If we are tail calling and generating PIC/GOT style code load the
2315       // address of the callee into ECX. The value in ecx is used as target of
2316       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2317       // for tail calls on PIC/GOT architectures. Normally we would just put the
2318       // address of GOT into ebx and then call target@PLT. But for tail calls
2319       // ebx would be restored (since ebx is callee saved) before jumping to the
2320       // target@PLT.
2321
2322       // Note: The actual moving to ECX is done further down.
2323       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2324       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2325           !G->getGlobal()->hasProtectedVisibility())
2326         Callee = LowerGlobalAddress(Callee, DAG);
2327       else if (isa<ExternalSymbolSDNode>(Callee))
2328         Callee = LowerExternalSymbol(Callee, DAG);
2329     }
2330   }
2331
2332   if (Is64Bit && isVarArg && !IsWin64) {
2333     // From AMD64 ABI document:
2334     // For calls that may call functions that use varargs or stdargs
2335     // (prototype-less calls or calls to functions containing ellipsis (...) in
2336     // the declaration) %al is used as hidden argument to specify the number
2337     // of SSE registers used. The contents of %al do not need to match exactly
2338     // the number of registers, but must be an ubound on the number of SSE
2339     // registers used and is in the range 0 - 8 inclusive.
2340
2341     // Count the number of XMM registers allocated.
2342     static const uint16_t XMMArgRegs[] = {
2343       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2344       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2345     };
2346     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2347     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2348            && "SSE registers cannot be used when SSE is disabled");
2349
2350     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2351                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2352   }
2353
2354   // For tail calls lower the arguments to the 'real' stack slot.
2355   if (isTailCall) {
2356     // Force all the incoming stack arguments to be loaded from the stack
2357     // before any new outgoing arguments are stored to the stack, because the
2358     // outgoing stack slots may alias the incoming argument stack slots, and
2359     // the alias isn't otherwise explicit. This is slightly more conservative
2360     // than necessary, because it means that each store effectively depends
2361     // on every argument instead of just those arguments it would clobber.
2362     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2363
2364     SmallVector<SDValue, 8> MemOpChains2;
2365     SDValue FIN;
2366     int FI = 0;
2367     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2368       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2369         CCValAssign &VA = ArgLocs[i];
2370         if (VA.isRegLoc())
2371           continue;
2372         assert(VA.isMemLoc());
2373         SDValue Arg = OutVals[i];
2374         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2375         // Create frame index.
2376         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2377         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2378         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2379         FIN = DAG.getFrameIndex(FI, getPointerTy());
2380
2381         if (Flags.isByVal()) {
2382           // Copy relative to framepointer.
2383           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2384           if (StackPtr.getNode() == 0)
2385             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2386                                           getPointerTy());
2387           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2388
2389           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2390                                                            ArgChain,
2391                                                            Flags, DAG, dl));
2392         } else {
2393           // Store relative to framepointer.
2394           MemOpChains2.push_back(
2395             DAG.getStore(ArgChain, dl, Arg, FIN,
2396                          MachinePointerInfo::getFixedStack(FI),
2397                          false, false, 0));
2398         }
2399       }
2400     }
2401
2402     if (!MemOpChains2.empty())
2403       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2404                           &MemOpChains2[0], MemOpChains2.size());
2405
2406     // Store the return address to the appropriate stack slot.
2407     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2408                                      FPDiff, dl);
2409   }
2410
2411   // Build a sequence of copy-to-reg nodes chained together with token chain
2412   // and flag operands which copy the outgoing args into registers.
2413   SDValue InFlag;
2414   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2415     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2416                              RegsToPass[i].second, InFlag);
2417     InFlag = Chain.getValue(1);
2418   }
2419
2420   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2421     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2422     // In the 64-bit large code model, we have to make all calls
2423     // through a register, since the call instruction's 32-bit
2424     // pc-relative offset may not be large enough to hold the whole
2425     // address.
2426   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2427     // If the callee is a GlobalAddress node (quite common, every direct call
2428     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2429     // it.
2430
2431     // We should use extra load for direct calls to dllimported functions in
2432     // non-JIT mode.
2433     const GlobalValue *GV = G->getGlobal();
2434     if (!GV->hasDLLImportLinkage()) {
2435       unsigned char OpFlags = 0;
2436       bool ExtraLoad = false;
2437       unsigned WrapperKind = ISD::DELETED_NODE;
2438
2439       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2440       // external symbols most go through the PLT in PIC mode.  If the symbol
2441       // has hidden or protected visibility, or if it is static or local, then
2442       // we don't need to use the PLT - we can directly call it.
2443       if (Subtarget->isTargetELF() &&
2444           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2445           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2446         OpFlags = X86II::MO_PLT;
2447       } else if (Subtarget->isPICStyleStubAny() &&
2448                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2449                  (!Subtarget->getTargetTriple().isMacOSX() ||
2450                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2451         // PC-relative references to external symbols should go through $stub,
2452         // unless we're building with the leopard linker or later, which
2453         // automatically synthesizes these stubs.
2454         OpFlags = X86II::MO_DARWIN_STUB;
2455       } else if (Subtarget->isPICStyleRIPRel() &&
2456                  isa<Function>(GV) &&
2457                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2458         // If the function is marked as non-lazy, generate an indirect call
2459         // which loads from the GOT directly. This avoids runtime overhead
2460         // at the cost of eager binding (and one extra byte of encoding).
2461         OpFlags = X86II::MO_GOTPCREL;
2462         WrapperKind = X86ISD::WrapperRIP;
2463         ExtraLoad = true;
2464       }
2465
2466       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2467                                           G->getOffset(), OpFlags);
2468
2469       // Add a wrapper if needed.
2470       if (WrapperKind != ISD::DELETED_NODE)
2471         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2472       // Add extra indirection if needed.
2473       if (ExtraLoad)
2474         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2475                              MachinePointerInfo::getGOT(),
2476                              false, false, false, 0);
2477     }
2478   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2479     unsigned char OpFlags = 0;
2480
2481     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2482     // external symbols should go through the PLT.
2483     if (Subtarget->isTargetELF() &&
2484         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2485       OpFlags = X86II::MO_PLT;
2486     } else if (Subtarget->isPICStyleStubAny() &&
2487                (!Subtarget->getTargetTriple().isMacOSX() ||
2488                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2489       // PC-relative references to external symbols should go through $stub,
2490       // unless we're building with the leopard linker or later, which
2491       // automatically synthesizes these stubs.
2492       OpFlags = X86II::MO_DARWIN_STUB;
2493     }
2494
2495     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2496                                          OpFlags);
2497   }
2498
2499   // Returns a chain & a flag for retval copy to use.
2500   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2501   SmallVector<SDValue, 8> Ops;
2502
2503   if (!IsSibcall && isTailCall) {
2504     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2505                            DAG.getIntPtrConstant(0, true), InFlag);
2506     InFlag = Chain.getValue(1);
2507   }
2508
2509   Ops.push_back(Chain);
2510   Ops.push_back(Callee);
2511
2512   if (isTailCall)
2513     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2514
2515   // Add argument registers to the end of the list so that they are known live
2516   // into the call.
2517   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2518     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2519                                   RegsToPass[i].second.getValueType()));
2520
2521   // Add a register mask operand representing the call-preserved registers.
2522   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2523   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2524   assert(Mask && "Missing call preserved mask for calling convention");
2525   Ops.push_back(DAG.getRegisterMask(Mask));
2526
2527   if (InFlag.getNode())
2528     Ops.push_back(InFlag);
2529
2530   if (isTailCall) {
2531     // We used to do:
2532     //// If this is the first return lowered for this function, add the regs
2533     //// to the liveout set for the function.
2534     // This isn't right, although it's probably harmless on x86; liveouts
2535     // should be computed from returns not tail calls.  Consider a void
2536     // function making a tail call to a function returning int.
2537     return DAG.getNode(X86ISD::TC_RETURN, dl,
2538                        NodeTys, &Ops[0], Ops.size());
2539   }
2540
2541   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2542   InFlag = Chain.getValue(1);
2543
2544   // Create the CALLSEQ_END node.
2545   unsigned NumBytesForCalleeToPush;
2546   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2547                        getTargetMachine().Options.GuaranteedTailCallOpt))
2548     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2549   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2550            IsStructRet)
2551     // If this is a call to a struct-return function, the callee
2552     // pops the hidden struct pointer, so we have to push it back.
2553     // This is common for Darwin/X86, Linux & Mingw32 targets.
2554     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2555     NumBytesForCalleeToPush = 4;
2556   else
2557     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2558
2559   // Returns a flag for retval copy to use.
2560   if (!IsSibcall) {
2561     Chain = DAG.getCALLSEQ_END(Chain,
2562                                DAG.getIntPtrConstant(NumBytes, true),
2563                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2564                                                      true),
2565                                InFlag);
2566     InFlag = Chain.getValue(1);
2567   }
2568
2569   // Handle result values, copying them out of physregs into vregs that we
2570   // return.
2571   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2572                          Ins, dl, DAG, InVals);
2573 }
2574
2575
2576 //===----------------------------------------------------------------------===//
2577 //                Fast Calling Convention (tail call) implementation
2578 //===----------------------------------------------------------------------===//
2579
2580 //  Like std call, callee cleans arguments, convention except that ECX is
2581 //  reserved for storing the tail called function address. Only 2 registers are
2582 //  free for argument passing (inreg). Tail call optimization is performed
2583 //  provided:
2584 //                * tailcallopt is enabled
2585 //                * caller/callee are fastcc
2586 //  On X86_64 architecture with GOT-style position independent code only local
2587 //  (within module) calls are supported at the moment.
2588 //  To keep the stack aligned according to platform abi the function
2589 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2590 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2591 //  If a tail called function callee has more arguments than the caller the
2592 //  caller needs to make sure that there is room to move the RETADDR to. This is
2593 //  achieved by reserving an area the size of the argument delta right after the
2594 //  original REtADDR, but before the saved framepointer or the spilled registers
2595 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2596 //  stack layout:
2597 //    arg1
2598 //    arg2
2599 //    RETADDR
2600 //    [ new RETADDR
2601 //      move area ]
2602 //    (possible EBP)
2603 //    ESI
2604 //    EDI
2605 //    local1 ..
2606
2607 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2608 /// for a 16 byte align requirement.
2609 unsigned
2610 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2611                                                SelectionDAG& DAG) const {
2612   MachineFunction &MF = DAG.getMachineFunction();
2613   const TargetMachine &TM = MF.getTarget();
2614   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2615   unsigned StackAlignment = TFI.getStackAlignment();
2616   uint64_t AlignMask = StackAlignment - 1;
2617   int64_t Offset = StackSize;
2618   uint64_t SlotSize = TD->getPointerSize();
2619   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2620     // Number smaller than 12 so just add the difference.
2621     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2622   } else {
2623     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2624     Offset = ((~AlignMask) & Offset) + StackAlignment +
2625       (StackAlignment-SlotSize);
2626   }
2627   return Offset;
2628 }
2629
2630 /// MatchingStackOffset - Return true if the given stack call argument is
2631 /// already available in the same position (relatively) of the caller's
2632 /// incoming argument stack.
2633 static
2634 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2635                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2636                          const X86InstrInfo *TII) {
2637   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2638   int FI = INT_MAX;
2639   if (Arg.getOpcode() == ISD::CopyFromReg) {
2640     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2641     if (!TargetRegisterInfo::isVirtualRegister(VR))
2642       return false;
2643     MachineInstr *Def = MRI->getVRegDef(VR);
2644     if (!Def)
2645       return false;
2646     if (!Flags.isByVal()) {
2647       if (!TII->isLoadFromStackSlot(Def, FI))
2648         return false;
2649     } else {
2650       unsigned Opcode = Def->getOpcode();
2651       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2652           Def->getOperand(1).isFI()) {
2653         FI = Def->getOperand(1).getIndex();
2654         Bytes = Flags.getByValSize();
2655       } else
2656         return false;
2657     }
2658   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2659     if (Flags.isByVal())
2660       // ByVal argument is passed in as a pointer but it's now being
2661       // dereferenced. e.g.
2662       // define @foo(%struct.X* %A) {
2663       //   tail call @bar(%struct.X* byval %A)
2664       // }
2665       return false;
2666     SDValue Ptr = Ld->getBasePtr();
2667     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2668     if (!FINode)
2669       return false;
2670     FI = FINode->getIndex();
2671   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2672     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2673     FI = FINode->getIndex();
2674     Bytes = Flags.getByValSize();
2675   } else
2676     return false;
2677
2678   assert(FI != INT_MAX);
2679   if (!MFI->isFixedObjectIndex(FI))
2680     return false;
2681   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2682 }
2683
2684 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2685 /// for tail call optimization. Targets which want to do tail call
2686 /// optimization should implement this function.
2687 bool
2688 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2689                                                      CallingConv::ID CalleeCC,
2690                                                      bool isVarArg,
2691                                                      bool isCalleeStructRet,
2692                                                      bool isCallerStructRet,
2693                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2694                                     const SmallVectorImpl<SDValue> &OutVals,
2695                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2696                                                      SelectionDAG& DAG) const {
2697   if (!IsTailCallConvention(CalleeCC) &&
2698       CalleeCC != CallingConv::C)
2699     return false;
2700
2701   // If -tailcallopt is specified, make fastcc functions tail-callable.
2702   const MachineFunction &MF = DAG.getMachineFunction();
2703   const Function *CallerF = DAG.getMachineFunction().getFunction();
2704   CallingConv::ID CallerCC = CallerF->getCallingConv();
2705   bool CCMatch = CallerCC == CalleeCC;
2706
2707   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2708     if (IsTailCallConvention(CalleeCC) && CCMatch)
2709       return true;
2710     return false;
2711   }
2712
2713   // Look for obvious safe cases to perform tail call optimization that do not
2714   // require ABI changes. This is what gcc calls sibcall.
2715
2716   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2717   // emit a special epilogue.
2718   if (RegInfo->needsStackRealignment(MF))
2719     return false;
2720
2721   // Also avoid sibcall optimization if either caller or callee uses struct
2722   // return semantics.
2723   if (isCalleeStructRet || isCallerStructRet)
2724     return false;
2725
2726   // An stdcall caller is expected to clean up its arguments; the callee
2727   // isn't going to do that.
2728   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2729     return false;
2730
2731   // Do not sibcall optimize vararg calls unless all arguments are passed via
2732   // registers.
2733   if (isVarArg && !Outs.empty()) {
2734
2735     // Optimizing for varargs on Win64 is unlikely to be safe without
2736     // additional testing.
2737     if (Subtarget->isTargetWin64())
2738       return false;
2739
2740     SmallVector<CCValAssign, 16> ArgLocs;
2741     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2742                    getTargetMachine(), ArgLocs, *DAG.getContext());
2743
2744     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2745     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2746       if (!ArgLocs[i].isRegLoc())
2747         return false;
2748   }
2749
2750   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2751   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2752   // this into a sibcall.
2753   bool Unused = false;
2754   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2755     if (!Ins[i].Used) {
2756       Unused = true;
2757       break;
2758     }
2759   }
2760   if (Unused) {
2761     SmallVector<CCValAssign, 16> RVLocs;
2762     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2763                    getTargetMachine(), RVLocs, *DAG.getContext());
2764     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2765     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2766       CCValAssign &VA = RVLocs[i];
2767       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2768         return false;
2769     }
2770   }
2771
2772   // If the calling conventions do not match, then we'd better make sure the
2773   // results are returned in the same way as what the caller expects.
2774   if (!CCMatch) {
2775     SmallVector<CCValAssign, 16> RVLocs1;
2776     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2777                     getTargetMachine(), RVLocs1, *DAG.getContext());
2778     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2779
2780     SmallVector<CCValAssign, 16> RVLocs2;
2781     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2782                     getTargetMachine(), RVLocs2, *DAG.getContext());
2783     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2784
2785     if (RVLocs1.size() != RVLocs2.size())
2786       return false;
2787     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2788       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2789         return false;
2790       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2791         return false;
2792       if (RVLocs1[i].isRegLoc()) {
2793         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2794           return false;
2795       } else {
2796         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2797           return false;
2798       }
2799     }
2800   }
2801
2802   // If the callee takes no arguments then go on to check the results of the
2803   // call.
2804   if (!Outs.empty()) {
2805     // Check if stack adjustment is needed. For now, do not do this if any
2806     // argument is passed on the stack.
2807     SmallVector<CCValAssign, 16> ArgLocs;
2808     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2809                    getTargetMachine(), ArgLocs, *DAG.getContext());
2810
2811     // Allocate shadow area for Win64
2812     if (Subtarget->isTargetWin64()) {
2813       CCInfo.AllocateStack(32, 8);
2814     }
2815
2816     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2817     if (CCInfo.getNextStackOffset()) {
2818       MachineFunction &MF = DAG.getMachineFunction();
2819       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2820         return false;
2821
2822       // Check if the arguments are already laid out in the right way as
2823       // the caller's fixed stack objects.
2824       MachineFrameInfo *MFI = MF.getFrameInfo();
2825       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2826       const X86InstrInfo *TII =
2827         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2828       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2829         CCValAssign &VA = ArgLocs[i];
2830         SDValue Arg = OutVals[i];
2831         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2832         if (VA.getLocInfo() == CCValAssign::Indirect)
2833           return false;
2834         if (!VA.isRegLoc()) {
2835           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2836                                    MFI, MRI, TII))
2837             return false;
2838         }
2839       }
2840     }
2841
2842     // If the tailcall address may be in a register, then make sure it's
2843     // possible to register allocate for it. In 32-bit, the call address can
2844     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2845     // callee-saved registers are restored. These happen to be the same
2846     // registers used to pass 'inreg' arguments so watch out for those.
2847     if (!Subtarget->is64Bit() &&
2848         !isa<GlobalAddressSDNode>(Callee) &&
2849         !isa<ExternalSymbolSDNode>(Callee)) {
2850       unsigned NumInRegs = 0;
2851       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2852         CCValAssign &VA = ArgLocs[i];
2853         if (!VA.isRegLoc())
2854           continue;
2855         unsigned Reg = VA.getLocReg();
2856         switch (Reg) {
2857         default: break;
2858         case X86::EAX: case X86::EDX: case X86::ECX:
2859           if (++NumInRegs == 3)
2860             return false;
2861           break;
2862         }
2863       }
2864     }
2865   }
2866
2867   return true;
2868 }
2869
2870 FastISel *
2871 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2872   return X86::createFastISel(funcInfo);
2873 }
2874
2875
2876 //===----------------------------------------------------------------------===//
2877 //                           Other Lowering Hooks
2878 //===----------------------------------------------------------------------===//
2879
2880 static bool MayFoldLoad(SDValue Op) {
2881   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2882 }
2883
2884 static bool MayFoldIntoStore(SDValue Op) {
2885   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2886 }
2887
2888 static bool isTargetShuffle(unsigned Opcode) {
2889   switch(Opcode) {
2890   default: return false;
2891   case X86ISD::PSHUFD:
2892   case X86ISD::PSHUFHW:
2893   case X86ISD::PSHUFLW:
2894   case X86ISD::SHUFP:
2895   case X86ISD::PALIGN:
2896   case X86ISD::MOVLHPS:
2897   case X86ISD::MOVLHPD:
2898   case X86ISD::MOVHLPS:
2899   case X86ISD::MOVLPS:
2900   case X86ISD::MOVLPD:
2901   case X86ISD::MOVSHDUP:
2902   case X86ISD::MOVSLDUP:
2903   case X86ISD::MOVDDUP:
2904   case X86ISD::MOVSS:
2905   case X86ISD::MOVSD:
2906   case X86ISD::UNPCKL:
2907   case X86ISD::UNPCKH:
2908   case X86ISD::VPERMILP:
2909   case X86ISD::VPERM2X128:
2910   case X86ISD::VPERMI:
2911     return true;
2912   }
2913 }
2914
2915 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2916                                     SDValue V1, SelectionDAG &DAG) {
2917   switch(Opc) {
2918   default: llvm_unreachable("Unknown x86 shuffle node");
2919   case X86ISD::MOVSHDUP:
2920   case X86ISD::MOVSLDUP:
2921   case X86ISD::MOVDDUP:
2922     return DAG.getNode(Opc, dl, VT, V1);
2923   }
2924 }
2925
2926 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2927                                     SDValue V1, unsigned TargetMask,
2928                                     SelectionDAG &DAG) {
2929   switch(Opc) {
2930   default: llvm_unreachable("Unknown x86 shuffle node");
2931   case X86ISD::PSHUFD:
2932   case X86ISD::PSHUFHW:
2933   case X86ISD::PSHUFLW:
2934   case X86ISD::VPERMILP:
2935   case X86ISD::VPERMI:
2936     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2937   }
2938 }
2939
2940 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2941                                     SDValue V1, SDValue V2, unsigned TargetMask,
2942                                     SelectionDAG &DAG) {
2943   switch(Opc) {
2944   default: llvm_unreachable("Unknown x86 shuffle node");
2945   case X86ISD::PALIGN:
2946   case X86ISD::SHUFP:
2947   case X86ISD::VPERM2X128:
2948     return DAG.getNode(Opc, dl, VT, V1, V2,
2949                        DAG.getConstant(TargetMask, MVT::i8));
2950   }
2951 }
2952
2953 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2954                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2955   switch(Opc) {
2956   default: llvm_unreachable("Unknown x86 shuffle node");
2957   case X86ISD::MOVLHPS:
2958   case X86ISD::MOVLHPD:
2959   case X86ISD::MOVHLPS:
2960   case X86ISD::MOVLPS:
2961   case X86ISD::MOVLPD:
2962   case X86ISD::MOVSS:
2963   case X86ISD::MOVSD:
2964   case X86ISD::UNPCKL:
2965   case X86ISD::UNPCKH:
2966     return DAG.getNode(Opc, dl, VT, V1, V2);
2967   }
2968 }
2969
2970 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2971   MachineFunction &MF = DAG.getMachineFunction();
2972   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2973   int ReturnAddrIndex = FuncInfo->getRAIndex();
2974
2975   if (ReturnAddrIndex == 0) {
2976     // Set up a frame object for the return address.
2977     uint64_t SlotSize = TD->getPointerSize();
2978     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2979                                                            false);
2980     FuncInfo->setRAIndex(ReturnAddrIndex);
2981   }
2982
2983   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2984 }
2985
2986
2987 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2988                                        bool hasSymbolicDisplacement) {
2989   // Offset should fit into 32 bit immediate field.
2990   if (!isInt<32>(Offset))
2991     return false;
2992
2993   // If we don't have a symbolic displacement - we don't have any extra
2994   // restrictions.
2995   if (!hasSymbolicDisplacement)
2996     return true;
2997
2998   // FIXME: Some tweaks might be needed for medium code model.
2999   if (M != CodeModel::Small && M != CodeModel::Kernel)
3000     return false;
3001
3002   // For small code model we assume that latest object is 16MB before end of 31
3003   // bits boundary. We may also accept pretty large negative constants knowing
3004   // that all objects are in the positive half of address space.
3005   if (M == CodeModel::Small && Offset < 16*1024*1024)
3006     return true;
3007
3008   // For kernel code model we know that all object resist in the negative half
3009   // of 32bits address space. We may not accept negative offsets, since they may
3010   // be just off and we may accept pretty large positive ones.
3011   if (M == CodeModel::Kernel && Offset > 0)
3012     return true;
3013
3014   return false;
3015 }
3016
3017 /// isCalleePop - Determines whether the callee is required to pop its
3018 /// own arguments. Callee pop is necessary to support tail calls.
3019 bool X86::isCalleePop(CallingConv::ID CallingConv,
3020                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3021   if (IsVarArg)
3022     return false;
3023
3024   switch (CallingConv) {
3025   default:
3026     return false;
3027   case CallingConv::X86_StdCall:
3028     return !is64Bit;
3029   case CallingConv::X86_FastCall:
3030     return !is64Bit;
3031   case CallingConv::X86_ThisCall:
3032     return !is64Bit;
3033   case CallingConv::Fast:
3034     return TailCallOpt;
3035   case CallingConv::GHC:
3036     return TailCallOpt;
3037   }
3038 }
3039
3040 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3041 /// specific condition code, returning the condition code and the LHS/RHS of the
3042 /// comparison to make.
3043 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3044                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3045   if (!isFP) {
3046     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3047       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3048         // X > -1   -> X == 0, jump !sign.
3049         RHS = DAG.getConstant(0, RHS.getValueType());
3050         return X86::COND_NS;
3051       }
3052       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3053         // X < 0   -> X == 0, jump on sign.
3054         return X86::COND_S;
3055       }
3056       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3057         // X < 1   -> X <= 0
3058         RHS = DAG.getConstant(0, RHS.getValueType());
3059         return X86::COND_LE;
3060       }
3061     }
3062
3063     switch (SetCCOpcode) {
3064     default: llvm_unreachable("Invalid integer condition!");
3065     case ISD::SETEQ:  return X86::COND_E;
3066     case ISD::SETGT:  return X86::COND_G;
3067     case ISD::SETGE:  return X86::COND_GE;
3068     case ISD::SETLT:  return X86::COND_L;
3069     case ISD::SETLE:  return X86::COND_LE;
3070     case ISD::SETNE:  return X86::COND_NE;
3071     case ISD::SETULT: return X86::COND_B;
3072     case ISD::SETUGT: return X86::COND_A;
3073     case ISD::SETULE: return X86::COND_BE;
3074     case ISD::SETUGE: return X86::COND_AE;
3075     }
3076   }
3077
3078   // First determine if it is required or is profitable to flip the operands.
3079
3080   // If LHS is a foldable load, but RHS is not, flip the condition.
3081   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3082       !ISD::isNON_EXTLoad(RHS.getNode())) {
3083     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3084     std::swap(LHS, RHS);
3085   }
3086
3087   switch (SetCCOpcode) {
3088   default: break;
3089   case ISD::SETOLT:
3090   case ISD::SETOLE:
3091   case ISD::SETUGT:
3092   case ISD::SETUGE:
3093     std::swap(LHS, RHS);
3094     break;
3095   }
3096
3097   // On a floating point condition, the flags are set as follows:
3098   // ZF  PF  CF   op
3099   //  0 | 0 | 0 | X > Y
3100   //  0 | 0 | 1 | X < Y
3101   //  1 | 0 | 0 | X == Y
3102   //  1 | 1 | 1 | unordered
3103   switch (SetCCOpcode) {
3104   default: llvm_unreachable("Condcode should be pre-legalized away");
3105   case ISD::SETUEQ:
3106   case ISD::SETEQ:   return X86::COND_E;
3107   case ISD::SETOLT:              // flipped
3108   case ISD::SETOGT:
3109   case ISD::SETGT:   return X86::COND_A;
3110   case ISD::SETOLE:              // flipped
3111   case ISD::SETOGE:
3112   case ISD::SETGE:   return X86::COND_AE;
3113   case ISD::SETUGT:              // flipped
3114   case ISD::SETULT:
3115   case ISD::SETLT:   return X86::COND_B;
3116   case ISD::SETUGE:              // flipped
3117   case ISD::SETULE:
3118   case ISD::SETLE:   return X86::COND_BE;
3119   case ISD::SETONE:
3120   case ISD::SETNE:   return X86::COND_NE;
3121   case ISD::SETUO:   return X86::COND_P;
3122   case ISD::SETO:    return X86::COND_NP;
3123   case ISD::SETOEQ:
3124   case ISD::SETUNE:  return X86::COND_INVALID;
3125   }
3126 }
3127
3128 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3129 /// code. Current x86 isa includes the following FP cmov instructions:
3130 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3131 static bool hasFPCMov(unsigned X86CC) {
3132   switch (X86CC) {
3133   default:
3134     return false;
3135   case X86::COND_B:
3136   case X86::COND_BE:
3137   case X86::COND_E:
3138   case X86::COND_P:
3139   case X86::COND_A:
3140   case X86::COND_AE:
3141   case X86::COND_NE:
3142   case X86::COND_NP:
3143     return true;
3144   }
3145 }
3146
3147 /// isFPImmLegal - Returns true if the target can instruction select the
3148 /// specified FP immediate natively. If false, the legalizer will
3149 /// materialize the FP immediate as a load from a constant pool.
3150 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3151   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3152     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3153       return true;
3154   }
3155   return false;
3156 }
3157
3158 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3159 /// the specified range (L, H].
3160 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3161   return (Val < 0) || (Val >= Low && Val < Hi);
3162 }
3163
3164 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3165 /// specified value.
3166 static bool isUndefOrEqual(int Val, int CmpVal) {
3167   if (Val < 0 || Val == CmpVal)
3168     return true;
3169   return false;
3170 }
3171
3172 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3173 /// from position Pos and ending in Pos+Size, falls within the specified
3174 /// sequential range (L, L+Pos]. or is undef.
3175 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3176                                        unsigned Pos, unsigned Size, int Low) {
3177   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3178     if (!isUndefOrEqual(Mask[i], Low))
3179       return false;
3180   return true;
3181 }
3182
3183 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3184 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3185 /// the second operand.
3186 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3187   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3188     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3189   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3190     return (Mask[0] < 2 && Mask[1] < 2);
3191   return false;
3192 }
3193
3194 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3195 /// is suitable for input to PSHUFHW.
3196 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3197   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3198     return false;
3199
3200   // Lower quadword copied in order or undef.
3201   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3202     return false;
3203
3204   // Upper quadword shuffled.
3205   for (unsigned i = 4; i != 8; ++i)
3206     if (!isUndefOrInRange(Mask[i], 4, 8))
3207       return false;
3208
3209   if (VT == MVT::v16i16) {
3210     // Lower quadword copied in order or undef.
3211     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3212       return false;
3213
3214     // Upper quadword shuffled.
3215     for (unsigned i = 12; i != 16; ++i)
3216       if (!isUndefOrInRange(Mask[i], 12, 16))
3217         return false;
3218   }
3219
3220   return true;
3221 }
3222
3223 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3224 /// is suitable for input to PSHUFLW.
3225 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3226   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3227     return false;
3228
3229   // Upper quadword copied in order.
3230   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3231     return false;
3232
3233   // Lower quadword shuffled.
3234   for (unsigned i = 0; i != 4; ++i)
3235     if (!isUndefOrInRange(Mask[i], 0, 4))
3236       return false;
3237
3238   if (VT == MVT::v16i16) {
3239     // Upper quadword copied in order.
3240     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3241       return false;
3242
3243     // Lower quadword shuffled.
3244     for (unsigned i = 8; i != 12; ++i)
3245       if (!isUndefOrInRange(Mask[i], 8, 12))
3246         return false;
3247   }
3248
3249   return true;
3250 }
3251
3252 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3253 /// is suitable for input to PALIGNR.
3254 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3255                           const X86Subtarget *Subtarget) {
3256   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3257       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3258     return false;
3259
3260   unsigned NumElts = VT.getVectorNumElements();
3261   unsigned NumLanes = VT.getSizeInBits()/128;
3262   unsigned NumLaneElts = NumElts/NumLanes;
3263
3264   // Do not handle 64-bit element shuffles with palignr.
3265   if (NumLaneElts == 2)
3266     return false;
3267
3268   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3269     unsigned i;
3270     for (i = 0; i != NumLaneElts; ++i) {
3271       if (Mask[i+l] >= 0)
3272         break;
3273     }
3274
3275     // Lane is all undef, go to next lane
3276     if (i == NumLaneElts)
3277       continue;
3278
3279     int Start = Mask[i+l];
3280
3281     // Make sure its in this lane in one of the sources
3282     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3283         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3284       return false;
3285
3286     // If not lane 0, then we must match lane 0
3287     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3288       return false;
3289
3290     // Correct second source to be contiguous with first source
3291     if (Start >= (int)NumElts)
3292       Start -= NumElts - NumLaneElts;
3293
3294     // Make sure we're shifting in the right direction.
3295     if (Start <= (int)(i+l))
3296       return false;
3297
3298     Start -= i;
3299
3300     // Check the rest of the elements to see if they are consecutive.
3301     for (++i; i != NumLaneElts; ++i) {
3302       int Idx = Mask[i+l];
3303
3304       // Make sure its in this lane
3305       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3306           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3307         return false;
3308
3309       // If not lane 0, then we must match lane 0
3310       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3311         return false;
3312
3313       if (Idx >= (int)NumElts)
3314         Idx -= NumElts - NumLaneElts;
3315
3316       if (!isUndefOrEqual(Idx, Start+i))
3317         return false;
3318
3319     }
3320   }
3321
3322   return true;
3323 }
3324
3325 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3326 /// the two vector operands have swapped position.
3327 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3328                                      unsigned NumElems) {
3329   for (unsigned i = 0; i != NumElems; ++i) {
3330     int idx = Mask[i];
3331     if (idx < 0)
3332       continue;
3333     else if (idx < (int)NumElems)
3334       Mask[i] = idx + NumElems;
3335     else
3336       Mask[i] = idx - NumElems;
3337   }
3338 }
3339
3340 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3341 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3342 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3343 /// reverse of what x86 shuffles want.
3344 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3345                         bool Commuted = false) {
3346   if (!HasAVX && VT.getSizeInBits() == 256)
3347     return false;
3348
3349   unsigned NumElems = VT.getVectorNumElements();
3350   unsigned NumLanes = VT.getSizeInBits()/128;
3351   unsigned NumLaneElems = NumElems/NumLanes;
3352
3353   if (NumLaneElems != 2 && NumLaneElems != 4)
3354     return false;
3355
3356   // VSHUFPSY divides the resulting vector into 4 chunks.
3357   // The sources are also splitted into 4 chunks, and each destination
3358   // chunk must come from a different source chunk.
3359   //
3360   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3361   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3362   //
3363   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3364   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3365   //
3366   // VSHUFPDY divides the resulting vector into 4 chunks.
3367   // The sources are also splitted into 4 chunks, and each destination
3368   // chunk must come from a different source chunk.
3369   //
3370   //  SRC1 =>      X3       X2       X1       X0
3371   //  SRC2 =>      Y3       Y2       Y1       Y0
3372   //
3373   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3374   //
3375   unsigned HalfLaneElems = NumLaneElems/2;
3376   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3377     for (unsigned i = 0; i != NumLaneElems; ++i) {
3378       int Idx = Mask[i+l];
3379       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3380       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3381         return false;
3382       // For VSHUFPSY, the mask of the second half must be the same as the
3383       // first but with the appropriate offsets. This works in the same way as
3384       // VPERMILPS works with masks.
3385       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3386         continue;
3387       if (!isUndefOrEqual(Idx, Mask[i]+l))
3388         return false;
3389     }
3390   }
3391
3392   return true;
3393 }
3394
3395 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3396 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3397 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3398   unsigned NumElems = VT.getVectorNumElements();
3399
3400   if (VT.getSizeInBits() != 128)
3401     return false;
3402
3403   if (NumElems != 4)
3404     return false;
3405
3406   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3407   return isUndefOrEqual(Mask[0], 6) &&
3408          isUndefOrEqual(Mask[1], 7) &&
3409          isUndefOrEqual(Mask[2], 2) &&
3410          isUndefOrEqual(Mask[3], 3);
3411 }
3412
3413 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3414 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3415 /// <2, 3, 2, 3>
3416 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3417   unsigned NumElems = VT.getVectorNumElements();
3418
3419   if (VT.getSizeInBits() != 128)
3420     return false;
3421
3422   if (NumElems != 4)
3423     return false;
3424
3425   return isUndefOrEqual(Mask[0], 2) &&
3426          isUndefOrEqual(Mask[1], 3) &&
3427          isUndefOrEqual(Mask[2], 2) &&
3428          isUndefOrEqual(Mask[3], 3);
3429 }
3430
3431 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3432 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3433 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3434   if (VT.getSizeInBits() != 128)
3435     return false;
3436
3437   unsigned NumElems = VT.getVectorNumElements();
3438
3439   if (NumElems != 2 && NumElems != 4)
3440     return false;
3441
3442   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3443     if (!isUndefOrEqual(Mask[i], i + NumElems))
3444       return false;
3445
3446   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3447     if (!isUndefOrEqual(Mask[i], i))
3448       return false;
3449
3450   return true;
3451 }
3452
3453 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3454 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3455 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3456   unsigned NumElems = VT.getVectorNumElements();
3457
3458   if ((NumElems != 2 && NumElems != 4)
3459       || VT.getSizeInBits() > 128)
3460     return false;
3461
3462   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3463     if (!isUndefOrEqual(Mask[i], i))
3464       return false;
3465
3466   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3467     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3468       return false;
3469
3470   return true;
3471 }
3472
3473 //
3474 // Some special combinations that can be optimized.
3475 //
3476 static
3477 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3478                                SelectionDAG &DAG) {
3479   EVT VT = SVOp->getValueType(0);
3480   DebugLoc dl = SVOp->getDebugLoc();
3481
3482   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3483     return SDValue();
3484
3485   ArrayRef<int> Mask = SVOp->getMask();
3486
3487   // These are the special masks that may be optimized.
3488   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3489   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3490   bool MatchEvenMask = true;
3491   bool MatchOddMask  = true;
3492   for (int i=0; i<8; ++i) {
3493     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3494       MatchEvenMask = false;
3495     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3496       MatchOddMask = false;
3497   }
3498   static const int CompactionMaskEven[] = {0, 2, -1, -1, 4, 6, -1, -1};
3499   static const int CompactionMaskOdd [] = {1, 3, -1, -1, 5, 7, -1, -1};
3500
3501   const int *CompactionMask;
3502   if (MatchEvenMask)
3503     CompactionMask = CompactionMaskEven;
3504   else if (MatchOddMask)
3505     CompactionMask = CompactionMaskOdd;
3506   else
3507     return SDValue();
3508
3509   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3510
3511   SDValue Op0 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(0),
3512                                      UndefNode, CompactionMask);
3513   SDValue Op1 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(1),
3514                                      UndefNode, CompactionMask);
3515   static const int UnpackMask[] = {0, 8, 1, 9, 4, 12, 5, 13};
3516   return DAG.getVectorShuffle(VT, dl, Op0, Op1, UnpackMask);
3517 }
3518
3519 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3520 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3521 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3522                          bool HasAVX2, bool V2IsSplat = false) {
3523   unsigned NumElts = VT.getVectorNumElements();
3524
3525   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3526          "Unsupported vector type for unpckh");
3527
3528   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3529       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3530     return false;
3531
3532   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3533   // independently on 128-bit lanes.
3534   unsigned NumLanes = VT.getSizeInBits()/128;
3535   unsigned NumLaneElts = NumElts/NumLanes;
3536
3537   for (unsigned l = 0; l != NumLanes; ++l) {
3538     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3539          i != (l+1)*NumLaneElts;
3540          i += 2, ++j) {
3541       int BitI  = Mask[i];
3542       int BitI1 = Mask[i+1];
3543       if (!isUndefOrEqual(BitI, j))
3544         return false;
3545       if (V2IsSplat) {
3546         if (!isUndefOrEqual(BitI1, NumElts))
3547           return false;
3548       } else {
3549         if (!isUndefOrEqual(BitI1, j + NumElts))
3550           return false;
3551       }
3552     }
3553   }
3554
3555   return true;
3556 }
3557
3558 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3559 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3560 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3561                          bool HasAVX2, bool V2IsSplat = false) {
3562   unsigned NumElts = VT.getVectorNumElements();
3563
3564   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3565          "Unsupported vector type for unpckh");
3566
3567   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3568       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3569     return false;
3570
3571   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3572   // independently on 128-bit lanes.
3573   unsigned NumLanes = VT.getSizeInBits()/128;
3574   unsigned NumLaneElts = NumElts/NumLanes;
3575
3576   for (unsigned l = 0; l != NumLanes; ++l) {
3577     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3578          i != (l+1)*NumLaneElts; i += 2, ++j) {
3579       int BitI  = Mask[i];
3580       int BitI1 = Mask[i+1];
3581       if (!isUndefOrEqual(BitI, j))
3582         return false;
3583       if (V2IsSplat) {
3584         if (isUndefOrEqual(BitI1, NumElts))
3585           return false;
3586       } else {
3587         if (!isUndefOrEqual(BitI1, j+NumElts))
3588           return false;
3589       }
3590     }
3591   }
3592   return true;
3593 }
3594
3595 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3596 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3597 /// <0, 0, 1, 1>
3598 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3599                                   bool HasAVX2) {
3600   unsigned NumElts = VT.getVectorNumElements();
3601
3602   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3603          "Unsupported vector type for unpckh");
3604
3605   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3606       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3607     return false;
3608
3609   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3610   // FIXME: Need a better way to get rid of this, there's no latency difference
3611   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3612   // the former later. We should also remove the "_undef" special mask.
3613   if (NumElts == 4 && VT.getSizeInBits() == 256)
3614     return false;
3615
3616   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3617   // independently on 128-bit lanes.
3618   unsigned NumLanes = VT.getSizeInBits()/128;
3619   unsigned NumLaneElts = NumElts/NumLanes;
3620
3621   for (unsigned l = 0; l != NumLanes; ++l) {
3622     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3623          i != (l+1)*NumLaneElts;
3624          i += 2, ++j) {
3625       int BitI  = Mask[i];
3626       int BitI1 = Mask[i+1];
3627
3628       if (!isUndefOrEqual(BitI, j))
3629         return false;
3630       if (!isUndefOrEqual(BitI1, j))
3631         return false;
3632     }
3633   }
3634
3635   return true;
3636 }
3637
3638 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3639 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3640 /// <2, 2, 3, 3>
3641 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3642   unsigned NumElts = VT.getVectorNumElements();
3643
3644   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3645          "Unsupported vector type for unpckh");
3646
3647   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3648       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3649     return false;
3650
3651   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3652   // independently on 128-bit lanes.
3653   unsigned NumLanes = VT.getSizeInBits()/128;
3654   unsigned NumLaneElts = NumElts/NumLanes;
3655
3656   for (unsigned l = 0; l != NumLanes; ++l) {
3657     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3658          i != (l+1)*NumLaneElts; i += 2, ++j) {
3659       int BitI  = Mask[i];
3660       int BitI1 = Mask[i+1];
3661       if (!isUndefOrEqual(BitI, j))
3662         return false;
3663       if (!isUndefOrEqual(BitI1, j))
3664         return false;
3665     }
3666   }
3667   return true;
3668 }
3669
3670 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3671 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3672 /// MOVSD, and MOVD, i.e. setting the lowest element.
3673 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3674   if (VT.getVectorElementType().getSizeInBits() < 32)
3675     return false;
3676   if (VT.getSizeInBits() == 256)
3677     return false;
3678
3679   unsigned NumElts = VT.getVectorNumElements();
3680
3681   if (!isUndefOrEqual(Mask[0], NumElts))
3682     return false;
3683
3684   for (unsigned i = 1; i != NumElts; ++i)
3685     if (!isUndefOrEqual(Mask[i], i))
3686       return false;
3687
3688   return true;
3689 }
3690
3691 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3692 /// as permutations between 128-bit chunks or halves. As an example: this
3693 /// shuffle bellow:
3694 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3695 /// The first half comes from the second half of V1 and the second half from the
3696 /// the second half of V2.
3697 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3698   if (!HasAVX || VT.getSizeInBits() != 256)
3699     return false;
3700
3701   // The shuffle result is divided into half A and half B. In total the two
3702   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3703   // B must come from C, D, E or F.
3704   unsigned HalfSize = VT.getVectorNumElements()/2;
3705   bool MatchA = false, MatchB = false;
3706
3707   // Check if A comes from one of C, D, E, F.
3708   for (unsigned Half = 0; Half != 4; ++Half) {
3709     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3710       MatchA = true;
3711       break;
3712     }
3713   }
3714
3715   // Check if B comes from one of C, D, E, F.
3716   for (unsigned Half = 0; Half != 4; ++Half) {
3717     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3718       MatchB = true;
3719       break;
3720     }
3721   }
3722
3723   return MatchA && MatchB;
3724 }
3725
3726 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3727 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3728 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3729   EVT VT = SVOp->getValueType(0);
3730
3731   unsigned HalfSize = VT.getVectorNumElements()/2;
3732
3733   unsigned FstHalf = 0, SndHalf = 0;
3734   for (unsigned i = 0; i < HalfSize; ++i) {
3735     if (SVOp->getMaskElt(i) > 0) {
3736       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3737       break;
3738     }
3739   }
3740   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3741     if (SVOp->getMaskElt(i) > 0) {
3742       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3743       break;
3744     }
3745   }
3746
3747   return (FstHalf | (SndHalf << 4));
3748 }
3749
3750 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3751 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3752 /// Note that VPERMIL mask matching is different depending whether theunderlying
3753 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3754 /// to the same elements of the low, but to the higher half of the source.
3755 /// In VPERMILPD the two lanes could be shuffled independently of each other
3756 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3757 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3758   if (!HasAVX)
3759     return false;
3760
3761   unsigned NumElts = VT.getVectorNumElements();
3762   // Only match 256-bit with 32/64-bit types
3763   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3764     return false;
3765
3766   unsigned NumLanes = VT.getSizeInBits()/128;
3767   unsigned LaneSize = NumElts/NumLanes;
3768   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3769     for (unsigned i = 0; i != LaneSize; ++i) {
3770       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3771         return false;
3772       if (NumElts != 8 || l == 0)
3773         continue;
3774       // VPERMILPS handling
3775       if (Mask[i] < 0)
3776         continue;
3777       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3778         return false;
3779     }
3780   }
3781
3782   return true;
3783 }
3784
3785 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3786 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3787 /// element of vector 2 and the other elements to come from vector 1 in order.
3788 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3789                                bool V2IsSplat = false, bool V2IsUndef = false) {
3790   unsigned NumOps = VT.getVectorNumElements();
3791   if (VT.getSizeInBits() == 256)
3792     return false;
3793   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3794     return false;
3795
3796   if (!isUndefOrEqual(Mask[0], 0))
3797     return false;
3798
3799   for (unsigned i = 1; i != NumOps; ++i)
3800     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3801           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3802           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3803       return false;
3804
3805   return true;
3806 }
3807
3808 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3809 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3810 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3811 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3812                            const X86Subtarget *Subtarget) {
3813   if (!Subtarget->hasSSE3())
3814     return false;
3815
3816   unsigned NumElems = VT.getVectorNumElements();
3817
3818   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3819       (VT.getSizeInBits() == 256 && NumElems != 8))
3820     return false;
3821
3822   // "i+1" is the value the indexed mask element must have
3823   for (unsigned i = 0; i != NumElems; i += 2)
3824     if (!isUndefOrEqual(Mask[i], i+1) ||
3825         !isUndefOrEqual(Mask[i+1], i+1))
3826       return false;
3827
3828   return true;
3829 }
3830
3831 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3832 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3833 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3834 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3835                            const X86Subtarget *Subtarget) {
3836   if (!Subtarget->hasSSE3())
3837     return false;
3838
3839   unsigned NumElems = VT.getVectorNumElements();
3840
3841   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3842       (VT.getSizeInBits() == 256 && NumElems != 8))
3843     return false;
3844
3845   // "i" is the value the indexed mask element must have
3846   for (unsigned i = 0; i != NumElems; i += 2)
3847     if (!isUndefOrEqual(Mask[i], i) ||
3848         !isUndefOrEqual(Mask[i+1], i))
3849       return false;
3850
3851   return true;
3852 }
3853
3854 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3855 /// specifies a shuffle of elements that is suitable for input to 256-bit
3856 /// version of MOVDDUP.
3857 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3858   unsigned NumElts = VT.getVectorNumElements();
3859
3860   if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3861     return false;
3862
3863   for (unsigned i = 0; i != NumElts/2; ++i)
3864     if (!isUndefOrEqual(Mask[i], 0))
3865       return false;
3866   for (unsigned i = NumElts/2; i != NumElts; ++i)
3867     if (!isUndefOrEqual(Mask[i], NumElts/2))
3868       return false;
3869   return true;
3870 }
3871
3872 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3873 /// specifies a shuffle of elements that is suitable for input to 128-bit
3874 /// version of MOVDDUP.
3875 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3876   if (VT.getSizeInBits() != 128)
3877     return false;
3878
3879   unsigned e = VT.getVectorNumElements() / 2;
3880   for (unsigned i = 0; i != e; ++i)
3881     if (!isUndefOrEqual(Mask[i], i))
3882       return false;
3883   for (unsigned i = 0; i != e; ++i)
3884     if (!isUndefOrEqual(Mask[e+i], i))
3885       return false;
3886   return true;
3887 }
3888
3889 /// isVEXTRACTF128Index - Return true if the specified
3890 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3891 /// suitable for input to VEXTRACTF128.
3892 bool X86::isVEXTRACTF128Index(SDNode *N) {
3893   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3894     return false;
3895
3896   // The index should be aligned on a 128-bit boundary.
3897   uint64_t Index =
3898     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3899
3900   unsigned VL = N->getValueType(0).getVectorNumElements();
3901   unsigned VBits = N->getValueType(0).getSizeInBits();
3902   unsigned ElSize = VBits / VL;
3903   bool Result = (Index * ElSize) % 128 == 0;
3904
3905   return Result;
3906 }
3907
3908 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3909 /// operand specifies a subvector insert that is suitable for input to
3910 /// VINSERTF128.
3911 bool X86::isVINSERTF128Index(SDNode *N) {
3912   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3913     return false;
3914
3915   // The index should be aligned on a 128-bit boundary.
3916   uint64_t Index =
3917     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3918
3919   unsigned VL = N->getValueType(0).getVectorNumElements();
3920   unsigned VBits = N->getValueType(0).getSizeInBits();
3921   unsigned ElSize = VBits / VL;
3922   bool Result = (Index * ElSize) % 128 == 0;
3923
3924   return Result;
3925 }
3926
3927 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3928 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3929 /// Handles 128-bit and 256-bit.
3930 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3931   EVT VT = N->getValueType(0);
3932
3933   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3934          "Unsupported vector type for PSHUF/SHUFP");
3935
3936   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3937   // independently on 128-bit lanes.
3938   unsigned NumElts = VT.getVectorNumElements();
3939   unsigned NumLanes = VT.getSizeInBits()/128;
3940   unsigned NumLaneElts = NumElts/NumLanes;
3941
3942   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3943          "Only supports 2 or 4 elements per lane");
3944
3945   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3946   unsigned Mask = 0;
3947   for (unsigned i = 0; i != NumElts; ++i) {
3948     int Elt = N->getMaskElt(i);
3949     if (Elt < 0) continue;
3950     Elt &= NumLaneElts - 1;
3951     unsigned ShAmt = (i << Shift) % 8;
3952     Mask |= Elt << ShAmt;
3953   }
3954
3955   return Mask;
3956 }
3957
3958 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3959 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3960 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3961   EVT VT = N->getValueType(0);
3962
3963   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3964          "Unsupported vector type for PSHUFHW");
3965
3966   unsigned NumElts = VT.getVectorNumElements();
3967
3968   unsigned Mask = 0;
3969   for (unsigned l = 0; l != NumElts; l += 8) {
3970     // 8 nodes per lane, but we only care about the last 4.
3971     for (unsigned i = 0; i < 4; ++i) {
3972       int Elt = N->getMaskElt(l+i+4);
3973       if (Elt < 0) continue;
3974       Elt &= 0x3; // only 2-bits.
3975       Mask |= Elt << (i * 2);
3976     }
3977   }
3978
3979   return Mask;
3980 }
3981
3982 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3983 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3984 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
3985   EVT VT = N->getValueType(0);
3986
3987   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3988          "Unsupported vector type for PSHUFHW");
3989
3990   unsigned NumElts = VT.getVectorNumElements();
3991
3992   unsigned Mask = 0;
3993   for (unsigned l = 0; l != NumElts; l += 8) {
3994     // 8 nodes per lane, but we only care about the first 4.
3995     for (unsigned i = 0; i < 4; ++i) {
3996       int Elt = N->getMaskElt(l+i);
3997       if (Elt < 0) continue;
3998       Elt &= 0x3; // only 2-bits
3999       Mask |= Elt << (i * 2);
4000     }
4001   }
4002
4003   return Mask;
4004 }
4005
4006 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4007 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4008 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4009   EVT VT = SVOp->getValueType(0);
4010   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4011
4012   unsigned NumElts = VT.getVectorNumElements();
4013   unsigned NumLanes = VT.getSizeInBits()/128;
4014   unsigned NumLaneElts = NumElts/NumLanes;
4015
4016   int Val = 0;
4017   unsigned i;
4018   for (i = 0; i != NumElts; ++i) {
4019     Val = SVOp->getMaskElt(i);
4020     if (Val >= 0)
4021       break;
4022   }
4023   if (Val >= (int)NumElts)
4024     Val -= NumElts - NumLaneElts;
4025
4026   assert(Val - i > 0 && "PALIGNR imm should be positive");
4027   return (Val - i) * EltSize;
4028 }
4029
4030 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4031 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4032 /// instructions.
4033 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4034   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4035     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4036
4037   uint64_t Index =
4038     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4039
4040   EVT VecVT = N->getOperand(0).getValueType();
4041   EVT ElVT = VecVT.getVectorElementType();
4042
4043   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4044   return Index / NumElemsPerChunk;
4045 }
4046
4047 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4048 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4049 /// instructions.
4050 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4051   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4052     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4053
4054   uint64_t Index =
4055     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4056
4057   EVT VecVT = N->getValueType(0);
4058   EVT ElVT = VecVT.getVectorElementType();
4059
4060   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4061   return Index / NumElemsPerChunk;
4062 }
4063
4064 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4065 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4066 /// Handles 256-bit.
4067 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4068   EVT VT = N->getValueType(0);
4069
4070   unsigned NumElts = VT.getVectorNumElements();
4071
4072   assert((VT.is256BitVector() && NumElts == 4) &&
4073          "Unsupported vector type for VPERMQ/VPERMPD");
4074
4075   unsigned Mask = 0;
4076   for (unsigned i = 0; i != NumElts; ++i) {
4077     int Elt = N->getMaskElt(i);
4078     if (Elt < 0)
4079       continue;
4080     Mask |= Elt << (i*2);
4081   }
4082
4083   return Mask;
4084 }
4085 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4086 /// constant +0.0.
4087 bool X86::isZeroNode(SDValue Elt) {
4088   return ((isa<ConstantSDNode>(Elt) &&
4089            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4090           (isa<ConstantFPSDNode>(Elt) &&
4091            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4092 }
4093
4094 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4095 /// their permute mask.
4096 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4097                                     SelectionDAG &DAG) {
4098   EVT VT = SVOp->getValueType(0);
4099   unsigned NumElems = VT.getVectorNumElements();
4100   SmallVector<int, 8> MaskVec;
4101
4102   for (unsigned i = 0; i != NumElems; ++i) {
4103     int Idx = SVOp->getMaskElt(i);
4104     if (Idx >= 0) {
4105       if (Idx < (int)NumElems)
4106         Idx += NumElems;
4107       else
4108         Idx -= NumElems;
4109     }
4110     MaskVec.push_back(Idx);
4111   }
4112   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4113                               SVOp->getOperand(0), &MaskVec[0]);
4114 }
4115
4116 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4117 /// match movhlps. The lower half elements should come from upper half of
4118 /// V1 (and in order), and the upper half elements should come from the upper
4119 /// half of V2 (and in order).
4120 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4121   if (VT.getSizeInBits() != 128)
4122     return false;
4123   if (VT.getVectorNumElements() != 4)
4124     return false;
4125   for (unsigned i = 0, e = 2; i != e; ++i)
4126     if (!isUndefOrEqual(Mask[i], i+2))
4127       return false;
4128   for (unsigned i = 2; i != 4; ++i)
4129     if (!isUndefOrEqual(Mask[i], i+4))
4130       return false;
4131   return true;
4132 }
4133
4134 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4135 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4136 /// required.
4137 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4138   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4139     return false;
4140   N = N->getOperand(0).getNode();
4141   if (!ISD::isNON_EXTLoad(N))
4142     return false;
4143   if (LD)
4144     *LD = cast<LoadSDNode>(N);
4145   return true;
4146 }
4147
4148 // Test whether the given value is a vector value which will be legalized
4149 // into a load.
4150 static bool WillBeConstantPoolLoad(SDNode *N) {
4151   if (N->getOpcode() != ISD::BUILD_VECTOR)
4152     return false;
4153
4154   // Check for any non-constant elements.
4155   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4156     switch (N->getOperand(i).getNode()->getOpcode()) {
4157     case ISD::UNDEF:
4158     case ISD::ConstantFP:
4159     case ISD::Constant:
4160       break;
4161     default:
4162       return false;
4163     }
4164
4165   // Vectors of all-zeros and all-ones are materialized with special
4166   // instructions rather than being loaded.
4167   return !ISD::isBuildVectorAllZeros(N) &&
4168          !ISD::isBuildVectorAllOnes(N);
4169 }
4170
4171 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4172 /// match movlp{s|d}. The lower half elements should come from lower half of
4173 /// V1 (and in order), and the upper half elements should come from the upper
4174 /// half of V2 (and in order). And since V1 will become the source of the
4175 /// MOVLP, it must be either a vector load or a scalar load to vector.
4176 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4177                                ArrayRef<int> Mask, EVT VT) {
4178   if (VT.getSizeInBits() != 128)
4179     return false;
4180
4181   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4182     return false;
4183   // Is V2 is a vector load, don't do this transformation. We will try to use
4184   // load folding shufps op.
4185   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4186     return false;
4187
4188   unsigned NumElems = VT.getVectorNumElements();
4189
4190   if (NumElems != 2 && NumElems != 4)
4191     return false;
4192   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4193     if (!isUndefOrEqual(Mask[i], i))
4194       return false;
4195   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4196     if (!isUndefOrEqual(Mask[i], i+NumElems))
4197       return false;
4198   return true;
4199 }
4200
4201 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4202 /// all the same.
4203 static bool isSplatVector(SDNode *N) {
4204   if (N->getOpcode() != ISD::BUILD_VECTOR)
4205     return false;
4206
4207   SDValue SplatValue = N->getOperand(0);
4208   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4209     if (N->getOperand(i) != SplatValue)
4210       return false;
4211   return true;
4212 }
4213
4214 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4215 /// to an zero vector.
4216 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4217 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4218   SDValue V1 = N->getOperand(0);
4219   SDValue V2 = N->getOperand(1);
4220   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4221   for (unsigned i = 0; i != NumElems; ++i) {
4222     int Idx = N->getMaskElt(i);
4223     if (Idx >= (int)NumElems) {
4224       unsigned Opc = V2.getOpcode();
4225       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4226         continue;
4227       if (Opc != ISD::BUILD_VECTOR ||
4228           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4229         return false;
4230     } else if (Idx >= 0) {
4231       unsigned Opc = V1.getOpcode();
4232       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4233         continue;
4234       if (Opc != ISD::BUILD_VECTOR ||
4235           !X86::isZeroNode(V1.getOperand(Idx)))
4236         return false;
4237     }
4238   }
4239   return true;
4240 }
4241
4242 /// getZeroVector - Returns a vector of specified type with all zero elements.
4243 ///
4244 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4245                              SelectionDAG &DAG, DebugLoc dl) {
4246   assert(VT.isVector() && "Expected a vector type");
4247   unsigned Size = VT.getSizeInBits();
4248
4249   // Always build SSE zero vectors as <4 x i32> bitcasted
4250   // to their dest type. This ensures they get CSE'd.
4251   SDValue Vec;
4252   if (Size == 128) {  // SSE
4253     if (Subtarget->hasSSE2()) {  // SSE2
4254       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4255       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4256     } else { // SSE1
4257       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4258       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4259     }
4260   } else if (Size == 256) { // AVX
4261     if (Subtarget->hasAVX2()) { // AVX2
4262       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4263       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4264       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4265     } else {
4266       // 256-bit logic and arithmetic instructions in AVX are all
4267       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4268       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4269       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4270       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4271     }
4272   } else
4273     llvm_unreachable("Unexpected vector type");
4274
4275   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4276 }
4277
4278 /// getOnesVector - Returns a vector of specified type with all bits set.
4279 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4280 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4281 /// Then bitcast to their original type, ensuring they get CSE'd.
4282 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4283                              DebugLoc dl) {
4284   assert(VT.isVector() && "Expected a vector type");
4285   unsigned Size = VT.getSizeInBits();
4286
4287   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4288   SDValue Vec;
4289   if (Size == 256) {
4290     if (HasAVX2) { // AVX2
4291       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4292       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4293     } else { // AVX
4294       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4295       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4296     }
4297   } else if (Size == 128) {
4298     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4299   } else
4300     llvm_unreachable("Unexpected vector type");
4301
4302   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4303 }
4304
4305 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4306 /// that point to V2 points to its first element.
4307 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4308   for (unsigned i = 0; i != NumElems; ++i) {
4309     if (Mask[i] > (int)NumElems) {
4310       Mask[i] = NumElems;
4311     }
4312   }
4313 }
4314
4315 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4316 /// operation of specified width.
4317 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4318                        SDValue V2) {
4319   unsigned NumElems = VT.getVectorNumElements();
4320   SmallVector<int, 8> Mask;
4321   Mask.push_back(NumElems);
4322   for (unsigned i = 1; i != NumElems; ++i)
4323     Mask.push_back(i);
4324   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4325 }
4326
4327 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4328 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4329                           SDValue V2) {
4330   unsigned NumElems = VT.getVectorNumElements();
4331   SmallVector<int, 8> Mask;
4332   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4333     Mask.push_back(i);
4334     Mask.push_back(i + NumElems);
4335   }
4336   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4337 }
4338
4339 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4340 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4341                           SDValue V2) {
4342   unsigned NumElems = VT.getVectorNumElements();
4343   SmallVector<int, 8> Mask;
4344   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4345     Mask.push_back(i + Half);
4346     Mask.push_back(i + NumElems + Half);
4347   }
4348   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4349 }
4350
4351 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4352 // a generic shuffle instruction because the target has no such instructions.
4353 // Generate shuffles which repeat i16 and i8 several times until they can be
4354 // represented by v4f32 and then be manipulated by target suported shuffles.
4355 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4356   EVT VT = V.getValueType();
4357   int NumElems = VT.getVectorNumElements();
4358   DebugLoc dl = V.getDebugLoc();
4359
4360   while (NumElems > 4) {
4361     if (EltNo < NumElems/2) {
4362       V = getUnpackl(DAG, dl, VT, V, V);
4363     } else {
4364       V = getUnpackh(DAG, dl, VT, V, V);
4365       EltNo -= NumElems/2;
4366     }
4367     NumElems >>= 1;
4368   }
4369   return V;
4370 }
4371
4372 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4373 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4374   EVT VT = V.getValueType();
4375   DebugLoc dl = V.getDebugLoc();
4376   unsigned Size = VT.getSizeInBits();
4377
4378   if (Size == 128) {
4379     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4380     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4381     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4382                              &SplatMask[0]);
4383   } else if (Size == 256) {
4384     // To use VPERMILPS to splat scalars, the second half of indicies must
4385     // refer to the higher part, which is a duplication of the lower one,
4386     // because VPERMILPS can only handle in-lane permutations.
4387     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4388                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4389
4390     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4391     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4392                              &SplatMask[0]);
4393   } else
4394     llvm_unreachable("Vector size not supported");
4395
4396   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4397 }
4398
4399 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4400 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4401   EVT SrcVT = SV->getValueType(0);
4402   SDValue V1 = SV->getOperand(0);
4403   DebugLoc dl = SV->getDebugLoc();
4404
4405   int EltNo = SV->getSplatIndex();
4406   int NumElems = SrcVT.getVectorNumElements();
4407   unsigned Size = SrcVT.getSizeInBits();
4408
4409   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4410           "Unknown how to promote splat for type");
4411
4412   // Extract the 128-bit part containing the splat element and update
4413   // the splat element index when it refers to the higher register.
4414   if (Size == 256) {
4415     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4416     if (EltNo >= NumElems/2)
4417       EltNo -= NumElems/2;
4418   }
4419
4420   // All i16 and i8 vector types can't be used directly by a generic shuffle
4421   // instruction because the target has no such instruction. Generate shuffles
4422   // which repeat i16 and i8 several times until they fit in i32, and then can
4423   // be manipulated by target suported shuffles.
4424   EVT EltVT = SrcVT.getVectorElementType();
4425   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4426     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4427
4428   // Recreate the 256-bit vector and place the same 128-bit vector
4429   // into the low and high part. This is necessary because we want
4430   // to use VPERM* to shuffle the vectors
4431   if (Size == 256) {
4432     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4433   }
4434
4435   return getLegalSplat(DAG, V1, EltNo);
4436 }
4437
4438 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4439 /// vector of zero or undef vector.  This produces a shuffle where the low
4440 /// element of V2 is swizzled into the zero/undef vector, landing at element
4441 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4442 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4443                                            bool IsZero,
4444                                            const X86Subtarget *Subtarget,
4445                                            SelectionDAG &DAG) {
4446   EVT VT = V2.getValueType();
4447   SDValue V1 = IsZero
4448     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4449   unsigned NumElems = VT.getVectorNumElements();
4450   SmallVector<int, 16> MaskVec;
4451   for (unsigned i = 0; i != NumElems; ++i)
4452     // If this is the insertion idx, put the low elt of V2 here.
4453     MaskVec.push_back(i == Idx ? NumElems : i);
4454   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4455 }
4456
4457 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4458 /// target specific opcode. Returns true if the Mask could be calculated.
4459 /// Sets IsUnary to true if only uses one source.
4460 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4461                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4462   unsigned NumElems = VT.getVectorNumElements();
4463   SDValue ImmN;
4464
4465   IsUnary = false;
4466   switch(N->getOpcode()) {
4467   case X86ISD::SHUFP:
4468     ImmN = N->getOperand(N->getNumOperands()-1);
4469     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4470     break;
4471   case X86ISD::UNPCKH:
4472     DecodeUNPCKHMask(VT, Mask);
4473     break;
4474   case X86ISD::UNPCKL:
4475     DecodeUNPCKLMask(VT, Mask);
4476     break;
4477   case X86ISD::MOVHLPS:
4478     DecodeMOVHLPSMask(NumElems, Mask);
4479     break;
4480   case X86ISD::MOVLHPS:
4481     DecodeMOVLHPSMask(NumElems, Mask);
4482     break;
4483   case X86ISD::PSHUFD:
4484   case X86ISD::VPERMILP:
4485     ImmN = N->getOperand(N->getNumOperands()-1);
4486     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4487     IsUnary = true;
4488     break;
4489   case X86ISD::PSHUFHW:
4490     ImmN = N->getOperand(N->getNumOperands()-1);
4491     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4492     IsUnary = true;
4493     break;
4494   case X86ISD::PSHUFLW:
4495     ImmN = N->getOperand(N->getNumOperands()-1);
4496     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4497     IsUnary = true;
4498     break;
4499   case X86ISD::VPERMI:
4500     ImmN = N->getOperand(N->getNumOperands()-1);
4501     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4502     IsUnary = true;
4503     break;
4504   case X86ISD::MOVSS:
4505   case X86ISD::MOVSD: {
4506     // The index 0 always comes from the first element of the second source,
4507     // this is why MOVSS and MOVSD are used in the first place. The other
4508     // elements come from the other positions of the first source vector
4509     Mask.push_back(NumElems);
4510     for (unsigned i = 1; i != NumElems; ++i) {
4511       Mask.push_back(i);
4512     }
4513     break;
4514   }
4515   case X86ISD::VPERM2X128:
4516     ImmN = N->getOperand(N->getNumOperands()-1);
4517     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4518     if (Mask.empty()) return false;
4519     break;
4520   case X86ISD::MOVDDUP:
4521   case X86ISD::MOVLHPD:
4522   case X86ISD::MOVLPD:
4523   case X86ISD::MOVLPS:
4524   case X86ISD::MOVSHDUP:
4525   case X86ISD::MOVSLDUP:
4526   case X86ISD::PALIGN:
4527     // Not yet implemented
4528     return false;
4529   default: llvm_unreachable("unknown target shuffle node");
4530   }
4531
4532   return true;
4533 }
4534
4535 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4536 /// element of the result of the vector shuffle.
4537 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4538                                    unsigned Depth) {
4539   if (Depth == 6)
4540     return SDValue();  // Limit search depth.
4541
4542   SDValue V = SDValue(N, 0);
4543   EVT VT = V.getValueType();
4544   unsigned Opcode = V.getOpcode();
4545
4546   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4547   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4548     int Elt = SV->getMaskElt(Index);
4549
4550     if (Elt < 0)
4551       return DAG.getUNDEF(VT.getVectorElementType());
4552
4553     unsigned NumElems = VT.getVectorNumElements();
4554     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4555                                          : SV->getOperand(1);
4556     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4557   }
4558
4559   // Recurse into target specific vector shuffles to find scalars.
4560   if (isTargetShuffle(Opcode)) {
4561     MVT ShufVT = V.getValueType().getSimpleVT();
4562     unsigned NumElems = ShufVT.getVectorNumElements();
4563     SmallVector<int, 16> ShuffleMask;
4564     SDValue ImmN;
4565     bool IsUnary;
4566
4567     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4568       return SDValue();
4569
4570     int Elt = ShuffleMask[Index];
4571     if (Elt < 0)
4572       return DAG.getUNDEF(ShufVT.getVectorElementType());
4573
4574     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4575                                          : N->getOperand(1);
4576     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4577                                Depth+1);
4578   }
4579
4580   // Actual nodes that may contain scalar elements
4581   if (Opcode == ISD::BITCAST) {
4582     V = V.getOperand(0);
4583     EVT SrcVT = V.getValueType();
4584     unsigned NumElems = VT.getVectorNumElements();
4585
4586     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4587       return SDValue();
4588   }
4589
4590   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4591     return (Index == 0) ? V.getOperand(0)
4592                         : DAG.getUNDEF(VT.getVectorElementType());
4593
4594   if (V.getOpcode() == ISD::BUILD_VECTOR)
4595     return V.getOperand(Index);
4596
4597   return SDValue();
4598 }
4599
4600 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4601 /// shuffle operation which come from a consecutively from a zero. The
4602 /// search can start in two different directions, from left or right.
4603 static
4604 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4605                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4606   unsigned i;
4607   for (i = 0; i != NumElems; ++i) {
4608     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4609     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4610     if (!(Elt.getNode() &&
4611          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4612       break;
4613   }
4614
4615   return i;
4616 }
4617
4618 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4619 /// correspond consecutively to elements from one of the vector operands,
4620 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4621 static
4622 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4623                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4624                               unsigned NumElems, unsigned &OpNum) {
4625   bool SeenV1 = false;
4626   bool SeenV2 = false;
4627
4628   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4629     int Idx = SVOp->getMaskElt(i);
4630     // Ignore undef indicies
4631     if (Idx < 0)
4632       continue;
4633
4634     if (Idx < (int)NumElems)
4635       SeenV1 = true;
4636     else
4637       SeenV2 = true;
4638
4639     // Only accept consecutive elements from the same vector
4640     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4641       return false;
4642   }
4643
4644   OpNum = SeenV1 ? 0 : 1;
4645   return true;
4646 }
4647
4648 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4649 /// logical left shift of a vector.
4650 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4651                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4652   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4653   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4654               false /* check zeros from right */, DAG);
4655   unsigned OpSrc;
4656
4657   if (!NumZeros)
4658     return false;
4659
4660   // Considering the elements in the mask that are not consecutive zeros,
4661   // check if they consecutively come from only one of the source vectors.
4662   //
4663   //               V1 = {X, A, B, C}     0
4664   //                         \  \  \    /
4665   //   vector_shuffle V1, V2 <1, 2, 3, X>
4666   //
4667   if (!isShuffleMaskConsecutive(SVOp,
4668             0,                   // Mask Start Index
4669             NumElems-NumZeros,   // Mask End Index(exclusive)
4670             NumZeros,            // Where to start looking in the src vector
4671             NumElems,            // Number of elements in vector
4672             OpSrc))              // Which source operand ?
4673     return false;
4674
4675   isLeft = false;
4676   ShAmt = NumZeros;
4677   ShVal = SVOp->getOperand(OpSrc);
4678   return true;
4679 }
4680
4681 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4682 /// logical left shift of a vector.
4683 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4684                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4685   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4686   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4687               true /* check zeros from left */, DAG);
4688   unsigned OpSrc;
4689
4690   if (!NumZeros)
4691     return false;
4692
4693   // Considering the elements in the mask that are not consecutive zeros,
4694   // check if they consecutively come from only one of the source vectors.
4695   //
4696   //                           0    { A, B, X, X } = V2
4697   //                          / \    /  /
4698   //   vector_shuffle V1, V2 <X, X, 4, 5>
4699   //
4700   if (!isShuffleMaskConsecutive(SVOp,
4701             NumZeros,     // Mask Start Index
4702             NumElems,     // Mask End Index(exclusive)
4703             0,            // Where to start looking in the src vector
4704             NumElems,     // Number of elements in vector
4705             OpSrc))       // Which source operand ?
4706     return false;
4707
4708   isLeft = true;
4709   ShAmt = NumZeros;
4710   ShVal = SVOp->getOperand(OpSrc);
4711   return true;
4712 }
4713
4714 /// isVectorShift - Returns true if the shuffle can be implemented as a
4715 /// logical left or right shift of a vector.
4716 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4717                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4718   // Although the logic below support any bitwidth size, there are no
4719   // shift instructions which handle more than 128-bit vectors.
4720   if (SVOp->getValueType(0).getSizeInBits() > 128)
4721     return false;
4722
4723   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4724       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4725     return true;
4726
4727   return false;
4728 }
4729
4730 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4731 ///
4732 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4733                                        unsigned NumNonZero, unsigned NumZero,
4734                                        SelectionDAG &DAG,
4735                                        const X86Subtarget* Subtarget,
4736                                        const TargetLowering &TLI) {
4737   if (NumNonZero > 8)
4738     return SDValue();
4739
4740   DebugLoc dl = Op.getDebugLoc();
4741   SDValue V(0, 0);
4742   bool First = true;
4743   for (unsigned i = 0; i < 16; ++i) {
4744     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4745     if (ThisIsNonZero && First) {
4746       if (NumZero)
4747         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4748       else
4749         V = DAG.getUNDEF(MVT::v8i16);
4750       First = false;
4751     }
4752
4753     if ((i & 1) != 0) {
4754       SDValue ThisElt(0, 0), LastElt(0, 0);
4755       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4756       if (LastIsNonZero) {
4757         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4758                               MVT::i16, Op.getOperand(i-1));
4759       }
4760       if (ThisIsNonZero) {
4761         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4762         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4763                               ThisElt, DAG.getConstant(8, MVT::i8));
4764         if (LastIsNonZero)
4765           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4766       } else
4767         ThisElt = LastElt;
4768
4769       if (ThisElt.getNode())
4770         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4771                         DAG.getIntPtrConstant(i/2));
4772     }
4773   }
4774
4775   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4776 }
4777
4778 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4779 ///
4780 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4781                                      unsigned NumNonZero, unsigned NumZero,
4782                                      SelectionDAG &DAG,
4783                                      const X86Subtarget* Subtarget,
4784                                      const TargetLowering &TLI) {
4785   if (NumNonZero > 4)
4786     return SDValue();
4787
4788   DebugLoc dl = Op.getDebugLoc();
4789   SDValue V(0, 0);
4790   bool First = true;
4791   for (unsigned i = 0; i < 8; ++i) {
4792     bool isNonZero = (NonZeros & (1 << i)) != 0;
4793     if (isNonZero) {
4794       if (First) {
4795         if (NumZero)
4796           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4797         else
4798           V = DAG.getUNDEF(MVT::v8i16);
4799         First = false;
4800       }
4801       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4802                       MVT::v8i16, V, Op.getOperand(i),
4803                       DAG.getIntPtrConstant(i));
4804     }
4805   }
4806
4807   return V;
4808 }
4809
4810 /// getVShift - Return a vector logical shift node.
4811 ///
4812 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4813                          unsigned NumBits, SelectionDAG &DAG,
4814                          const TargetLowering &TLI, DebugLoc dl) {
4815   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4816   EVT ShVT = MVT::v2i64;
4817   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4818   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4819   return DAG.getNode(ISD::BITCAST, dl, VT,
4820                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4821                              DAG.getConstant(NumBits,
4822                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4823 }
4824
4825 SDValue
4826 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4827                                           SelectionDAG &DAG) const {
4828
4829   // Check if the scalar load can be widened into a vector load. And if
4830   // the address is "base + cst" see if the cst can be "absorbed" into
4831   // the shuffle mask.
4832   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4833     SDValue Ptr = LD->getBasePtr();
4834     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4835       return SDValue();
4836     EVT PVT = LD->getValueType(0);
4837     if (PVT != MVT::i32 && PVT != MVT::f32)
4838       return SDValue();
4839
4840     int FI = -1;
4841     int64_t Offset = 0;
4842     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4843       FI = FINode->getIndex();
4844       Offset = 0;
4845     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4846                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4847       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4848       Offset = Ptr.getConstantOperandVal(1);
4849       Ptr = Ptr.getOperand(0);
4850     } else {
4851       return SDValue();
4852     }
4853
4854     // FIXME: 256-bit vector instructions don't require a strict alignment,
4855     // improve this code to support it better.
4856     unsigned RequiredAlign = VT.getSizeInBits()/8;
4857     SDValue Chain = LD->getChain();
4858     // Make sure the stack object alignment is at least 16 or 32.
4859     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4860     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4861       if (MFI->isFixedObjectIndex(FI)) {
4862         // Can't change the alignment. FIXME: It's possible to compute
4863         // the exact stack offset and reference FI + adjust offset instead.
4864         // If someone *really* cares about this. That's the way to implement it.
4865         return SDValue();
4866       } else {
4867         MFI->setObjectAlignment(FI, RequiredAlign);
4868       }
4869     }
4870
4871     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4872     // Ptr + (Offset & ~15).
4873     if (Offset < 0)
4874       return SDValue();
4875     if ((Offset % RequiredAlign) & 3)
4876       return SDValue();
4877     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4878     if (StartOffset)
4879       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4880                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4881
4882     int EltNo = (Offset - StartOffset) >> 2;
4883     unsigned NumElems = VT.getVectorNumElements();
4884
4885     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4886     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4887                              LD->getPointerInfo().getWithOffset(StartOffset),
4888                              false, false, false, 0);
4889
4890     SmallVector<int, 8> Mask;
4891     for (unsigned i = 0; i != NumElems; ++i)
4892       Mask.push_back(EltNo);
4893
4894     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4895   }
4896
4897   return SDValue();
4898 }
4899
4900 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4901 /// vector of type 'VT', see if the elements can be replaced by a single large
4902 /// load which has the same value as a build_vector whose operands are 'elts'.
4903 ///
4904 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4905 ///
4906 /// FIXME: we'd also like to handle the case where the last elements are zero
4907 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4908 /// There's even a handy isZeroNode for that purpose.
4909 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4910                                         DebugLoc &DL, SelectionDAG &DAG) {
4911   EVT EltVT = VT.getVectorElementType();
4912   unsigned NumElems = Elts.size();
4913
4914   LoadSDNode *LDBase = NULL;
4915   unsigned LastLoadedElt = -1U;
4916
4917   // For each element in the initializer, see if we've found a load or an undef.
4918   // If we don't find an initial load element, or later load elements are
4919   // non-consecutive, bail out.
4920   for (unsigned i = 0; i < NumElems; ++i) {
4921     SDValue Elt = Elts[i];
4922
4923     if (!Elt.getNode() ||
4924         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4925       return SDValue();
4926     if (!LDBase) {
4927       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4928         return SDValue();
4929       LDBase = cast<LoadSDNode>(Elt.getNode());
4930       LastLoadedElt = i;
4931       continue;
4932     }
4933     if (Elt.getOpcode() == ISD::UNDEF)
4934       continue;
4935
4936     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4937     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4938       return SDValue();
4939     LastLoadedElt = i;
4940   }
4941
4942   // If we have found an entire vector of loads and undefs, then return a large
4943   // load of the entire vector width starting at the base pointer.  If we found
4944   // consecutive loads for the low half, generate a vzext_load node.
4945   if (LastLoadedElt == NumElems - 1) {
4946     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4947       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4948                          LDBase->getPointerInfo(),
4949                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4950                          LDBase->isInvariant(), 0);
4951     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4952                        LDBase->getPointerInfo(),
4953                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4954                        LDBase->isInvariant(), LDBase->getAlignment());
4955   }
4956   if (NumElems == 4 && LastLoadedElt == 1 &&
4957       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4958     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4959     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4960     SDValue ResNode =
4961         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4962                                 LDBase->getPointerInfo(),
4963                                 LDBase->getAlignment(),
4964                                 false/*isVolatile*/, true/*ReadMem*/,
4965                                 false/*WriteMem*/);
4966     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4967   }
4968   return SDValue();
4969 }
4970
4971 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4972 /// to generate a splat value for the following cases:
4973 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4974 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4975 /// a scalar load, or a constant.
4976 /// The VBROADCAST node is returned when a pattern is found,
4977 /// or SDValue() otherwise.
4978 SDValue
4979 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
4980   if (!Subtarget->hasAVX())
4981     return SDValue();
4982
4983   EVT VT = Op.getValueType();
4984   DebugLoc dl = Op.getDebugLoc();
4985
4986   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4987          "Unsupported vector type for broadcast.");
4988
4989   SDValue Ld;
4990   bool ConstSplatVal;
4991
4992   switch (Op.getOpcode()) {
4993     default:
4994       // Unknown pattern found.
4995       return SDValue();
4996
4997     case ISD::BUILD_VECTOR: {
4998       // The BUILD_VECTOR node must be a splat.
4999       if (!isSplatVector(Op.getNode()))
5000         return SDValue();
5001
5002       Ld = Op.getOperand(0);
5003       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5004                      Ld.getOpcode() == ISD::ConstantFP);
5005
5006       // The suspected load node has several users. Make sure that all
5007       // of its users are from the BUILD_VECTOR node.
5008       // Constants may have multiple users.
5009       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5010         return SDValue();
5011       break;
5012     }
5013
5014     case ISD::VECTOR_SHUFFLE: {
5015       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5016
5017       // Shuffles must have a splat mask where the first element is
5018       // broadcasted.
5019       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5020         return SDValue();
5021
5022       SDValue Sc = Op.getOperand(0);
5023       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5024           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5025
5026         if (!Subtarget->hasAVX2())
5027           return SDValue();
5028
5029         // Use the register form of the broadcast instruction available on AVX2.
5030         if (VT.is256BitVector())
5031           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5032         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5033       }
5034
5035       Ld = Sc.getOperand(0);
5036       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5037                        Ld.getOpcode() == ISD::ConstantFP);
5038
5039       // The scalar_to_vector node and the suspected
5040       // load node must have exactly one user.
5041       // Constants may have multiple users.
5042       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5043         return SDValue();
5044       break;
5045     }
5046   }
5047
5048   bool Is256 = VT.getSizeInBits() == 256;
5049
5050   // Handle the broadcasting a single constant scalar from the constant pool
5051   // into a vector. On Sandybridge it is still better to load a constant vector
5052   // from the constant pool and not to broadcast it from a scalar.
5053   if (ConstSplatVal && Subtarget->hasAVX2()) {
5054     EVT CVT = Ld.getValueType();
5055     assert(!CVT.isVector() && "Must not broadcast a vector type");
5056     unsigned ScalarSize = CVT.getSizeInBits();
5057
5058     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5059       const Constant *C = 0;
5060       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5061         C = CI->getConstantIntValue();
5062       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5063         C = CF->getConstantFPValue();
5064
5065       assert(C && "Invalid constant type");
5066
5067       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5068       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5069       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5070                        MachinePointerInfo::getConstantPool(),
5071                        false, false, false, Alignment);
5072
5073       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5074     }
5075   }
5076
5077   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5078   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5079
5080   // Handle AVX2 in-register broadcasts.
5081   if (!IsLoad && Subtarget->hasAVX2() &&
5082       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5083     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5084
5085   // The scalar source must be a normal load.
5086   if (!IsLoad)
5087     return SDValue();
5088
5089   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5090     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5091
5092   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5093   // double since there is no vbroadcastsd xmm
5094   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5095     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5096       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5097   }
5098
5099   // Unsupported broadcast.
5100   return SDValue();
5101 }
5102
5103 SDValue
5104 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5105   DebugLoc dl = Op.getDebugLoc();
5106
5107   EVT VT = Op.getValueType();
5108   EVT ExtVT = VT.getVectorElementType();
5109   unsigned NumElems = Op.getNumOperands();
5110
5111   // Vectors containing all zeros can be matched by pxor and xorps later
5112   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5113     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5114     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5115     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5116       return Op;
5117
5118     return getZeroVector(VT, Subtarget, DAG, dl);
5119   }
5120
5121   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5122   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5123   // vpcmpeqd on 256-bit vectors.
5124   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5125     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5126       return Op;
5127
5128     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5129   }
5130
5131   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5132   if (Broadcast.getNode())
5133     return Broadcast;
5134
5135   unsigned EVTBits = ExtVT.getSizeInBits();
5136
5137   unsigned NumZero  = 0;
5138   unsigned NumNonZero = 0;
5139   unsigned NonZeros = 0;
5140   bool IsAllConstants = true;
5141   SmallSet<SDValue, 8> Values;
5142   for (unsigned i = 0; i < NumElems; ++i) {
5143     SDValue Elt = Op.getOperand(i);
5144     if (Elt.getOpcode() == ISD::UNDEF)
5145       continue;
5146     Values.insert(Elt);
5147     if (Elt.getOpcode() != ISD::Constant &&
5148         Elt.getOpcode() != ISD::ConstantFP)
5149       IsAllConstants = false;
5150     if (X86::isZeroNode(Elt))
5151       NumZero++;
5152     else {
5153       NonZeros |= (1 << i);
5154       NumNonZero++;
5155     }
5156   }
5157
5158   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5159   if (NumNonZero == 0)
5160     return DAG.getUNDEF(VT);
5161
5162   // Special case for single non-zero, non-undef, element.
5163   if (NumNonZero == 1) {
5164     unsigned Idx = CountTrailingZeros_32(NonZeros);
5165     SDValue Item = Op.getOperand(Idx);
5166
5167     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5168     // the value are obviously zero, truncate the value to i32 and do the
5169     // insertion that way.  Only do this if the value is non-constant or if the
5170     // value is a constant being inserted into element 0.  It is cheaper to do
5171     // a constant pool load than it is to do a movd + shuffle.
5172     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5173         (!IsAllConstants || Idx == 0)) {
5174       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5175         // Handle SSE only.
5176         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5177         EVT VecVT = MVT::v4i32;
5178         unsigned VecElts = 4;
5179
5180         // Truncate the value (which may itself be a constant) to i32, and
5181         // convert it to a vector with movd (S2V+shuffle to zero extend).
5182         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5183         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5184         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5185
5186         // Now we have our 32-bit value zero extended in the low element of
5187         // a vector.  If Idx != 0, swizzle it into place.
5188         if (Idx != 0) {
5189           SmallVector<int, 4> Mask;
5190           Mask.push_back(Idx);
5191           for (unsigned i = 1; i != VecElts; ++i)
5192             Mask.push_back(i);
5193           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5194                                       &Mask[0]);
5195         }
5196         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5197       }
5198     }
5199
5200     // If we have a constant or non-constant insertion into the low element of
5201     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5202     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5203     // depending on what the source datatype is.
5204     if (Idx == 0) {
5205       if (NumZero == 0)
5206         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5207
5208       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5209           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5210         if (VT.getSizeInBits() == 256) {
5211           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5212           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5213                              Item, DAG.getIntPtrConstant(0));
5214         }
5215         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5216         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5217         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5218         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5219       }
5220
5221       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5222         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5223         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5224         if (VT.getSizeInBits() == 256) {
5225           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5226           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5227         } else {
5228           assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5229           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5230         }
5231         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5232       }
5233     }
5234
5235     // Is it a vector logical left shift?
5236     if (NumElems == 2 && Idx == 1 &&
5237         X86::isZeroNode(Op.getOperand(0)) &&
5238         !X86::isZeroNode(Op.getOperand(1))) {
5239       unsigned NumBits = VT.getSizeInBits();
5240       return getVShift(true, VT,
5241                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5242                                    VT, Op.getOperand(1)),
5243                        NumBits/2, DAG, *this, dl);
5244     }
5245
5246     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5247       return SDValue();
5248
5249     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5250     // is a non-constant being inserted into an element other than the low one,
5251     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5252     // movd/movss) to move this into the low element, then shuffle it into
5253     // place.
5254     if (EVTBits == 32) {
5255       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5256
5257       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5258       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5259       SmallVector<int, 8> MaskVec;
5260       for (unsigned i = 0; i != NumElems; ++i)
5261         MaskVec.push_back(i == Idx ? 0 : 1);
5262       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5263     }
5264   }
5265
5266   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5267   if (Values.size() == 1) {
5268     if (EVTBits == 32) {
5269       // Instead of a shuffle like this:
5270       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5271       // Check if it's possible to issue this instead.
5272       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5273       unsigned Idx = CountTrailingZeros_32(NonZeros);
5274       SDValue Item = Op.getOperand(Idx);
5275       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5276         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5277     }
5278     return SDValue();
5279   }
5280
5281   // A vector full of immediates; various special cases are already
5282   // handled, so this is best done with a single constant-pool load.
5283   if (IsAllConstants)
5284     return SDValue();
5285
5286   // For AVX-length vectors, build the individual 128-bit pieces and use
5287   // shuffles to put them in place.
5288   if (VT.getSizeInBits() == 256) {
5289     SmallVector<SDValue, 32> V;
5290     for (unsigned i = 0; i != NumElems; ++i)
5291       V.push_back(Op.getOperand(i));
5292
5293     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5294
5295     // Build both the lower and upper subvector.
5296     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5297     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5298                                 NumElems/2);
5299
5300     // Recreate the wider vector with the lower and upper part.
5301     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5302   }
5303
5304   // Let legalizer expand 2-wide build_vectors.
5305   if (EVTBits == 64) {
5306     if (NumNonZero == 1) {
5307       // One half is zero or undef.
5308       unsigned Idx = CountTrailingZeros_32(NonZeros);
5309       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5310                                  Op.getOperand(Idx));
5311       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5312     }
5313     return SDValue();
5314   }
5315
5316   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5317   if (EVTBits == 8 && NumElems == 16) {
5318     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5319                                         Subtarget, *this);
5320     if (V.getNode()) return V;
5321   }
5322
5323   if (EVTBits == 16 && NumElems == 8) {
5324     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5325                                       Subtarget, *this);
5326     if (V.getNode()) return V;
5327   }
5328
5329   // If element VT is == 32 bits, turn it into a number of shuffles.
5330   SmallVector<SDValue, 8> V(NumElems);
5331   if (NumElems == 4 && NumZero > 0) {
5332     for (unsigned i = 0; i < 4; ++i) {
5333       bool isZero = !(NonZeros & (1 << i));
5334       if (isZero)
5335         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5336       else
5337         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5338     }
5339
5340     for (unsigned i = 0; i < 2; ++i) {
5341       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5342         default: break;
5343         case 0:
5344           V[i] = V[i*2];  // Must be a zero vector.
5345           break;
5346         case 1:
5347           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5348           break;
5349         case 2:
5350           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5351           break;
5352         case 3:
5353           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5354           break;
5355       }
5356     }
5357
5358     bool Reverse1 = (NonZeros & 0x3) == 2;
5359     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5360     int MaskVec[] = {
5361       Reverse1 ? 1 : 0,
5362       Reverse1 ? 0 : 1,
5363       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5364       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5365     };
5366     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5367   }
5368
5369   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5370     // Check for a build vector of consecutive loads.
5371     for (unsigned i = 0; i < NumElems; ++i)
5372       V[i] = Op.getOperand(i);
5373
5374     // Check for elements which are consecutive loads.
5375     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5376     if (LD.getNode())
5377       return LD;
5378
5379     // For SSE 4.1, use insertps to put the high elements into the low element.
5380     if (getSubtarget()->hasSSE41()) {
5381       SDValue Result;
5382       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5383         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5384       else
5385         Result = DAG.getUNDEF(VT);
5386
5387       for (unsigned i = 1; i < NumElems; ++i) {
5388         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5389         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5390                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5391       }
5392       return Result;
5393     }
5394
5395     // Otherwise, expand into a number of unpckl*, start by extending each of
5396     // our (non-undef) elements to the full vector width with the element in the
5397     // bottom slot of the vector (which generates no code for SSE).
5398     for (unsigned i = 0; i < NumElems; ++i) {
5399       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5400         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5401       else
5402         V[i] = DAG.getUNDEF(VT);
5403     }
5404
5405     // Next, we iteratively mix elements, e.g. for v4f32:
5406     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5407     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5408     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5409     unsigned EltStride = NumElems >> 1;
5410     while (EltStride != 0) {
5411       for (unsigned i = 0; i < EltStride; ++i) {
5412         // If V[i+EltStride] is undef and this is the first round of mixing,
5413         // then it is safe to just drop this shuffle: V[i] is already in the
5414         // right place, the one element (since it's the first round) being
5415         // inserted as undef can be dropped.  This isn't safe for successive
5416         // rounds because they will permute elements within both vectors.
5417         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5418             EltStride == NumElems/2)
5419           continue;
5420
5421         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5422       }
5423       EltStride >>= 1;
5424     }
5425     return V[0];
5426   }
5427   return SDValue();
5428 }
5429
5430 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5431 // them in a MMX register.  This is better than doing a stack convert.
5432 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5433   DebugLoc dl = Op.getDebugLoc();
5434   EVT ResVT = Op.getValueType();
5435
5436   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5437          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5438   int Mask[2];
5439   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5440   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5441   InVec = Op.getOperand(1);
5442   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5443     unsigned NumElts = ResVT.getVectorNumElements();
5444     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5445     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5446                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5447   } else {
5448     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5449     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5450     Mask[0] = 0; Mask[1] = 2;
5451     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5452   }
5453   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5454 }
5455
5456 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5457 // to create 256-bit vectors from two other 128-bit ones.
5458 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5459   DebugLoc dl = Op.getDebugLoc();
5460   EVT ResVT = Op.getValueType();
5461
5462   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5463
5464   SDValue V1 = Op.getOperand(0);
5465   SDValue V2 = Op.getOperand(1);
5466   unsigned NumElems = ResVT.getVectorNumElements();
5467
5468   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5469 }
5470
5471 SDValue
5472 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5473   EVT ResVT = Op.getValueType();
5474
5475   assert(Op.getNumOperands() == 2);
5476   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5477          "Unsupported CONCAT_VECTORS for value type");
5478
5479   // We support concatenate two MMX registers and place them in a MMX register.
5480   // This is better than doing a stack convert.
5481   if (ResVT.is128BitVector())
5482     return LowerMMXCONCAT_VECTORS(Op, DAG);
5483
5484   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5485   // from two other 128-bit ones.
5486   return LowerAVXCONCAT_VECTORS(Op, DAG);
5487 }
5488
5489 // Try to lower a shuffle node into a simple blend instruction.
5490 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5491                                           const X86Subtarget *Subtarget,
5492                                           SelectionDAG &DAG) {
5493   SDValue V1 = SVOp->getOperand(0);
5494   SDValue V2 = SVOp->getOperand(1);
5495   DebugLoc dl = SVOp->getDebugLoc();
5496   MVT VT = SVOp->getValueType(0).getSimpleVT();
5497   unsigned NumElems = VT.getVectorNumElements();
5498
5499   if (!Subtarget->hasSSE41())
5500     return SDValue();
5501
5502   unsigned ISDNo = 0;
5503   MVT OpTy;
5504
5505   switch (VT.SimpleTy) {
5506   default: return SDValue();
5507   case MVT::v8i16:
5508     ISDNo = X86ISD::BLENDPW;
5509     OpTy = MVT::v8i16;
5510     break;
5511   case MVT::v4i32:
5512   case MVT::v4f32:
5513     ISDNo = X86ISD::BLENDPS;
5514     OpTy = MVT::v4f32;
5515     break;
5516   case MVT::v2i64:
5517   case MVT::v2f64:
5518     ISDNo = X86ISD::BLENDPD;
5519     OpTy = MVT::v2f64;
5520     break;
5521   case MVT::v8i32:
5522   case MVT::v8f32:
5523     if (!Subtarget->hasAVX())
5524       return SDValue();
5525     ISDNo = X86ISD::BLENDPS;
5526     OpTy = MVT::v8f32;
5527     break;
5528   case MVT::v4i64:
5529   case MVT::v4f64:
5530     if (!Subtarget->hasAVX())
5531       return SDValue();
5532     ISDNo = X86ISD::BLENDPD;
5533     OpTy = MVT::v4f64;
5534     break;
5535   }
5536   assert(ISDNo && "Invalid Op Number");
5537
5538   unsigned MaskVals = 0;
5539
5540   for (unsigned i = 0; i != NumElems; ++i) {
5541     int EltIdx = SVOp->getMaskElt(i);
5542     if (EltIdx == (int)i || EltIdx < 0)
5543       MaskVals |= (1<<i);
5544     else if (EltIdx == (int)(i + NumElems))
5545       continue; // Bit is set to zero;
5546     else
5547       return SDValue();
5548   }
5549
5550   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5551   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5552   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5553                              DAG.getConstant(MaskVals, MVT::i32));
5554   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5555 }
5556
5557 // v8i16 shuffles - Prefer shuffles in the following order:
5558 // 1. [all]   pshuflw, pshufhw, optional move
5559 // 2. [ssse3] 1 x pshufb
5560 // 3. [ssse3] 2 x pshufb + 1 x por
5561 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5562 SDValue
5563 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5564                                             SelectionDAG &DAG) const {
5565   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5566   SDValue V1 = SVOp->getOperand(0);
5567   SDValue V2 = SVOp->getOperand(1);
5568   DebugLoc dl = SVOp->getDebugLoc();
5569   SmallVector<int, 8> MaskVals;
5570
5571   // Determine if more than 1 of the words in each of the low and high quadwords
5572   // of the result come from the same quadword of one of the two inputs.  Undef
5573   // mask values count as coming from any quadword, for better codegen.
5574   unsigned LoQuad[] = { 0, 0, 0, 0 };
5575   unsigned HiQuad[] = { 0, 0, 0, 0 };
5576   std::bitset<4> InputQuads;
5577   for (unsigned i = 0; i < 8; ++i) {
5578     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5579     int EltIdx = SVOp->getMaskElt(i);
5580     MaskVals.push_back(EltIdx);
5581     if (EltIdx < 0) {
5582       ++Quad[0];
5583       ++Quad[1];
5584       ++Quad[2];
5585       ++Quad[3];
5586       continue;
5587     }
5588     ++Quad[EltIdx / 4];
5589     InputQuads.set(EltIdx / 4);
5590   }
5591
5592   int BestLoQuad = -1;
5593   unsigned MaxQuad = 1;
5594   for (unsigned i = 0; i < 4; ++i) {
5595     if (LoQuad[i] > MaxQuad) {
5596       BestLoQuad = i;
5597       MaxQuad = LoQuad[i];
5598     }
5599   }
5600
5601   int BestHiQuad = -1;
5602   MaxQuad = 1;
5603   for (unsigned i = 0; i < 4; ++i) {
5604     if (HiQuad[i] > MaxQuad) {
5605       BestHiQuad = i;
5606       MaxQuad = HiQuad[i];
5607     }
5608   }
5609
5610   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5611   // of the two input vectors, shuffle them into one input vector so only a
5612   // single pshufb instruction is necessary. If There are more than 2 input
5613   // quads, disable the next transformation since it does not help SSSE3.
5614   bool V1Used = InputQuads[0] || InputQuads[1];
5615   bool V2Used = InputQuads[2] || InputQuads[3];
5616   if (Subtarget->hasSSSE3()) {
5617     if (InputQuads.count() == 2 && V1Used && V2Used) {
5618       BestLoQuad = InputQuads[0] ? 0 : 1;
5619       BestHiQuad = InputQuads[2] ? 2 : 3;
5620     }
5621     if (InputQuads.count() > 2) {
5622       BestLoQuad = -1;
5623       BestHiQuad = -1;
5624     }
5625   }
5626
5627   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5628   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5629   // words from all 4 input quadwords.
5630   SDValue NewV;
5631   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5632     int MaskV[] = {
5633       BestLoQuad < 0 ? 0 : BestLoQuad,
5634       BestHiQuad < 0 ? 1 : BestHiQuad
5635     };
5636     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5637                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5638                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5639     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5640
5641     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5642     // source words for the shuffle, to aid later transformations.
5643     bool AllWordsInNewV = true;
5644     bool InOrder[2] = { true, true };
5645     for (unsigned i = 0; i != 8; ++i) {
5646       int idx = MaskVals[i];
5647       if (idx != (int)i)
5648         InOrder[i/4] = false;
5649       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5650         continue;
5651       AllWordsInNewV = false;
5652       break;
5653     }
5654
5655     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5656     if (AllWordsInNewV) {
5657       for (int i = 0; i != 8; ++i) {
5658         int idx = MaskVals[i];
5659         if (idx < 0)
5660           continue;
5661         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5662         if ((idx != i) && idx < 4)
5663           pshufhw = false;
5664         if ((idx != i) && idx > 3)
5665           pshuflw = false;
5666       }
5667       V1 = NewV;
5668       V2Used = false;
5669       BestLoQuad = 0;
5670       BestHiQuad = 1;
5671     }
5672
5673     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5674     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5675     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5676       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5677       unsigned TargetMask = 0;
5678       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5679                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5680       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5681       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5682                              getShufflePSHUFLWImmediate(SVOp);
5683       V1 = NewV.getOperand(0);
5684       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5685     }
5686   }
5687
5688   // If we have SSSE3, and all words of the result are from 1 input vector,
5689   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5690   // is present, fall back to case 4.
5691   if (Subtarget->hasSSSE3()) {
5692     SmallVector<SDValue,16> pshufbMask;
5693
5694     // If we have elements from both input vectors, set the high bit of the
5695     // shuffle mask element to zero out elements that come from V2 in the V1
5696     // mask, and elements that come from V1 in the V2 mask, so that the two
5697     // results can be OR'd together.
5698     bool TwoInputs = V1Used && V2Used;
5699     for (unsigned i = 0; i != 8; ++i) {
5700       int EltIdx = MaskVals[i] * 2;
5701       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5702       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5703       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5704       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5705     }
5706     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5707     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5708                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5709                                  MVT::v16i8, &pshufbMask[0], 16));
5710     if (!TwoInputs)
5711       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5712
5713     // Calculate the shuffle mask for the second input, shuffle it, and
5714     // OR it with the first shuffled input.
5715     pshufbMask.clear();
5716     for (unsigned i = 0; i != 8; ++i) {
5717       int EltIdx = MaskVals[i] * 2;
5718       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5719       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5720       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5721       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5722     }
5723     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5724     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5725                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5726                                  MVT::v16i8, &pshufbMask[0], 16));
5727     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5728     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5729   }
5730
5731   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5732   // and update MaskVals with new element order.
5733   std::bitset<8> InOrder;
5734   if (BestLoQuad >= 0) {
5735     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5736     for (int i = 0; i != 4; ++i) {
5737       int idx = MaskVals[i];
5738       if (idx < 0) {
5739         InOrder.set(i);
5740       } else if ((idx / 4) == BestLoQuad) {
5741         MaskV[i] = idx & 3;
5742         InOrder.set(i);
5743       }
5744     }
5745     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5746                                 &MaskV[0]);
5747
5748     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5749       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5750       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5751                                   NewV.getOperand(0),
5752                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5753     }
5754   }
5755
5756   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5757   // and update MaskVals with the new element order.
5758   if (BestHiQuad >= 0) {
5759     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5760     for (unsigned i = 4; i != 8; ++i) {
5761       int idx = MaskVals[i];
5762       if (idx < 0) {
5763         InOrder.set(i);
5764       } else if ((idx / 4) == BestHiQuad) {
5765         MaskV[i] = (idx & 3) + 4;
5766         InOrder.set(i);
5767       }
5768     }
5769     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5770                                 &MaskV[0]);
5771
5772     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5773       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5774       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5775                                   NewV.getOperand(0),
5776                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5777     }
5778   }
5779
5780   // In case BestHi & BestLo were both -1, which means each quadword has a word
5781   // from each of the four input quadwords, calculate the InOrder bitvector now
5782   // before falling through to the insert/extract cleanup.
5783   if (BestLoQuad == -1 && BestHiQuad == -1) {
5784     NewV = V1;
5785     for (int i = 0; i != 8; ++i)
5786       if (MaskVals[i] < 0 || MaskVals[i] == i)
5787         InOrder.set(i);
5788   }
5789
5790   // The other elements are put in the right place using pextrw and pinsrw.
5791   for (unsigned i = 0; i != 8; ++i) {
5792     if (InOrder[i])
5793       continue;
5794     int EltIdx = MaskVals[i];
5795     if (EltIdx < 0)
5796       continue;
5797     SDValue ExtOp = (EltIdx < 8) ?
5798       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5799                   DAG.getIntPtrConstant(EltIdx)) :
5800       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5801                   DAG.getIntPtrConstant(EltIdx - 8));
5802     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5803                        DAG.getIntPtrConstant(i));
5804   }
5805   return NewV;
5806 }
5807
5808 // v16i8 shuffles - Prefer shuffles in the following order:
5809 // 1. [ssse3] 1 x pshufb
5810 // 2. [ssse3] 2 x pshufb + 1 x por
5811 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5812 static
5813 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5814                                  SelectionDAG &DAG,
5815                                  const X86TargetLowering &TLI) {
5816   SDValue V1 = SVOp->getOperand(0);
5817   SDValue V2 = SVOp->getOperand(1);
5818   DebugLoc dl = SVOp->getDebugLoc();
5819   ArrayRef<int> MaskVals = SVOp->getMask();
5820
5821   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5822
5823   // If we have SSSE3, case 1 is generated when all result bytes come from
5824   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5825   // present, fall back to case 3.
5826
5827   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5828   if (TLI.getSubtarget()->hasSSSE3()) {
5829     SmallVector<SDValue,16> pshufbMask;
5830
5831     // If all result elements are from one input vector, then only translate
5832     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5833     //
5834     // Otherwise, we have elements from both input vectors, and must zero out
5835     // elements that come from V2 in the first mask, and V1 in the second mask
5836     // so that we can OR them together.
5837     for (unsigned i = 0; i != 16; ++i) {
5838       int EltIdx = MaskVals[i];
5839       if (EltIdx < 0 || EltIdx >= 16)
5840         EltIdx = 0x80;
5841       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5842     }
5843     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5844                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5845                                  MVT::v16i8, &pshufbMask[0], 16));
5846     if (V2IsUndef)
5847       return V1;
5848
5849     // Calculate the shuffle mask for the second input, shuffle it, and
5850     // OR it with the first shuffled input.
5851     pshufbMask.clear();
5852     for (unsigned i = 0; i != 16; ++i) {
5853       int EltIdx = MaskVals[i];
5854       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5855       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5856     }
5857     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5858                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5859                                  MVT::v16i8, &pshufbMask[0], 16));
5860     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5861   }
5862
5863   // No SSSE3 - Calculate in place words and then fix all out of place words
5864   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5865   // the 16 different words that comprise the two doublequadword input vectors.
5866   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5867   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5868   SDValue NewV = V1;
5869   for (int i = 0; i != 8; ++i) {
5870     int Elt0 = MaskVals[i*2];
5871     int Elt1 = MaskVals[i*2+1];
5872
5873     // This word of the result is all undef, skip it.
5874     if (Elt0 < 0 && Elt1 < 0)
5875       continue;
5876
5877     // This word of the result is already in the correct place, skip it.
5878     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5879       continue;
5880
5881     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5882     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5883     SDValue InsElt;
5884
5885     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5886     // using a single extract together, load it and store it.
5887     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5888       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5889                            DAG.getIntPtrConstant(Elt1 / 2));
5890       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5891                         DAG.getIntPtrConstant(i));
5892       continue;
5893     }
5894
5895     // If Elt1 is defined, extract it from the appropriate source.  If the
5896     // source byte is not also odd, shift the extracted word left 8 bits
5897     // otherwise clear the bottom 8 bits if we need to do an or.
5898     if (Elt1 >= 0) {
5899       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5900                            DAG.getIntPtrConstant(Elt1 / 2));
5901       if ((Elt1 & 1) == 0)
5902         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5903                              DAG.getConstant(8,
5904                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5905       else if (Elt0 >= 0)
5906         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5907                              DAG.getConstant(0xFF00, MVT::i16));
5908     }
5909     // If Elt0 is defined, extract it from the appropriate source.  If the
5910     // source byte is not also even, shift the extracted word right 8 bits. If
5911     // Elt1 was also defined, OR the extracted values together before
5912     // inserting them in the result.
5913     if (Elt0 >= 0) {
5914       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5915                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5916       if ((Elt0 & 1) != 0)
5917         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5918                               DAG.getConstant(8,
5919                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5920       else if (Elt1 >= 0)
5921         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5922                              DAG.getConstant(0x00FF, MVT::i16));
5923       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5924                          : InsElt0;
5925     }
5926     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5927                        DAG.getIntPtrConstant(i));
5928   }
5929   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5930 }
5931
5932 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5933 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5934 /// done when every pair / quad of shuffle mask elements point to elements in
5935 /// the right sequence. e.g.
5936 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5937 static
5938 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5939                                  SelectionDAG &DAG, DebugLoc dl) {
5940   MVT VT = SVOp->getValueType(0).getSimpleVT();
5941   unsigned NumElems = VT.getVectorNumElements();
5942   MVT NewVT;
5943   unsigned Scale;
5944   switch (VT.SimpleTy) {
5945   default: llvm_unreachable("Unexpected!");
5946   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
5947   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
5948   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
5949   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
5950   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
5951   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
5952   }
5953
5954   SmallVector<int, 8> MaskVec;
5955   for (unsigned i = 0; i != NumElems; i += Scale) {
5956     int StartIdx = -1;
5957     for (unsigned j = 0; j != Scale; ++j) {
5958       int EltIdx = SVOp->getMaskElt(i+j);
5959       if (EltIdx < 0)
5960         continue;
5961       if (StartIdx < 0)
5962         StartIdx = (EltIdx / Scale);
5963       if (EltIdx != (int)(StartIdx*Scale + j))
5964         return SDValue();
5965     }
5966     MaskVec.push_back(StartIdx);
5967   }
5968
5969   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
5970   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
5971   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5972 }
5973
5974 /// getVZextMovL - Return a zero-extending vector move low node.
5975 ///
5976 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5977                             SDValue SrcOp, SelectionDAG &DAG,
5978                             const X86Subtarget *Subtarget, DebugLoc dl) {
5979   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5980     LoadSDNode *LD = NULL;
5981     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5982       LD = dyn_cast<LoadSDNode>(SrcOp);
5983     if (!LD) {
5984       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5985       // instead.
5986       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5987       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5988           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5989           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5990           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5991         // PR2108
5992         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5993         return DAG.getNode(ISD::BITCAST, dl, VT,
5994                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5995                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5996                                                    OpVT,
5997                                                    SrcOp.getOperand(0)
5998                                                           .getOperand(0))));
5999       }
6000     }
6001   }
6002
6003   return DAG.getNode(ISD::BITCAST, dl, VT,
6004                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6005                                  DAG.getNode(ISD::BITCAST, dl,
6006                                              OpVT, SrcOp)));
6007 }
6008
6009 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6010 /// which could not be matched by any known target speficic shuffle
6011 static SDValue
6012 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6013
6014   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6015   if (NewOp.getNode())
6016     return NewOp;
6017
6018   EVT VT = SVOp->getValueType(0);
6019
6020   unsigned NumElems = VT.getVectorNumElements();
6021   unsigned NumLaneElems = NumElems / 2;
6022
6023   DebugLoc dl = SVOp->getDebugLoc();
6024   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6025   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6026   SDValue Output[2];
6027
6028   SmallVector<int, 16> Mask;
6029   for (unsigned l = 0; l < 2; ++l) {
6030     // Build a shuffle mask for the output, discovering on the fly which
6031     // input vectors to use as shuffle operands (recorded in InputUsed).
6032     // If building a suitable shuffle vector proves too hard, then bail
6033     // out with UseBuildVector set.
6034     bool UseBuildVector = false;
6035     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6036     unsigned LaneStart = l * NumLaneElems;
6037     for (unsigned i = 0; i != NumLaneElems; ++i) {
6038       // The mask element.  This indexes into the input.
6039       int Idx = SVOp->getMaskElt(i+LaneStart);
6040       if (Idx < 0) {
6041         // the mask element does not index into any input vector.
6042         Mask.push_back(-1);
6043         continue;
6044       }
6045
6046       // The input vector this mask element indexes into.
6047       int Input = Idx / NumLaneElems;
6048
6049       // Turn the index into an offset from the start of the input vector.
6050       Idx -= Input * NumLaneElems;
6051
6052       // Find or create a shuffle vector operand to hold this input.
6053       unsigned OpNo;
6054       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6055         if (InputUsed[OpNo] == Input)
6056           // This input vector is already an operand.
6057           break;
6058         if (InputUsed[OpNo] < 0) {
6059           // Create a new operand for this input vector.
6060           InputUsed[OpNo] = Input;
6061           break;
6062         }
6063       }
6064
6065       if (OpNo >= array_lengthof(InputUsed)) {
6066         // More than two input vectors used!  Give up on trying to create a
6067         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6068         UseBuildVector = true;
6069         break;
6070       }
6071
6072       // Add the mask index for the new shuffle vector.
6073       Mask.push_back(Idx + OpNo * NumLaneElems);
6074     }
6075
6076     if (UseBuildVector) {
6077       SmallVector<SDValue, 16> SVOps;
6078       for (unsigned i = 0; i != NumLaneElems; ++i) {
6079         // The mask element.  This indexes into the input.
6080         int Idx = SVOp->getMaskElt(i+LaneStart);
6081         if (Idx < 0) {
6082           SVOps.push_back(DAG.getUNDEF(EltVT));
6083           continue;
6084         }
6085
6086         // The input vector this mask element indexes into.
6087         int Input = Idx / NumElems;
6088
6089         // Turn the index into an offset from the start of the input vector.
6090         Idx -= Input * NumElems;
6091
6092         // Extract the vector element by hand.
6093         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6094                                     SVOp->getOperand(Input),
6095                                     DAG.getIntPtrConstant(Idx)));
6096       }
6097
6098       // Construct the output using a BUILD_VECTOR.
6099       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6100                               SVOps.size());
6101     } else if (InputUsed[0] < 0) {
6102       // No input vectors were used! The result is undefined.
6103       Output[l] = DAG.getUNDEF(NVT);
6104     } else {
6105       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6106                                         (InputUsed[0] % 2) * NumLaneElems,
6107                                         DAG, dl);
6108       // If only one input was used, use an undefined vector for the other.
6109       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6110         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6111                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6112       // At least one input vector was used. Create a new shuffle vector.
6113       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6114     }
6115
6116     Mask.clear();
6117   }
6118
6119   // Concatenate the result back
6120   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6121 }
6122
6123 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6124 /// 4 elements, and match them with several different shuffle types.
6125 static SDValue
6126 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6127   SDValue V1 = SVOp->getOperand(0);
6128   SDValue V2 = SVOp->getOperand(1);
6129   DebugLoc dl = SVOp->getDebugLoc();
6130   EVT VT = SVOp->getValueType(0);
6131
6132   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6133
6134   std::pair<int, int> Locs[4];
6135   int Mask1[] = { -1, -1, -1, -1 };
6136   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6137
6138   unsigned NumHi = 0;
6139   unsigned NumLo = 0;
6140   for (unsigned i = 0; i != 4; ++i) {
6141     int Idx = PermMask[i];
6142     if (Idx < 0) {
6143       Locs[i] = std::make_pair(-1, -1);
6144     } else {
6145       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6146       if (Idx < 4) {
6147         Locs[i] = std::make_pair(0, NumLo);
6148         Mask1[NumLo] = Idx;
6149         NumLo++;
6150       } else {
6151         Locs[i] = std::make_pair(1, NumHi);
6152         if (2+NumHi < 4)
6153           Mask1[2+NumHi] = Idx;
6154         NumHi++;
6155       }
6156     }
6157   }
6158
6159   if (NumLo <= 2 && NumHi <= 2) {
6160     // If no more than two elements come from either vector. This can be
6161     // implemented with two shuffles. First shuffle gather the elements.
6162     // The second shuffle, which takes the first shuffle as both of its
6163     // vector operands, put the elements into the right order.
6164     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6165
6166     int Mask2[] = { -1, -1, -1, -1 };
6167
6168     for (unsigned i = 0; i != 4; ++i)
6169       if (Locs[i].first != -1) {
6170         unsigned Idx = (i < 2) ? 0 : 4;
6171         Idx += Locs[i].first * 2 + Locs[i].second;
6172         Mask2[i] = Idx;
6173       }
6174
6175     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6176   }
6177
6178   if (NumLo == 3 || NumHi == 3) {
6179     // Otherwise, we must have three elements from one vector, call it X, and
6180     // one element from the other, call it Y.  First, use a shufps to build an
6181     // intermediate vector with the one element from Y and the element from X
6182     // that will be in the same half in the final destination (the indexes don't
6183     // matter). Then, use a shufps to build the final vector, taking the half
6184     // containing the element from Y from the intermediate, and the other half
6185     // from X.
6186     if (NumHi == 3) {
6187       // Normalize it so the 3 elements come from V1.
6188       CommuteVectorShuffleMask(PermMask, 4);
6189       std::swap(V1, V2);
6190     }
6191
6192     // Find the element from V2.
6193     unsigned HiIndex;
6194     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6195       int Val = PermMask[HiIndex];
6196       if (Val < 0)
6197         continue;
6198       if (Val >= 4)
6199         break;
6200     }
6201
6202     Mask1[0] = PermMask[HiIndex];
6203     Mask1[1] = -1;
6204     Mask1[2] = PermMask[HiIndex^1];
6205     Mask1[3] = -1;
6206     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6207
6208     if (HiIndex >= 2) {
6209       Mask1[0] = PermMask[0];
6210       Mask1[1] = PermMask[1];
6211       Mask1[2] = HiIndex & 1 ? 6 : 4;
6212       Mask1[3] = HiIndex & 1 ? 4 : 6;
6213       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6214     }
6215
6216     Mask1[0] = HiIndex & 1 ? 2 : 0;
6217     Mask1[1] = HiIndex & 1 ? 0 : 2;
6218     Mask1[2] = PermMask[2];
6219     Mask1[3] = PermMask[3];
6220     if (Mask1[2] >= 0)
6221       Mask1[2] += 4;
6222     if (Mask1[3] >= 0)
6223       Mask1[3] += 4;
6224     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6225   }
6226
6227   // Break it into (shuffle shuffle_hi, shuffle_lo).
6228   int LoMask[] = { -1, -1, -1, -1 };
6229   int HiMask[] = { -1, -1, -1, -1 };
6230
6231   int *MaskPtr = LoMask;
6232   unsigned MaskIdx = 0;
6233   unsigned LoIdx = 0;
6234   unsigned HiIdx = 2;
6235   for (unsigned i = 0; i != 4; ++i) {
6236     if (i == 2) {
6237       MaskPtr = HiMask;
6238       MaskIdx = 1;
6239       LoIdx = 0;
6240       HiIdx = 2;
6241     }
6242     int Idx = PermMask[i];
6243     if (Idx < 0) {
6244       Locs[i] = std::make_pair(-1, -1);
6245     } else if (Idx < 4) {
6246       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6247       MaskPtr[LoIdx] = Idx;
6248       LoIdx++;
6249     } else {
6250       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6251       MaskPtr[HiIdx] = Idx;
6252       HiIdx++;
6253     }
6254   }
6255
6256   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6257   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6258   int MaskOps[] = { -1, -1, -1, -1 };
6259   for (unsigned i = 0; i != 4; ++i)
6260     if (Locs[i].first != -1)
6261       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6262   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6263 }
6264
6265 static bool MayFoldVectorLoad(SDValue V) {
6266   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6267     V = V.getOperand(0);
6268   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6269     V = V.getOperand(0);
6270   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6271       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6272     // BUILD_VECTOR (load), undef
6273     V = V.getOperand(0);
6274   if (MayFoldLoad(V))
6275     return true;
6276   return false;
6277 }
6278
6279 // FIXME: the version above should always be used. Since there's
6280 // a bug where several vector shuffles can't be folded because the
6281 // DAG is not updated during lowering and a node claims to have two
6282 // uses while it only has one, use this version, and let isel match
6283 // another instruction if the load really happens to have more than
6284 // one use. Remove this version after this bug get fixed.
6285 // rdar://8434668, PR8156
6286 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6287   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6288     V = V.getOperand(0);
6289   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6290     V = V.getOperand(0);
6291   if (ISD::isNormalLoad(V.getNode()))
6292     return true;
6293   return false;
6294 }
6295
6296 static
6297 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6298   EVT VT = Op.getValueType();
6299
6300   // Canonizalize to v2f64.
6301   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6302   return DAG.getNode(ISD::BITCAST, dl, VT,
6303                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6304                                           V1, DAG));
6305 }
6306
6307 static
6308 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6309                         bool HasSSE2) {
6310   SDValue V1 = Op.getOperand(0);
6311   SDValue V2 = Op.getOperand(1);
6312   EVT VT = Op.getValueType();
6313
6314   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6315
6316   if (HasSSE2 && VT == MVT::v2f64)
6317     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6318
6319   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6320   return DAG.getNode(ISD::BITCAST, dl, VT,
6321                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6322                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6323                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6324 }
6325
6326 static
6327 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6328   SDValue V1 = Op.getOperand(0);
6329   SDValue V2 = Op.getOperand(1);
6330   EVT VT = Op.getValueType();
6331
6332   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6333          "unsupported shuffle type");
6334
6335   if (V2.getOpcode() == ISD::UNDEF)
6336     V2 = V1;
6337
6338   // v4i32 or v4f32
6339   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6340 }
6341
6342 static
6343 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6344   SDValue V1 = Op.getOperand(0);
6345   SDValue V2 = Op.getOperand(1);
6346   EVT VT = Op.getValueType();
6347   unsigned NumElems = VT.getVectorNumElements();
6348
6349   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6350   // operand of these instructions is only memory, so check if there's a
6351   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6352   // same masks.
6353   bool CanFoldLoad = false;
6354
6355   // Trivial case, when V2 comes from a load.
6356   if (MayFoldVectorLoad(V2))
6357     CanFoldLoad = true;
6358
6359   // When V1 is a load, it can be folded later into a store in isel, example:
6360   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6361   //    turns into:
6362   //  (MOVLPSmr addr:$src1, VR128:$src2)
6363   // So, recognize this potential and also use MOVLPS or MOVLPD
6364   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6365     CanFoldLoad = true;
6366
6367   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6368   if (CanFoldLoad) {
6369     if (HasSSE2 && NumElems == 2)
6370       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6371
6372     if (NumElems == 4)
6373       // If we don't care about the second element, proceed to use movss.
6374       if (SVOp->getMaskElt(1) != -1)
6375         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6376   }
6377
6378   // movl and movlp will both match v2i64, but v2i64 is never matched by
6379   // movl earlier because we make it strict to avoid messing with the movlp load
6380   // folding logic (see the code above getMOVLP call). Match it here then,
6381   // this is horrible, but will stay like this until we move all shuffle
6382   // matching to x86 specific nodes. Note that for the 1st condition all
6383   // types are matched with movsd.
6384   if (HasSSE2) {
6385     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6386     // as to remove this logic from here, as much as possible
6387     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6388       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6389     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6390   }
6391
6392   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6393
6394   // Invert the operand order and use SHUFPS to match it.
6395   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6396                               getShuffleSHUFImmediate(SVOp), DAG);
6397 }
6398
6399 SDValue
6400 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6401   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6402   EVT VT = Op.getValueType();
6403   DebugLoc dl = Op.getDebugLoc();
6404   SDValue V1 = Op.getOperand(0);
6405   SDValue V2 = Op.getOperand(1);
6406
6407   if (isZeroShuffle(SVOp))
6408     return getZeroVector(VT, Subtarget, DAG, dl);
6409
6410   // Handle splat operations
6411   if (SVOp->isSplat()) {
6412     unsigned NumElem = VT.getVectorNumElements();
6413     int Size = VT.getSizeInBits();
6414
6415     // Use vbroadcast whenever the splat comes from a foldable load
6416     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6417     if (Broadcast.getNode())
6418       return Broadcast;
6419
6420     // Handle splats by matching through known shuffle masks
6421     if ((Size == 128 && NumElem <= 4) ||
6422         (Size == 256 && NumElem < 8))
6423       return SDValue();
6424
6425     // All remaning splats are promoted to target supported vector shuffles.
6426     return PromoteSplat(SVOp, DAG);
6427   }
6428
6429   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6430   // do it!
6431   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6432       VT == MVT::v16i16 || VT == MVT::v32i8) {
6433     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6434     if (NewOp.getNode())
6435       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6436   } else if ((VT == MVT::v4i32 ||
6437              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6438     // FIXME: Figure out a cleaner way to do this.
6439     // Try to make use of movq to zero out the top part.
6440     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6441       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6442       if (NewOp.getNode()) {
6443         EVT NewVT = NewOp.getValueType();
6444         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6445                                NewVT, true, false))
6446           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6447                               DAG, Subtarget, dl);
6448       }
6449     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6450       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6451       if (NewOp.getNode()) {
6452         EVT NewVT = NewOp.getValueType();
6453         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6454           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6455                               DAG, Subtarget, dl);
6456       }
6457     }
6458   }
6459   return SDValue();
6460 }
6461
6462 SDValue
6463 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6464   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6465   SDValue V1 = Op.getOperand(0);
6466   SDValue V2 = Op.getOperand(1);
6467   EVT VT = Op.getValueType();
6468   DebugLoc dl = Op.getDebugLoc();
6469   unsigned NumElems = VT.getVectorNumElements();
6470   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6471   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6472   bool V1IsSplat = false;
6473   bool V2IsSplat = false;
6474   bool HasSSE2 = Subtarget->hasSSE2();
6475   bool HasAVX    = Subtarget->hasAVX();
6476   bool HasAVX2   = Subtarget->hasAVX2();
6477   MachineFunction &MF = DAG.getMachineFunction();
6478   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6479
6480   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6481
6482   if (V1IsUndef && V2IsUndef)
6483     return DAG.getUNDEF(VT);
6484
6485   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6486
6487   // Vector shuffle lowering takes 3 steps:
6488   //
6489   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6490   //    narrowing and commutation of operands should be handled.
6491   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6492   //    shuffle nodes.
6493   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6494   //    so the shuffle can be broken into other shuffles and the legalizer can
6495   //    try the lowering again.
6496   //
6497   // The general idea is that no vector_shuffle operation should be left to
6498   // be matched during isel, all of them must be converted to a target specific
6499   // node here.
6500
6501   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6502   // narrowing and commutation of operands should be handled. The actual code
6503   // doesn't include all of those, work in progress...
6504   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6505   if (NewOp.getNode())
6506     return NewOp;
6507
6508   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6509
6510   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6511   // unpckh_undef). Only use pshufd if speed is more important than size.
6512   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6513     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6514   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6515     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6516
6517   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6518       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6519     return getMOVDDup(Op, dl, V1, DAG);
6520
6521   if (isMOVHLPS_v_undef_Mask(M, VT))
6522     return getMOVHighToLow(Op, dl, DAG);
6523
6524   // Use to match splats
6525   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6526       (VT == MVT::v2f64 || VT == MVT::v2i64))
6527     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6528
6529   if (isPSHUFDMask(M, VT)) {
6530     // The actual implementation will match the mask in the if above and then
6531     // during isel it can match several different instructions, not only pshufd
6532     // as its name says, sad but true, emulate the behavior for now...
6533     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6534       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6535
6536     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6537
6538     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6539       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6540
6541     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6542       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6543
6544     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6545                                 TargetMask, DAG);
6546   }
6547
6548   // Check if this can be converted into a logical shift.
6549   bool isLeft = false;
6550   unsigned ShAmt = 0;
6551   SDValue ShVal;
6552   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6553   if (isShift && ShVal.hasOneUse()) {
6554     // If the shifted value has multiple uses, it may be cheaper to use
6555     // v_set0 + movlhps or movhlps, etc.
6556     EVT EltVT = VT.getVectorElementType();
6557     ShAmt *= EltVT.getSizeInBits();
6558     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6559   }
6560
6561   if (isMOVLMask(M, VT)) {
6562     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6563       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6564     if (!isMOVLPMask(M, VT)) {
6565       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6566         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6567
6568       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6569         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6570     }
6571   }
6572
6573   // FIXME: fold these into legal mask.
6574   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6575     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6576
6577   if (isMOVHLPSMask(M, VT))
6578     return getMOVHighToLow(Op, dl, DAG);
6579
6580   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6581     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6582
6583   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6584     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6585
6586   if (isMOVLPMask(M, VT))
6587     return getMOVLP(Op, dl, DAG, HasSSE2);
6588
6589   if (ShouldXformToMOVHLPS(M, VT) ||
6590       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6591     return CommuteVectorShuffle(SVOp, DAG);
6592
6593   if (isShift) {
6594     // No better options. Use a vshldq / vsrldq.
6595     EVT EltVT = VT.getVectorElementType();
6596     ShAmt *= EltVT.getSizeInBits();
6597     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6598   }
6599
6600   bool Commuted = false;
6601   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6602   // 1,1,1,1 -> v8i16 though.
6603   V1IsSplat = isSplatVector(V1.getNode());
6604   V2IsSplat = isSplatVector(V2.getNode());
6605
6606   // Canonicalize the splat or undef, if present, to be on the RHS.
6607   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6608     CommuteVectorShuffleMask(M, NumElems);
6609     std::swap(V1, V2);
6610     std::swap(V1IsSplat, V2IsSplat);
6611     Commuted = true;
6612   }
6613
6614   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6615     // Shuffling low element of v1 into undef, just return v1.
6616     if (V2IsUndef)
6617       return V1;
6618     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6619     // the instruction selector will not match, so get a canonical MOVL with
6620     // swapped operands to undo the commute.
6621     return getMOVL(DAG, dl, VT, V2, V1);
6622   }
6623
6624   if (isUNPCKLMask(M, VT, HasAVX2))
6625     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6626
6627   if (isUNPCKHMask(M, VT, HasAVX2))
6628     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6629
6630   if (V2IsSplat) {
6631     // Normalize mask so all entries that point to V2 points to its first
6632     // element then try to match unpck{h|l} again. If match, return a
6633     // new vector_shuffle with the corrected mask.p
6634     SmallVector<int, 8> NewMask(M.begin(), M.end());
6635     NormalizeMask(NewMask, NumElems);
6636     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6637       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6638     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6639       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6640   }
6641
6642   if (Commuted) {
6643     // Commute is back and try unpck* again.
6644     // FIXME: this seems wrong.
6645     CommuteVectorShuffleMask(M, NumElems);
6646     std::swap(V1, V2);
6647     std::swap(V1IsSplat, V2IsSplat);
6648     Commuted = false;
6649
6650     if (isUNPCKLMask(M, VT, HasAVX2))
6651       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6652
6653     if (isUNPCKHMask(M, VT, HasAVX2))
6654       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6655   }
6656
6657   // Normalize the node to match x86 shuffle ops if needed
6658   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6659     return CommuteVectorShuffle(SVOp, DAG);
6660
6661   // The checks below are all present in isShuffleMaskLegal, but they are
6662   // inlined here right now to enable us to directly emit target specific
6663   // nodes, and remove one by one until they don't return Op anymore.
6664
6665   if (isPALIGNRMask(M, VT, Subtarget))
6666     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6667                                 getShufflePALIGNRImmediate(SVOp),
6668                                 DAG);
6669
6670   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6671       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6672     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6673       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6674   }
6675
6676   if (isPSHUFHWMask(M, VT, HasAVX2))
6677     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6678                                 getShufflePSHUFHWImmediate(SVOp),
6679                                 DAG);
6680
6681   if (isPSHUFLWMask(M, VT, HasAVX2))
6682     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6683                                 getShufflePSHUFLWImmediate(SVOp),
6684                                 DAG);
6685
6686   if (isSHUFPMask(M, VT, HasAVX))
6687     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6688                                 getShuffleSHUFImmediate(SVOp), DAG);
6689
6690   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6691     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6692   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6693     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6694
6695   //===--------------------------------------------------------------------===//
6696   // Generate target specific nodes for 128 or 256-bit shuffles only
6697   // supported in the AVX instruction set.
6698   //
6699
6700   // Handle VMOVDDUPY permutations
6701   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6702     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6703
6704   // Handle VPERMILPS/D* permutations
6705   if (isVPERMILPMask(M, VT, HasAVX)) {
6706     if (HasAVX2 && VT == MVT::v8i32)
6707       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6708                                   getShuffleSHUFImmediate(SVOp), DAG);
6709     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6710                                 getShuffleSHUFImmediate(SVOp), DAG);
6711   }
6712
6713   // Handle VPERM2F128/VPERM2I128 permutations
6714   if (isVPERM2X128Mask(M, VT, HasAVX))
6715     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6716                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6717
6718   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6719   if (BlendOp.getNode())
6720     return BlendOp;
6721
6722   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6723     SmallVector<SDValue, 8> permclMask;
6724     for (unsigned i = 0; i != 8; ++i) {
6725       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6726     }
6727     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6728                                &permclMask[0], 8);
6729     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6730     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6731                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6732   }
6733
6734   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6735     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6736                                 getShuffleCLImmediate(SVOp), DAG);
6737
6738
6739   //===--------------------------------------------------------------------===//
6740   // Since no target specific shuffle was selected for this generic one,
6741   // lower it into other known shuffles. FIXME: this isn't true yet, but
6742   // this is the plan.
6743   //
6744
6745   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6746   if (VT == MVT::v8i16) {
6747     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6748     if (NewOp.getNode())
6749       return NewOp;
6750   }
6751
6752   if (VT == MVT::v16i8) {
6753     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6754     if (NewOp.getNode())
6755       return NewOp;
6756   }
6757
6758   // Handle all 128-bit wide vectors with 4 elements, and match them with
6759   // several different shuffle types.
6760   if (NumElems == 4 && VT.getSizeInBits() == 128)
6761     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6762
6763   // Handle general 256-bit shuffles
6764   if (VT.is256BitVector())
6765     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6766
6767   return SDValue();
6768 }
6769
6770 SDValue
6771 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6772                                                 SelectionDAG &DAG) const {
6773   EVT VT = Op.getValueType();
6774   DebugLoc dl = Op.getDebugLoc();
6775
6776   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6777     return SDValue();
6778
6779   if (VT.getSizeInBits() == 8) {
6780     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6781                                     Op.getOperand(0), Op.getOperand(1));
6782     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6783                                     DAG.getValueType(VT));
6784     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6785   }
6786
6787   if (VT.getSizeInBits() == 16) {
6788     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6789     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6790     if (Idx == 0)
6791       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6792                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6793                                      DAG.getNode(ISD::BITCAST, dl,
6794                                                  MVT::v4i32,
6795                                                  Op.getOperand(0)),
6796                                      Op.getOperand(1)));
6797     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6798                                     Op.getOperand(0), Op.getOperand(1));
6799     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6800                                     DAG.getValueType(VT));
6801     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6802   }
6803
6804   if (VT == MVT::f32) {
6805     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6806     // the result back to FR32 register. It's only worth matching if the
6807     // result has a single use which is a store or a bitcast to i32.  And in
6808     // the case of a store, it's not worth it if the index is a constant 0,
6809     // because a MOVSSmr can be used instead, which is smaller and faster.
6810     if (!Op.hasOneUse())
6811       return SDValue();
6812     SDNode *User = *Op.getNode()->use_begin();
6813     if ((User->getOpcode() != ISD::STORE ||
6814          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6815           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6816         (User->getOpcode() != ISD::BITCAST ||
6817          User->getValueType(0) != MVT::i32))
6818       return SDValue();
6819     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6820                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6821                                               Op.getOperand(0)),
6822                                               Op.getOperand(1));
6823     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6824   }
6825
6826   if (VT == MVT::i32 || VT == MVT::i64) {
6827     // ExtractPS/pextrq works with constant index.
6828     if (isa<ConstantSDNode>(Op.getOperand(1)))
6829       return Op;
6830   }
6831   return SDValue();
6832 }
6833
6834
6835 SDValue
6836 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6837                                            SelectionDAG &DAG) const {
6838   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6839     return SDValue();
6840
6841   SDValue Vec = Op.getOperand(0);
6842   EVT VecVT = Vec.getValueType();
6843
6844   // If this is a 256-bit vector result, first extract the 128-bit vector and
6845   // then extract the element from the 128-bit vector.
6846   if (VecVT.getSizeInBits() == 256) {
6847     DebugLoc dl = Op.getNode()->getDebugLoc();
6848     unsigned NumElems = VecVT.getVectorNumElements();
6849     SDValue Idx = Op.getOperand(1);
6850     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6851
6852     // Get the 128-bit vector.
6853     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6854
6855     if (IdxVal >= NumElems/2)
6856       IdxVal -= NumElems/2;
6857     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6858                        DAG.getConstant(IdxVal, MVT::i32));
6859   }
6860
6861   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6862
6863   if (Subtarget->hasSSE41()) {
6864     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6865     if (Res.getNode())
6866       return Res;
6867   }
6868
6869   EVT VT = Op.getValueType();
6870   DebugLoc dl = Op.getDebugLoc();
6871   // TODO: handle v16i8.
6872   if (VT.getSizeInBits() == 16) {
6873     SDValue Vec = Op.getOperand(0);
6874     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6875     if (Idx == 0)
6876       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6877                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6878                                      DAG.getNode(ISD::BITCAST, dl,
6879                                                  MVT::v4i32, Vec),
6880                                      Op.getOperand(1)));
6881     // Transform it so it match pextrw which produces a 32-bit result.
6882     EVT EltVT = MVT::i32;
6883     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6884                                     Op.getOperand(0), Op.getOperand(1));
6885     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6886                                     DAG.getValueType(VT));
6887     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6888   }
6889
6890   if (VT.getSizeInBits() == 32) {
6891     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6892     if (Idx == 0)
6893       return Op;
6894
6895     // SHUFPS the element to the lowest double word, then movss.
6896     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6897     EVT VVT = Op.getOperand(0).getValueType();
6898     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6899                                        DAG.getUNDEF(VVT), Mask);
6900     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6901                        DAG.getIntPtrConstant(0));
6902   }
6903
6904   if (VT.getSizeInBits() == 64) {
6905     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6906     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6907     //        to match extract_elt for f64.
6908     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6909     if (Idx == 0)
6910       return Op;
6911
6912     // UNPCKHPD the element to the lowest double word, then movsd.
6913     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6914     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6915     int Mask[2] = { 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   return SDValue();
6924 }
6925
6926 SDValue
6927 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6928                                                SelectionDAG &DAG) const {
6929   EVT VT = Op.getValueType();
6930   EVT EltVT = VT.getVectorElementType();
6931   DebugLoc dl = Op.getDebugLoc();
6932
6933   SDValue N0 = Op.getOperand(0);
6934   SDValue N1 = Op.getOperand(1);
6935   SDValue N2 = Op.getOperand(2);
6936
6937   if (VT.getSizeInBits() == 256)
6938     return SDValue();
6939
6940   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6941       isa<ConstantSDNode>(N2)) {
6942     unsigned Opc;
6943     if (VT == MVT::v8i16)
6944       Opc = X86ISD::PINSRW;
6945     else if (VT == MVT::v16i8)
6946       Opc = X86ISD::PINSRB;
6947     else
6948       Opc = X86ISD::PINSRB;
6949
6950     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6951     // argument.
6952     if (N1.getValueType() != MVT::i32)
6953       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6954     if (N2.getValueType() != MVT::i32)
6955       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6956     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6957   }
6958
6959   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6960     // Bits [7:6] of the constant are the source select.  This will always be
6961     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6962     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6963     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6964     // Bits [5:4] of the constant are the destination select.  This is the
6965     //  value of the incoming immediate.
6966     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6967     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6968     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6969     // Create this as a scalar to vector..
6970     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6971     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6972   }
6973
6974   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
6975     // PINSR* works with constant index.
6976     return Op;
6977   }
6978   return SDValue();
6979 }
6980
6981 SDValue
6982 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6983   EVT VT = Op.getValueType();
6984   EVT EltVT = VT.getVectorElementType();
6985
6986   DebugLoc dl = Op.getDebugLoc();
6987   SDValue N0 = Op.getOperand(0);
6988   SDValue N1 = Op.getOperand(1);
6989   SDValue N2 = Op.getOperand(2);
6990
6991   // If this is a 256-bit vector result, first extract the 128-bit vector,
6992   // insert the element into the extracted half and then place it back.
6993   if (VT.getSizeInBits() == 256) {
6994     if (!isa<ConstantSDNode>(N2))
6995       return SDValue();
6996
6997     // Get the desired 128-bit vector half.
6998     unsigned NumElems = VT.getVectorNumElements();
6999     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7000     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7001
7002     // Insert the element into the desired half.
7003     bool Upper = IdxVal >= NumElems/2;
7004     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7005                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7006
7007     // Insert the changed part back to the 256-bit vector
7008     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7009   }
7010
7011   if (Subtarget->hasSSE41())
7012     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7013
7014   if (EltVT == MVT::i8)
7015     return SDValue();
7016
7017   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7018     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7019     // as its second argument.
7020     if (N1.getValueType() != MVT::i32)
7021       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7022     if (N2.getValueType() != MVT::i32)
7023       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7024     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7025   }
7026   return SDValue();
7027 }
7028
7029 SDValue
7030 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7031   LLVMContext *Context = DAG.getContext();
7032   DebugLoc dl = Op.getDebugLoc();
7033   EVT OpVT = Op.getValueType();
7034
7035   // If this is a 256-bit vector result, first insert into a 128-bit
7036   // vector and then insert into the 256-bit vector.
7037   if (OpVT.getSizeInBits() > 128) {
7038     // Insert into a 128-bit vector.
7039     EVT VT128 = EVT::getVectorVT(*Context,
7040                                  OpVT.getVectorElementType(),
7041                                  OpVT.getVectorNumElements() / 2);
7042
7043     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7044
7045     // Insert the 128-bit vector.
7046     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7047   }
7048
7049   if (OpVT == MVT::v1i64 &&
7050       Op.getOperand(0).getValueType() == MVT::i64)
7051     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7052
7053   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7054   assert(OpVT.getSizeInBits() == 128 && "Expected an SSE type!");
7055   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7056                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7057 }
7058
7059 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7060 // a simple subregister reference or explicit instructions to grab
7061 // upper bits of a vector.
7062 SDValue
7063 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7064   if (Subtarget->hasAVX()) {
7065     DebugLoc dl = Op.getNode()->getDebugLoc();
7066     SDValue Vec = Op.getNode()->getOperand(0);
7067     SDValue Idx = Op.getNode()->getOperand(1);
7068
7069     if (Op.getNode()->getValueType(0).getSizeInBits() == 128 &&
7070         Vec.getNode()->getValueType(0).getSizeInBits() == 256 &&
7071         isa<ConstantSDNode>(Idx)) {
7072       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7073       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7074     }
7075   }
7076   return SDValue();
7077 }
7078
7079 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7080 // simple superregister reference or explicit instructions to insert
7081 // the upper bits of a vector.
7082 SDValue
7083 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7084   if (Subtarget->hasAVX()) {
7085     DebugLoc dl = Op.getNode()->getDebugLoc();
7086     SDValue Vec = Op.getNode()->getOperand(0);
7087     SDValue SubVec = Op.getNode()->getOperand(1);
7088     SDValue Idx = Op.getNode()->getOperand(2);
7089
7090     if (Op.getNode()->getValueType(0).getSizeInBits() == 256 &&
7091         SubVec.getNode()->getValueType(0).getSizeInBits() == 128 &&
7092         isa<ConstantSDNode>(Idx)) {
7093       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7094       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7095     }
7096   }
7097   return SDValue();
7098 }
7099
7100 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7101 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7102 // one of the above mentioned nodes. It has to be wrapped because otherwise
7103 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7104 // be used to form addressing mode. These wrapped nodes will be selected
7105 // into MOV32ri.
7106 SDValue
7107 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7108   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7109
7110   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7111   // global base reg.
7112   unsigned char OpFlag = 0;
7113   unsigned WrapperKind = X86ISD::Wrapper;
7114   CodeModel::Model M = getTargetMachine().getCodeModel();
7115
7116   if (Subtarget->isPICStyleRIPRel() &&
7117       (M == CodeModel::Small || M == CodeModel::Kernel))
7118     WrapperKind = X86ISD::WrapperRIP;
7119   else if (Subtarget->isPICStyleGOT())
7120     OpFlag = X86II::MO_GOTOFF;
7121   else if (Subtarget->isPICStyleStubPIC())
7122     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7123
7124   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7125                                              CP->getAlignment(),
7126                                              CP->getOffset(), OpFlag);
7127   DebugLoc DL = CP->getDebugLoc();
7128   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7129   // With PIC, the address is actually $g + Offset.
7130   if (OpFlag) {
7131     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7132                          DAG.getNode(X86ISD::GlobalBaseReg,
7133                                      DebugLoc(), getPointerTy()),
7134                          Result);
7135   }
7136
7137   return Result;
7138 }
7139
7140 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7141   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7142
7143   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7144   // global base reg.
7145   unsigned char OpFlag = 0;
7146   unsigned WrapperKind = X86ISD::Wrapper;
7147   CodeModel::Model M = getTargetMachine().getCodeModel();
7148
7149   if (Subtarget->isPICStyleRIPRel() &&
7150       (M == CodeModel::Small || M == CodeModel::Kernel))
7151     WrapperKind = X86ISD::WrapperRIP;
7152   else if (Subtarget->isPICStyleGOT())
7153     OpFlag = X86II::MO_GOTOFF;
7154   else if (Subtarget->isPICStyleStubPIC())
7155     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7156
7157   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7158                                           OpFlag);
7159   DebugLoc DL = JT->getDebugLoc();
7160   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7161
7162   // With PIC, the address is actually $g + Offset.
7163   if (OpFlag)
7164     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7165                          DAG.getNode(X86ISD::GlobalBaseReg,
7166                                      DebugLoc(), getPointerTy()),
7167                          Result);
7168
7169   return Result;
7170 }
7171
7172 SDValue
7173 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7174   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7175
7176   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7177   // global base reg.
7178   unsigned char OpFlag = 0;
7179   unsigned WrapperKind = X86ISD::Wrapper;
7180   CodeModel::Model M = getTargetMachine().getCodeModel();
7181
7182   if (Subtarget->isPICStyleRIPRel() &&
7183       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7184     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7185       OpFlag = X86II::MO_GOTPCREL;
7186     WrapperKind = X86ISD::WrapperRIP;
7187   } else if (Subtarget->isPICStyleGOT()) {
7188     OpFlag = X86II::MO_GOT;
7189   } else if (Subtarget->isPICStyleStubPIC()) {
7190     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7191   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7192     OpFlag = X86II::MO_DARWIN_NONLAZY;
7193   }
7194
7195   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7196
7197   DebugLoc DL = Op.getDebugLoc();
7198   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7199
7200
7201   // With PIC, the address is actually $g + Offset.
7202   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7203       !Subtarget->is64Bit()) {
7204     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7205                          DAG.getNode(X86ISD::GlobalBaseReg,
7206                                      DebugLoc(), getPointerTy()),
7207                          Result);
7208   }
7209
7210   // For symbols that require a load from a stub to get the address, emit the
7211   // load.
7212   if (isGlobalStubReference(OpFlag))
7213     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7214                          MachinePointerInfo::getGOT(), false, false, false, 0);
7215
7216   return Result;
7217 }
7218
7219 SDValue
7220 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7221   // Create the TargetBlockAddressAddress node.
7222   unsigned char OpFlags =
7223     Subtarget->ClassifyBlockAddressReference();
7224   CodeModel::Model M = getTargetMachine().getCodeModel();
7225   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7226   DebugLoc dl = Op.getDebugLoc();
7227   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7228                                        /*isTarget=*/true, OpFlags);
7229
7230   if (Subtarget->isPICStyleRIPRel() &&
7231       (M == CodeModel::Small || M == CodeModel::Kernel))
7232     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7233   else
7234     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7235
7236   // With PIC, the address is actually $g + Offset.
7237   if (isGlobalRelativeToPICBase(OpFlags)) {
7238     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7239                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7240                          Result);
7241   }
7242
7243   return Result;
7244 }
7245
7246 SDValue
7247 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7248                                       int64_t Offset,
7249                                       SelectionDAG &DAG) const {
7250   // Create the TargetGlobalAddress node, folding in the constant
7251   // offset if it is legal.
7252   unsigned char OpFlags =
7253     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7254   CodeModel::Model M = getTargetMachine().getCodeModel();
7255   SDValue Result;
7256   if (OpFlags == X86II::MO_NO_FLAG &&
7257       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7258     // A direct static reference to a global.
7259     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7260     Offset = 0;
7261   } else {
7262     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7263   }
7264
7265   if (Subtarget->isPICStyleRIPRel() &&
7266       (M == CodeModel::Small || M == CodeModel::Kernel))
7267     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7268   else
7269     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7270
7271   // With PIC, the address is actually $g + Offset.
7272   if (isGlobalRelativeToPICBase(OpFlags)) {
7273     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7274                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7275                          Result);
7276   }
7277
7278   // For globals that require a load from a stub to get the address, emit the
7279   // load.
7280   if (isGlobalStubReference(OpFlags))
7281     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7282                          MachinePointerInfo::getGOT(), false, false, false, 0);
7283
7284   // If there was a non-zero offset that we didn't fold, create an explicit
7285   // addition for it.
7286   if (Offset != 0)
7287     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7288                          DAG.getConstant(Offset, getPointerTy()));
7289
7290   return Result;
7291 }
7292
7293 SDValue
7294 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7295   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7296   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7297   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7298 }
7299
7300 static SDValue
7301 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7302            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7303            unsigned char OperandFlags, bool LocalDynamic = false) {
7304   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7305   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7306   DebugLoc dl = GA->getDebugLoc();
7307   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7308                                            GA->getValueType(0),
7309                                            GA->getOffset(),
7310                                            OperandFlags);
7311
7312   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7313                                            : X86ISD::TLSADDR;
7314
7315   if (InFlag) {
7316     SDValue Ops[] = { Chain,  TGA, *InFlag };
7317     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7318   } else {
7319     SDValue Ops[]  = { Chain, TGA };
7320     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7321   }
7322
7323   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7324   MFI->setAdjustsStack(true);
7325
7326   SDValue Flag = Chain.getValue(1);
7327   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7328 }
7329
7330 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7331 static SDValue
7332 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7333                                 const EVT PtrVT) {
7334   SDValue InFlag;
7335   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7336   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7337                                      DAG.getNode(X86ISD::GlobalBaseReg,
7338                                                  DebugLoc(), PtrVT), InFlag);
7339   InFlag = Chain.getValue(1);
7340
7341   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7342 }
7343
7344 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7345 static SDValue
7346 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7347                                 const EVT PtrVT) {
7348   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7349                     X86::RAX, X86II::MO_TLSGD);
7350 }
7351
7352 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7353                                            SelectionDAG &DAG,
7354                                            const EVT PtrVT,
7355                                            bool is64Bit) {
7356   DebugLoc dl = GA->getDebugLoc();
7357
7358   // Get the start address of the TLS block for this module.
7359   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7360       .getInfo<X86MachineFunctionInfo>();
7361   MFI->incNumLocalDynamicTLSAccesses();
7362
7363   SDValue Base;
7364   if (is64Bit) {
7365     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7366                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7367   } else {
7368     SDValue InFlag;
7369     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7370         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7371     InFlag = Chain.getValue(1);
7372     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7373                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7374   }
7375
7376   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7377   // of Base.
7378
7379   // Build x@dtpoff.
7380   unsigned char OperandFlags = X86II::MO_DTPOFF;
7381   unsigned WrapperKind = X86ISD::Wrapper;
7382   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7383                                            GA->getValueType(0),
7384                                            GA->getOffset(), OperandFlags);
7385   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7386
7387   // Add x@dtpoff with the base.
7388   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7389 }
7390
7391 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7392 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7393                                    const EVT PtrVT, TLSModel::Model model,
7394                                    bool is64Bit, bool isPIC) {
7395   DebugLoc dl = GA->getDebugLoc();
7396
7397   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7398   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7399                                                          is64Bit ? 257 : 256));
7400
7401   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7402                                       DAG.getIntPtrConstant(0),
7403                                       MachinePointerInfo(Ptr),
7404                                       false, false, false, 0);
7405
7406   unsigned char OperandFlags = 0;
7407   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7408   // initialexec.
7409   unsigned WrapperKind = X86ISD::Wrapper;
7410   if (model == TLSModel::LocalExec) {
7411     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7412   } else if (model == TLSModel::InitialExec) {
7413     if (is64Bit) {
7414       OperandFlags = X86II::MO_GOTTPOFF;
7415       WrapperKind = X86ISD::WrapperRIP;
7416     } else {
7417       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7418     }
7419   } else {
7420     llvm_unreachable("Unexpected model");
7421   }
7422
7423   // emit "addl x@ntpoff,%eax" (local exec)
7424   // or "addl x@indntpoff,%eax" (initial exec)
7425   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7426   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7427                                            GA->getValueType(0),
7428                                            GA->getOffset(), OperandFlags);
7429   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7430
7431   if (model == TLSModel::InitialExec) {
7432     if (isPIC && !is64Bit) {
7433       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7434                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7435                            Offset);
7436     }
7437
7438     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7439                          MachinePointerInfo::getGOT(), false, false, false,
7440                          0);
7441   }
7442
7443   // The address of the thread local variable is the add of the thread
7444   // pointer with the offset of the variable.
7445   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7446 }
7447
7448 SDValue
7449 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7450
7451   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7452   const GlobalValue *GV = GA->getGlobal();
7453
7454   if (Subtarget->isTargetELF()) {
7455     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7456
7457     switch (model) {
7458       case TLSModel::GeneralDynamic:
7459         if (Subtarget->is64Bit())
7460           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7461         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7462       case TLSModel::LocalDynamic:
7463         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7464                                            Subtarget->is64Bit());
7465       case TLSModel::InitialExec:
7466       case TLSModel::LocalExec:
7467         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7468                                    Subtarget->is64Bit(),
7469                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7470     }
7471     llvm_unreachable("Unknown TLS model.");
7472   }
7473
7474   if (Subtarget->isTargetDarwin()) {
7475     // Darwin only has one model of TLS.  Lower to that.
7476     unsigned char OpFlag = 0;
7477     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7478                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7479
7480     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7481     // global base reg.
7482     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7483                   !Subtarget->is64Bit();
7484     if (PIC32)
7485       OpFlag = X86II::MO_TLVP_PIC_BASE;
7486     else
7487       OpFlag = X86II::MO_TLVP;
7488     DebugLoc DL = Op.getDebugLoc();
7489     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7490                                                 GA->getValueType(0),
7491                                                 GA->getOffset(), OpFlag);
7492     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7493
7494     // With PIC32, the address is actually $g + Offset.
7495     if (PIC32)
7496       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7497                            DAG.getNode(X86ISD::GlobalBaseReg,
7498                                        DebugLoc(), getPointerTy()),
7499                            Offset);
7500
7501     // Lowering the machine isd will make sure everything is in the right
7502     // location.
7503     SDValue Chain = DAG.getEntryNode();
7504     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7505     SDValue Args[] = { Chain, Offset };
7506     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7507
7508     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7509     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7510     MFI->setAdjustsStack(true);
7511
7512     // And our return value (tls address) is in the standard call return value
7513     // location.
7514     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7515     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7516                               Chain.getValue(1));
7517   }
7518
7519   if (Subtarget->isTargetWindows()) {
7520     // Just use the implicit TLS architecture
7521     // Need to generate someting similar to:
7522     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7523     //                                  ; from TEB
7524     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7525     //   mov     rcx, qword [rdx+rcx*8]
7526     //   mov     eax, .tls$:tlsvar
7527     //   [rax+rcx] contains the address
7528     // Windows 64bit: gs:0x58
7529     // Windows 32bit: fs:__tls_array
7530
7531     // If GV is an alias then use the aliasee for determining
7532     // thread-localness.
7533     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7534       GV = GA->resolveAliasedGlobal(false);
7535     DebugLoc dl = GA->getDebugLoc();
7536     SDValue Chain = DAG.getEntryNode();
7537
7538     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7539     // %gs:0x58 (64-bit).
7540     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7541                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7542                                                              256)
7543                                         : Type::getInt32PtrTy(*DAG.getContext(),
7544                                                               257));
7545
7546     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7547                                         Subtarget->is64Bit()
7548                                         ? DAG.getIntPtrConstant(0x58)
7549                                         : DAG.getExternalSymbol("_tls_array",
7550                                                                 getPointerTy()),
7551                                         MachinePointerInfo(Ptr),
7552                                         false, false, false, 0);
7553
7554     // Load the _tls_index variable
7555     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7556     if (Subtarget->is64Bit())
7557       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7558                            IDX, MachinePointerInfo(), MVT::i32,
7559                            false, false, 0);
7560     else
7561       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7562                         false, false, false, 0);
7563
7564     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7565                                     getPointerTy());
7566     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7567
7568     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7569     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7570                       false, false, false, 0);
7571
7572     // Get the offset of start of .tls section
7573     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7574                                              GA->getValueType(0),
7575                                              GA->getOffset(), X86II::MO_SECREL);
7576     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7577
7578     // The address of the thread local variable is the add of the thread
7579     // pointer with the offset of the variable.
7580     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7581   }
7582
7583   llvm_unreachable("TLS not implemented for this target.");
7584 }
7585
7586
7587 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7588 /// and take a 2 x i32 value to shift plus a shift amount.
7589 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7590   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7591   EVT VT = Op.getValueType();
7592   unsigned VTBits = VT.getSizeInBits();
7593   DebugLoc dl = Op.getDebugLoc();
7594   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7595   SDValue ShOpLo = Op.getOperand(0);
7596   SDValue ShOpHi = Op.getOperand(1);
7597   SDValue ShAmt  = Op.getOperand(2);
7598   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7599                                      DAG.getConstant(VTBits - 1, MVT::i8))
7600                        : DAG.getConstant(0, VT);
7601
7602   SDValue Tmp2, Tmp3;
7603   if (Op.getOpcode() == ISD::SHL_PARTS) {
7604     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7605     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7606   } else {
7607     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7608     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7609   }
7610
7611   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7612                                 DAG.getConstant(VTBits, MVT::i8));
7613   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7614                              AndNode, DAG.getConstant(0, MVT::i8));
7615
7616   SDValue Hi, Lo;
7617   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7618   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7619   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7620
7621   if (Op.getOpcode() == ISD::SHL_PARTS) {
7622     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7623     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7624   } else {
7625     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7626     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7627   }
7628
7629   SDValue Ops[2] = { Lo, Hi };
7630   return DAG.getMergeValues(Ops, 2, dl);
7631 }
7632
7633 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7634                                            SelectionDAG &DAG) const {
7635   EVT SrcVT = Op.getOperand(0).getValueType();
7636
7637   if (SrcVT.isVector())
7638     return SDValue();
7639
7640   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7641          "Unknown SINT_TO_FP to lower!");
7642
7643   // These are really Legal; return the operand so the caller accepts it as
7644   // Legal.
7645   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7646     return Op;
7647   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7648       Subtarget->is64Bit()) {
7649     return Op;
7650   }
7651
7652   DebugLoc dl = Op.getDebugLoc();
7653   unsigned Size = SrcVT.getSizeInBits()/8;
7654   MachineFunction &MF = DAG.getMachineFunction();
7655   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7656   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7657   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7658                                StackSlot,
7659                                MachinePointerInfo::getFixedStack(SSFI),
7660                                false, false, 0);
7661   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7662 }
7663
7664 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7665                                      SDValue StackSlot,
7666                                      SelectionDAG &DAG) const {
7667   // Build the FILD
7668   DebugLoc DL = Op.getDebugLoc();
7669   SDVTList Tys;
7670   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7671   if (useSSE)
7672     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7673   else
7674     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7675
7676   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7677
7678   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7679   MachineMemOperand *MMO;
7680   if (FI) {
7681     int SSFI = FI->getIndex();
7682     MMO =
7683       DAG.getMachineFunction()
7684       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7685                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7686   } else {
7687     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7688     StackSlot = StackSlot.getOperand(1);
7689   }
7690   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7691   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7692                                            X86ISD::FILD, DL,
7693                                            Tys, Ops, array_lengthof(Ops),
7694                                            SrcVT, MMO);
7695
7696   if (useSSE) {
7697     Chain = Result.getValue(1);
7698     SDValue InFlag = Result.getValue(2);
7699
7700     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7701     // shouldn't be necessary except that RFP cannot be live across
7702     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7703     MachineFunction &MF = DAG.getMachineFunction();
7704     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7705     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7706     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7707     Tys = DAG.getVTList(MVT::Other);
7708     SDValue Ops[] = {
7709       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7710     };
7711     MachineMemOperand *MMO =
7712       DAG.getMachineFunction()
7713       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7714                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7715
7716     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7717                                     Ops, array_lengthof(Ops),
7718                                     Op.getValueType(), MMO);
7719     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7720                          MachinePointerInfo::getFixedStack(SSFI),
7721                          false, false, false, 0);
7722   }
7723
7724   return Result;
7725 }
7726
7727 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7728 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7729                                                SelectionDAG &DAG) const {
7730   // This algorithm is not obvious. Here it is what we're trying to output:
7731   /*
7732      movq       %rax,  %xmm0
7733      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7734      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7735      #ifdef __SSE3__
7736        haddpd   %xmm0, %xmm0          
7737      #else
7738        pshufd   $0x4e, %xmm0, %xmm1 
7739        addpd    %xmm1, %xmm0
7740      #endif
7741   */
7742
7743   DebugLoc dl = Op.getDebugLoc();
7744   LLVMContext *Context = DAG.getContext();
7745
7746   // Build some magic constants.
7747   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7748   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7749   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7750
7751   SmallVector<Constant*,2> CV1;
7752   CV1.push_back(
7753         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7754   CV1.push_back(
7755         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7756   Constant *C1 = ConstantVector::get(CV1);
7757   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7758
7759   // Load the 64-bit value into an XMM register.
7760   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7761                             Op.getOperand(0));
7762   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7763                               MachinePointerInfo::getConstantPool(),
7764                               false, false, false, 16);
7765   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7766                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7767                               CLod0);
7768
7769   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7770                               MachinePointerInfo::getConstantPool(),
7771                               false, false, false, 16);
7772   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7773   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7774   SDValue Result;
7775
7776   if (Subtarget->hasSSE3()) {
7777     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7778     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7779   } else {
7780     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7781     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7782                                            S2F, 0x4E, DAG);
7783     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7784                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7785                          Sub);
7786   }
7787
7788   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7789                      DAG.getIntPtrConstant(0));
7790 }
7791
7792 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7793 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7794                                                SelectionDAG &DAG) const {
7795   DebugLoc dl = Op.getDebugLoc();
7796   // FP constant to bias correct the final result.
7797   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7798                                    MVT::f64);
7799
7800   // Load the 32-bit value into an XMM register.
7801   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7802                              Op.getOperand(0));
7803
7804   // Zero out the upper parts of the register.
7805   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7806
7807   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7808                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7809                      DAG.getIntPtrConstant(0));
7810
7811   // Or the load with the bias.
7812   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7813                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7814                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7815                                                    MVT::v2f64, Load)),
7816                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7817                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7818                                                    MVT::v2f64, Bias)));
7819   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7820                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7821                    DAG.getIntPtrConstant(0));
7822
7823   // Subtract the bias.
7824   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7825
7826   // Handle final rounding.
7827   EVT DestVT = Op.getValueType();
7828
7829   if (DestVT.bitsLT(MVT::f64))
7830     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7831                        DAG.getIntPtrConstant(0));
7832   if (DestVT.bitsGT(MVT::f64))
7833     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7834
7835   // Handle final rounding.
7836   return Sub;
7837 }
7838
7839 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7840                                            SelectionDAG &DAG) const {
7841   SDValue N0 = Op.getOperand(0);
7842   DebugLoc dl = Op.getDebugLoc();
7843
7844   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7845   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7846   // the optimization here.
7847   if (DAG.SignBitIsZero(N0))
7848     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7849
7850   EVT SrcVT = N0.getValueType();
7851   EVT DstVT = Op.getValueType();
7852   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7853     return LowerUINT_TO_FP_i64(Op, DAG);
7854   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7855     return LowerUINT_TO_FP_i32(Op, DAG);
7856   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7857     return SDValue();
7858
7859   // Make a 64-bit buffer, and use it to build an FILD.
7860   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7861   if (SrcVT == MVT::i32) {
7862     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7863     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7864                                      getPointerTy(), StackSlot, WordOff);
7865     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7866                                   StackSlot, MachinePointerInfo(),
7867                                   false, false, 0);
7868     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7869                                   OffsetSlot, MachinePointerInfo(),
7870                                   false, false, 0);
7871     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7872     return Fild;
7873   }
7874
7875   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7876   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7877                                StackSlot, MachinePointerInfo(),
7878                                false, false, 0);
7879   // For i64 source, we need to add the appropriate power of 2 if the input
7880   // was negative.  This is the same as the optimization in
7881   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7882   // we must be careful to do the computation in x87 extended precision, not
7883   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7884   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7885   MachineMemOperand *MMO =
7886     DAG.getMachineFunction()
7887     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7888                           MachineMemOperand::MOLoad, 8, 8);
7889
7890   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7891   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7892   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7893                                          MVT::i64, MMO);
7894
7895   APInt FF(32, 0x5F800000ULL);
7896
7897   // Check whether the sign bit is set.
7898   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7899                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7900                                  ISD::SETLT);
7901
7902   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7903   SDValue FudgePtr = DAG.getConstantPool(
7904                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7905                                          getPointerTy());
7906
7907   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7908   SDValue Zero = DAG.getIntPtrConstant(0);
7909   SDValue Four = DAG.getIntPtrConstant(4);
7910   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7911                                Zero, Four);
7912   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7913
7914   // Load the value out, extending it from f32 to f80.
7915   // FIXME: Avoid the extend by constructing the right constant pool?
7916   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7917                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7918                                  MVT::f32, false, false, 4);
7919   // Extend everything to 80 bits to force it to be done on x87.
7920   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7921   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7922 }
7923
7924 std::pair<SDValue,SDValue> X86TargetLowering::
7925 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7926   DebugLoc DL = Op.getDebugLoc();
7927
7928   EVT DstTy = Op.getValueType();
7929
7930   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7931     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7932     DstTy = MVT::i64;
7933   }
7934
7935   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7936          DstTy.getSimpleVT() >= MVT::i16 &&
7937          "Unknown FP_TO_INT to lower!");
7938
7939   // These are really Legal.
7940   if (DstTy == MVT::i32 &&
7941       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7942     return std::make_pair(SDValue(), SDValue());
7943   if (Subtarget->is64Bit() &&
7944       DstTy == MVT::i64 &&
7945       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7946     return std::make_pair(SDValue(), SDValue());
7947
7948   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
7949   // stack slot, or into the FTOL runtime function.
7950   MachineFunction &MF = DAG.getMachineFunction();
7951   unsigned MemSize = DstTy.getSizeInBits()/8;
7952   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7953   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7954
7955   unsigned Opc;
7956   if (!IsSigned && isIntegerTypeFTOL(DstTy))
7957     Opc = X86ISD::WIN_FTOL;
7958   else
7959     switch (DstTy.getSimpleVT().SimpleTy) {
7960     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7961     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7962     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7963     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7964     }
7965
7966   SDValue Chain = DAG.getEntryNode();
7967   SDValue Value = Op.getOperand(0);
7968   EVT TheVT = Op.getOperand(0).getValueType();
7969   // FIXME This causes a redundant load/store if the SSE-class value is already
7970   // in memory, such as if it is on the callstack.
7971   if (isScalarFPTypeInSSEReg(TheVT)) {
7972     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7973     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7974                          MachinePointerInfo::getFixedStack(SSFI),
7975                          false, false, 0);
7976     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7977     SDValue Ops[] = {
7978       Chain, StackSlot, DAG.getValueType(TheVT)
7979     };
7980
7981     MachineMemOperand *MMO =
7982       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7983                               MachineMemOperand::MOLoad, MemSize, MemSize);
7984     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7985                                     DstTy, MMO);
7986     Chain = Value.getValue(1);
7987     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7988     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7989   }
7990
7991   MachineMemOperand *MMO =
7992     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7993                             MachineMemOperand::MOStore, MemSize, MemSize);
7994
7995   if (Opc != X86ISD::WIN_FTOL) {
7996     // Build the FP_TO_INT*_IN_MEM
7997     SDValue Ops[] = { Chain, Value, StackSlot };
7998     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7999                                            Ops, 3, DstTy, MMO);
8000     return std::make_pair(FIST, StackSlot);
8001   } else {
8002     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8003       DAG.getVTList(MVT::Other, MVT::Glue),
8004       Chain, Value);
8005     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8006       MVT::i32, ftol.getValue(1));
8007     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8008       MVT::i32, eax.getValue(2));
8009     SDValue Ops[] = { eax, edx };
8010     SDValue pair = IsReplace
8011       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8012       : DAG.getMergeValues(Ops, 2, DL);
8013     return std::make_pair(pair, SDValue());
8014   }
8015 }
8016
8017 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8018                                            SelectionDAG &DAG) const {
8019   if (Op.getValueType().isVector())
8020     return SDValue();
8021
8022   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8023     /*IsSigned=*/ true, /*IsReplace=*/ false);
8024   SDValue FIST = Vals.first, StackSlot = Vals.second;
8025   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8026   if (FIST.getNode() == 0) return Op;
8027
8028   if (StackSlot.getNode())
8029     // Load the result.
8030     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8031                        FIST, StackSlot, MachinePointerInfo(),
8032                        false, false, false, 0);
8033
8034   // The node is the result.
8035   return FIST;
8036 }
8037
8038 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8039                                            SelectionDAG &DAG) const {
8040   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8041     /*IsSigned=*/ false, /*IsReplace=*/ false);
8042   SDValue FIST = Vals.first, StackSlot = Vals.second;
8043   assert(FIST.getNode() && "Unexpected failure");
8044
8045   if (StackSlot.getNode())
8046     // Load the result.
8047     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8048                        FIST, StackSlot, MachinePointerInfo(),
8049                        false, false, false, 0);
8050
8051   // The node is the result.
8052   return FIST;
8053 }
8054
8055 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8056                                      SelectionDAG &DAG) const {
8057   LLVMContext *Context = DAG.getContext();
8058   DebugLoc dl = Op.getDebugLoc();
8059   EVT VT = Op.getValueType();
8060   EVT EltVT = VT;
8061   if (VT.isVector())
8062     EltVT = VT.getVectorElementType();
8063   Constant *C;
8064   if (EltVT == MVT::f64) {
8065     C = ConstantVector::getSplat(2, 
8066                 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8067   } else {
8068     C = ConstantVector::getSplat(4,
8069                ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8070   }
8071   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8072   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8073                              MachinePointerInfo::getConstantPool(),
8074                              false, false, false, 16);
8075   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8076 }
8077
8078 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8079   LLVMContext *Context = DAG.getContext();
8080   DebugLoc dl = Op.getDebugLoc();
8081   EVT VT = Op.getValueType();
8082   EVT EltVT = VT;
8083   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8084   if (VT.isVector()) {
8085     EltVT = VT.getVectorElementType();
8086     NumElts = VT.getVectorNumElements();
8087   }
8088   Constant *C;
8089   if (EltVT == MVT::f64)
8090     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8091   else
8092     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8093   C = ConstantVector::getSplat(NumElts, C);
8094   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8095   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8096                              MachinePointerInfo::getConstantPool(),
8097                              false, false, false, 16);
8098   if (VT.isVector()) {
8099     MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
8100     return DAG.getNode(ISD::BITCAST, dl, VT,
8101                        DAG.getNode(ISD::XOR, dl, XORVT,
8102                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8103                                                Op.getOperand(0)),
8104                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8105   }
8106
8107   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8108 }
8109
8110 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8111   LLVMContext *Context = DAG.getContext();
8112   SDValue Op0 = Op.getOperand(0);
8113   SDValue Op1 = Op.getOperand(1);
8114   DebugLoc dl = Op.getDebugLoc();
8115   EVT VT = Op.getValueType();
8116   EVT SrcVT = Op1.getValueType();
8117
8118   // If second operand is smaller, extend it first.
8119   if (SrcVT.bitsLT(VT)) {
8120     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8121     SrcVT = VT;
8122   }
8123   // And if it is bigger, shrink it first.
8124   if (SrcVT.bitsGT(VT)) {
8125     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8126     SrcVT = VT;
8127   }
8128
8129   // At this point the operands and the result should have the same
8130   // type, and that won't be f80 since that is not custom lowered.
8131
8132   // First get the sign bit of second operand.
8133   SmallVector<Constant*,4> CV;
8134   if (SrcVT == MVT::f64) {
8135     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8136     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8137   } else {
8138     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8139     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8140     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8141     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8142   }
8143   Constant *C = ConstantVector::get(CV);
8144   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8145   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8146                               MachinePointerInfo::getConstantPool(),
8147                               false, false, false, 16);
8148   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8149
8150   // Shift sign bit right or left if the two operands have different types.
8151   if (SrcVT.bitsGT(VT)) {
8152     // Op0 is MVT::f32, Op1 is MVT::f64.
8153     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8154     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8155                           DAG.getConstant(32, MVT::i32));
8156     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8157     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8158                           DAG.getIntPtrConstant(0));
8159   }
8160
8161   // Clear first operand sign bit.
8162   CV.clear();
8163   if (VT == MVT::f64) {
8164     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8165     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8166   } else {
8167     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8168     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8169     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8170     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8171   }
8172   C = ConstantVector::get(CV);
8173   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8174   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8175                               MachinePointerInfo::getConstantPool(),
8176                               false, false, false, 16);
8177   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8178
8179   // Or the value with the sign bit.
8180   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8181 }
8182
8183 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8184   SDValue N0 = Op.getOperand(0);
8185   DebugLoc dl = Op.getDebugLoc();
8186   EVT VT = Op.getValueType();
8187
8188   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8189   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8190                                   DAG.getConstant(1, VT));
8191   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8192 }
8193
8194 /// Emit nodes that will be selected as "test Op0,Op0", or something
8195 /// equivalent.
8196 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8197                                     SelectionDAG &DAG) const {
8198   DebugLoc dl = Op.getDebugLoc();
8199
8200   // CF and OF aren't always set the way we want. Determine which
8201   // of these we need.
8202   bool NeedCF = false;
8203   bool NeedOF = false;
8204   switch (X86CC) {
8205   default: break;
8206   case X86::COND_A: case X86::COND_AE:
8207   case X86::COND_B: case X86::COND_BE:
8208     NeedCF = true;
8209     break;
8210   case X86::COND_G: case X86::COND_GE:
8211   case X86::COND_L: case X86::COND_LE:
8212   case X86::COND_O: case X86::COND_NO:
8213     NeedOF = true;
8214     break;
8215   }
8216
8217   // See if we can use the EFLAGS value from the operand instead of
8218   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8219   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8220   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8221     // Emit a CMP with 0, which is the TEST pattern.
8222     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8223                        DAG.getConstant(0, Op.getValueType()));
8224
8225   unsigned Opcode = 0;
8226   unsigned NumOperands = 0;
8227   switch (Op.getNode()->getOpcode()) {
8228   case ISD::ADD:
8229     // Due to an isel shortcoming, be conservative if this add is likely to be
8230     // selected as part of a load-modify-store instruction. When the root node
8231     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8232     // uses of other nodes in the match, such as the ADD in this case. This
8233     // leads to the ADD being left around and reselected, with the result being
8234     // two adds in the output.  Alas, even if none our users are stores, that
8235     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8236     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8237     // climbing the DAG back to the root, and it doesn't seem to be worth the
8238     // effort.
8239     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8240          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8241       if (UI->getOpcode() != ISD::CopyToReg &&
8242           UI->getOpcode() != ISD::SETCC &&
8243           UI->getOpcode() != ISD::STORE)
8244         goto default_case;
8245
8246     if (ConstantSDNode *C =
8247         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8248       // An add of one will be selected as an INC.
8249       if (C->getAPIntValue() == 1) {
8250         Opcode = X86ISD::INC;
8251         NumOperands = 1;
8252         break;
8253       }
8254
8255       // An add of negative one (subtract of one) will be selected as a DEC.
8256       if (C->getAPIntValue().isAllOnesValue()) {
8257         Opcode = X86ISD::DEC;
8258         NumOperands = 1;
8259         break;
8260       }
8261     }
8262
8263     // Otherwise use a regular EFLAGS-setting add.
8264     Opcode = X86ISD::ADD;
8265     NumOperands = 2;
8266     break;
8267   case ISD::AND: {
8268     // If the primary and result isn't used, don't bother using X86ISD::AND,
8269     // because a TEST instruction will be better.
8270     bool NonFlagUse = false;
8271     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8272            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8273       SDNode *User = *UI;
8274       unsigned UOpNo = UI.getOperandNo();
8275       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8276         // Look pass truncate.
8277         UOpNo = User->use_begin().getOperandNo();
8278         User = *User->use_begin();
8279       }
8280
8281       if (User->getOpcode() != ISD::BRCOND &&
8282           User->getOpcode() != ISD::SETCC &&
8283           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8284         NonFlagUse = true;
8285         break;
8286       }
8287     }
8288
8289     if (!NonFlagUse)
8290       break;
8291   }
8292     // FALL THROUGH
8293   case ISD::SUB:
8294   case ISD::OR:
8295   case ISD::XOR:
8296     // Due to the ISEL shortcoming noted above, be conservative if this op is
8297     // likely to be selected as part of a load-modify-store instruction.
8298     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8299            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8300       if (UI->getOpcode() == ISD::STORE)
8301         goto default_case;
8302
8303     // Otherwise use a regular EFLAGS-setting instruction.
8304     switch (Op.getNode()->getOpcode()) {
8305     default: llvm_unreachable("unexpected operator!");
8306     case ISD::SUB:
8307       // If the only use of SUB is EFLAGS, use CMP instead.
8308       if (Op.hasOneUse())
8309         Opcode = X86ISD::CMP;
8310       else
8311         Opcode = X86ISD::SUB;
8312       break;
8313     case ISD::OR:  Opcode = X86ISD::OR;  break;
8314     case ISD::XOR: Opcode = X86ISD::XOR; break;
8315     case ISD::AND: Opcode = X86ISD::AND; break;
8316     }
8317
8318     NumOperands = 2;
8319     break;
8320   case X86ISD::ADD:
8321   case X86ISD::SUB:
8322   case X86ISD::INC:
8323   case X86ISD::DEC:
8324   case X86ISD::OR:
8325   case X86ISD::XOR:
8326   case X86ISD::AND:
8327     return SDValue(Op.getNode(), 1);
8328   default:
8329   default_case:
8330     break;
8331   }
8332
8333   if (Opcode == 0)
8334     // Emit a CMP with 0, which is the TEST pattern.
8335     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8336                        DAG.getConstant(0, Op.getValueType()));
8337
8338   if (Opcode == X86ISD::CMP) {
8339     SDValue New = DAG.getNode(Opcode, dl, MVT::i32, Op.getOperand(0),
8340                               Op.getOperand(1));
8341     // We can't replace usage of SUB with CMP.
8342     // The SUB node will be removed later because there is no use of it.
8343     return SDValue(New.getNode(), 0);
8344   }
8345
8346   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8347   SmallVector<SDValue, 4> Ops;
8348   for (unsigned i = 0; i != NumOperands; ++i)
8349     Ops.push_back(Op.getOperand(i));
8350
8351   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8352   DAG.ReplaceAllUsesWith(Op, New);
8353   return SDValue(New.getNode(), 1);
8354 }
8355
8356 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8357 /// equivalent.
8358 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8359                                    SelectionDAG &DAG) const {
8360   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8361     if (C->getAPIntValue() == 0)
8362       return EmitTest(Op0, X86CC, DAG);
8363
8364   DebugLoc dl = Op0.getDebugLoc();
8365   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8366 }
8367
8368 /// Convert a comparison if required by the subtarget.
8369 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8370                                                  SelectionDAG &DAG) const {
8371   // If the subtarget does not support the FUCOMI instruction, floating-point
8372   // comparisons have to be converted.
8373   if (Subtarget->hasCMov() ||
8374       Cmp.getOpcode() != X86ISD::CMP ||
8375       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8376       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8377     return Cmp;
8378
8379   // The instruction selector will select an FUCOM instruction instead of
8380   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8381   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8382   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8383   DebugLoc dl = Cmp.getDebugLoc();
8384   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8385   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8386   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8387                             DAG.getConstant(8, MVT::i8));
8388   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8389   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8390 }
8391
8392 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8393 /// if it's possible.
8394 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8395                                      DebugLoc dl, SelectionDAG &DAG) const {
8396   SDValue Op0 = And.getOperand(0);
8397   SDValue Op1 = And.getOperand(1);
8398   if (Op0.getOpcode() == ISD::TRUNCATE)
8399     Op0 = Op0.getOperand(0);
8400   if (Op1.getOpcode() == ISD::TRUNCATE)
8401     Op1 = Op1.getOperand(0);
8402
8403   SDValue LHS, RHS;
8404   if (Op1.getOpcode() == ISD::SHL)
8405     std::swap(Op0, Op1);
8406   if (Op0.getOpcode() == ISD::SHL) {
8407     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8408       if (And00C->getZExtValue() == 1) {
8409         // If we looked past a truncate, check that it's only truncating away
8410         // known zeros.
8411         unsigned BitWidth = Op0.getValueSizeInBits();
8412         unsigned AndBitWidth = And.getValueSizeInBits();
8413         if (BitWidth > AndBitWidth) {
8414           APInt Zeros, Ones;
8415           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8416           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8417             return SDValue();
8418         }
8419         LHS = Op1;
8420         RHS = Op0.getOperand(1);
8421       }
8422   } else if (Op1.getOpcode() == ISD::Constant) {
8423     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8424     uint64_t AndRHSVal = AndRHS->getZExtValue();
8425     SDValue AndLHS = Op0;
8426
8427     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8428       LHS = AndLHS.getOperand(0);
8429       RHS = AndLHS.getOperand(1);
8430     }
8431
8432     // Use BT if the immediate can't be encoded in a TEST instruction.
8433     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8434       LHS = AndLHS;
8435       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8436     }
8437   }
8438
8439   if (LHS.getNode()) {
8440     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8441     // instruction.  Since the shift amount is in-range-or-undefined, we know
8442     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8443     // the encoding for the i16 version is larger than the i32 version.
8444     // Also promote i16 to i32 for performance / code size reason.
8445     if (LHS.getValueType() == MVT::i8 ||
8446         LHS.getValueType() == MVT::i16)
8447       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8448
8449     // If the operand types disagree, extend the shift amount to match.  Since
8450     // BT ignores high bits (like shifts) we can use anyextend.
8451     if (LHS.getValueType() != RHS.getValueType())
8452       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8453
8454     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8455     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8456     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8457                        DAG.getConstant(Cond, MVT::i8), BT);
8458   }
8459
8460   return SDValue();
8461 }
8462
8463 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8464
8465   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8466
8467   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8468   SDValue Op0 = Op.getOperand(0);
8469   SDValue Op1 = Op.getOperand(1);
8470   DebugLoc dl = Op.getDebugLoc();
8471   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8472
8473   // Optimize to BT if possible.
8474   // Lower (X & (1 << N)) == 0 to BT(X, N).
8475   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8476   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8477   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8478       Op1.getOpcode() == ISD::Constant &&
8479       cast<ConstantSDNode>(Op1)->isNullValue() &&
8480       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8481     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8482     if (NewSetCC.getNode())
8483       return NewSetCC;
8484   }
8485
8486   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8487   // these.
8488   if (Op1.getOpcode() == ISD::Constant &&
8489       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8490        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8491       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8492
8493     // If the input is a setcc, then reuse the input setcc or use a new one with
8494     // the inverted condition.
8495     if (Op0.getOpcode() == X86ISD::SETCC) {
8496       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8497       bool Invert = (CC == ISD::SETNE) ^
8498         cast<ConstantSDNode>(Op1)->isNullValue();
8499       if (!Invert) return Op0;
8500
8501       CCode = X86::GetOppositeBranchCondition(CCode);
8502       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8503                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8504     }
8505   }
8506
8507   bool isFP = Op1.getValueType().isFloatingPoint();
8508   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8509   if (X86CC == X86::COND_INVALID)
8510     return SDValue();
8511
8512   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8513   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8514   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8515                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8516 }
8517
8518 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8519 // ones, and then concatenate the result back.
8520 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8521   EVT VT = Op.getValueType();
8522
8523   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8524          "Unsupported value type for operation");
8525
8526   unsigned NumElems = VT.getVectorNumElements();
8527   DebugLoc dl = Op.getDebugLoc();
8528   SDValue CC = Op.getOperand(2);
8529
8530   // Extract the LHS vectors
8531   SDValue LHS = Op.getOperand(0);
8532   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8533   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8534
8535   // Extract the RHS vectors
8536   SDValue RHS = Op.getOperand(1);
8537   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8538   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8539
8540   // Issue the operation on the smaller types and concatenate the result back
8541   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8542   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8543   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8544                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8545                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8546 }
8547
8548
8549 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8550   SDValue Cond;
8551   SDValue Op0 = Op.getOperand(0);
8552   SDValue Op1 = Op.getOperand(1);
8553   SDValue CC = Op.getOperand(2);
8554   EVT VT = Op.getValueType();
8555   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8556   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8557   DebugLoc dl = Op.getDebugLoc();
8558
8559   if (isFP) {
8560     unsigned SSECC = 8;
8561     EVT EltVT = Op0.getValueType().getVectorElementType();
8562     assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8563
8564     bool Swap = false;
8565
8566     // SSE Condition code mapping:
8567     //  0 - EQ
8568     //  1 - LT
8569     //  2 - LE
8570     //  3 - UNORD
8571     //  4 - NEQ
8572     //  5 - NLT
8573     //  6 - NLE
8574     //  7 - ORD
8575     switch (SetCCOpcode) {
8576     default: break;
8577     case ISD::SETOEQ:
8578     case ISD::SETEQ:  SSECC = 0; break;
8579     case ISD::SETOGT:
8580     case ISD::SETGT: Swap = true; // Fallthrough
8581     case ISD::SETLT:
8582     case ISD::SETOLT: SSECC = 1; break;
8583     case ISD::SETOGE:
8584     case ISD::SETGE: Swap = true; // Fallthrough
8585     case ISD::SETLE:
8586     case ISD::SETOLE: SSECC = 2; break;
8587     case ISD::SETUO:  SSECC = 3; break;
8588     case ISD::SETUNE:
8589     case ISD::SETNE:  SSECC = 4; break;
8590     case ISD::SETULE: Swap = true;
8591     case ISD::SETUGE: SSECC = 5; break;
8592     case ISD::SETULT: Swap = true;
8593     case ISD::SETUGT: SSECC = 6; break;
8594     case ISD::SETO:   SSECC = 7; break;
8595     }
8596     if (Swap)
8597       std::swap(Op0, Op1);
8598
8599     // In the two special cases we can't handle, emit two comparisons.
8600     if (SSECC == 8) {
8601       if (SetCCOpcode == ISD::SETUEQ) {
8602         SDValue UNORD, EQ;
8603         UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8604                             DAG.getConstant(3, MVT::i8));
8605         EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8606                          DAG.getConstant(0, MVT::i8));
8607         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8608       }
8609       if (SetCCOpcode == ISD::SETONE) {
8610         SDValue ORD, NEQ;
8611         ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8612                           DAG.getConstant(7, MVT::i8));
8613         NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8614                           DAG.getConstant(4, MVT::i8));
8615         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8616       }
8617       llvm_unreachable("Illegal FP comparison");
8618     }
8619     // Handle all other FP comparisons here.
8620     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8621                        DAG.getConstant(SSECC, MVT::i8));
8622   }
8623
8624   // Break 256-bit integer vector compare into smaller ones.
8625   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8626     return Lower256IntVSETCC(Op, DAG);
8627
8628   // We are handling one of the integer comparisons here.  Since SSE only has
8629   // GT and EQ comparisons for integer, swapping operands and multiple
8630   // operations may be required for some comparisons.
8631   unsigned Opc = 0;
8632   bool Swap = false, Invert = false, FlipSigns = false;
8633
8634   switch (SetCCOpcode) {
8635   default: break;
8636   case ISD::SETNE:  Invert = true;
8637   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8638   case ISD::SETLT:  Swap = true;
8639   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8640   case ISD::SETGE:  Swap = true;
8641   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8642   case ISD::SETULT: Swap = true;
8643   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8644   case ISD::SETUGE: Swap = true;
8645   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8646   }
8647   if (Swap)
8648     std::swap(Op0, Op1);
8649
8650   // Check that the operation in question is available (most are plain SSE2,
8651   // but PCMPGTQ and PCMPEQQ have different requirements).
8652   if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8653     return SDValue();
8654   if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8655     return SDValue();
8656
8657   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8658   // bits of the inputs before performing those operations.
8659   if (FlipSigns) {
8660     EVT EltVT = VT.getVectorElementType();
8661     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8662                                       EltVT);
8663     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8664     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8665                                     SignBits.size());
8666     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8667     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8668   }
8669
8670   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8671
8672   // If the logical-not of the result is required, perform that now.
8673   if (Invert)
8674     Result = DAG.getNOT(dl, Result, VT);
8675
8676   return Result;
8677 }
8678
8679 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8680 static bool isX86LogicalCmp(SDValue Op) {
8681   unsigned Opc = Op.getNode()->getOpcode();
8682   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8683       Opc == X86ISD::SAHF)
8684     return true;
8685   if (Op.getResNo() == 1 &&
8686       (Opc == X86ISD::ADD ||
8687        Opc == X86ISD::SUB ||
8688        Opc == X86ISD::ADC ||
8689        Opc == X86ISD::SBB ||
8690        Opc == X86ISD::SMUL ||
8691        Opc == X86ISD::UMUL ||
8692        Opc == X86ISD::INC ||
8693        Opc == X86ISD::DEC ||
8694        Opc == X86ISD::OR ||
8695        Opc == X86ISD::XOR ||
8696        Opc == X86ISD::AND))
8697     return true;
8698
8699   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8700     return true;
8701
8702   return false;
8703 }
8704
8705 static bool isZero(SDValue V) {
8706   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8707   return C && C->isNullValue();
8708 }
8709
8710 static bool isAllOnes(SDValue V) {
8711   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8712   return C && C->isAllOnesValue();
8713 }
8714
8715 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8716   bool addTest = true;
8717   SDValue Cond  = Op.getOperand(0);
8718   SDValue Op1 = Op.getOperand(1);
8719   SDValue Op2 = Op.getOperand(2);
8720   DebugLoc DL = Op.getDebugLoc();
8721   SDValue CC;
8722
8723   if (Cond.getOpcode() == ISD::SETCC) {
8724     SDValue NewCond = LowerSETCC(Cond, DAG);
8725     if (NewCond.getNode())
8726       Cond = NewCond;
8727   }
8728
8729   // Handle the following cases related to max and min:
8730   // (a > b) ? (a-b) : 0
8731   // (a >= b) ? (a-b) : 0
8732   // (b < a) ? (a-b) : 0
8733   // (b <= a) ? (a-b) : 0
8734   // Comparison is removed to use EFLAGS from SUB.
8735   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2))
8736     if (Cond.getOpcode() == X86ISD::SETCC &&
8737         Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8738         (Op1.getOpcode() == ISD::SUB || Op1.getOpcode() == X86ISD::SUB) &&
8739         C->getAPIntValue() == 0) {
8740       SDValue Cmp = Cond.getOperand(1);
8741       unsigned CC = cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8742       if ((DAG.isEqualTo(Op1.getOperand(0), Cmp.getOperand(0)) &&
8743            DAG.isEqualTo(Op1.getOperand(1), Cmp.getOperand(1)) &&
8744            (CC == X86::COND_G || CC == X86::COND_GE ||
8745             CC == X86::COND_A || CC == X86::COND_AE)) ||
8746           (DAG.isEqualTo(Op1.getOperand(0), Cmp.getOperand(1)) &&
8747            DAG.isEqualTo(Op1.getOperand(1), Cmp.getOperand(0)) &&
8748            (CC == X86::COND_L || CC == X86::COND_LE ||
8749             CC == X86::COND_B || CC == X86::COND_BE))) {
8750
8751         if (Op1.getOpcode() == ISD::SUB) {
8752           SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i32);
8753           SDValue New = DAG.getNode(X86ISD::SUB, DL, VTs,
8754                                     Op1.getOperand(0), Op1.getOperand(1));
8755           DAG.ReplaceAllUsesWith(Op1, New);
8756           Op1 = New;
8757         }
8758
8759         SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8760         unsigned NewCC = (CC == X86::COND_G || CC == X86::COND_GE ||
8761                           CC == X86::COND_L ||
8762                           CC == X86::COND_LE) ? X86::COND_GE : X86::COND_AE;
8763         SDValue Ops[] = { Op2, Op1, DAG.getConstant(NewCC, MVT::i8),
8764                           SDValue(Op1.getNode(), 1) };
8765         return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8766       }
8767     }
8768
8769   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8770   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8771   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8772   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8773   if (Cond.getOpcode() == X86ISD::SETCC &&
8774       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8775       isZero(Cond.getOperand(1).getOperand(1))) {
8776     SDValue Cmp = Cond.getOperand(1);
8777
8778     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8779
8780     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8781         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8782       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8783
8784       SDValue CmpOp0 = Cmp.getOperand(0);
8785       // Apply further optimizations for special cases
8786       // (select (x != 0), -1, 0) -> neg & sbb
8787       // (select (x == 0), 0, -1) -> neg & sbb
8788       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8789         if (YC->isNullValue() && 
8790             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8791           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8792           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs, 
8793                                     DAG.getConstant(0, CmpOp0.getValueType()), 
8794                                     CmpOp0);
8795           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8796                                     DAG.getConstant(X86::COND_B, MVT::i8),
8797                                     SDValue(Neg.getNode(), 1));
8798           return Res;
8799         }
8800
8801       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8802                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8803       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8804
8805       SDValue Res =   // Res = 0 or -1.
8806         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8807                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8808
8809       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8810         Res = DAG.getNOT(DL, Res, Res.getValueType());
8811
8812       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8813       if (N2C == 0 || !N2C->isNullValue())
8814         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8815       return Res;
8816     }
8817   }
8818
8819   // Look past (and (setcc_carry (cmp ...)), 1).
8820   if (Cond.getOpcode() == ISD::AND &&
8821       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8822     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8823     if (C && C->getAPIntValue() == 1)
8824       Cond = Cond.getOperand(0);
8825   }
8826
8827   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8828   // setting operand in place of the X86ISD::SETCC.
8829   unsigned CondOpcode = Cond.getOpcode();
8830   if (CondOpcode == X86ISD::SETCC ||
8831       CondOpcode == X86ISD::SETCC_CARRY) {
8832     CC = Cond.getOperand(0);
8833
8834     SDValue Cmp = Cond.getOperand(1);
8835     unsigned Opc = Cmp.getOpcode();
8836     EVT VT = Op.getValueType();
8837
8838     bool IllegalFPCMov = false;
8839     if (VT.isFloatingPoint() && !VT.isVector() &&
8840         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8841       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8842
8843     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8844         Opc == X86ISD::BT) { // FIXME
8845       Cond = Cmp;
8846       addTest = false;
8847     }
8848   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8849              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8850              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8851               Cond.getOperand(0).getValueType() != MVT::i8)) {
8852     SDValue LHS = Cond.getOperand(0);
8853     SDValue RHS = Cond.getOperand(1);
8854     unsigned X86Opcode;
8855     unsigned X86Cond;
8856     SDVTList VTs;
8857     switch (CondOpcode) {
8858     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8859     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8860     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8861     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8862     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8863     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8864     default: llvm_unreachable("unexpected overflowing operator");
8865     }
8866     if (CondOpcode == ISD::UMULO)
8867       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8868                           MVT::i32);
8869     else
8870       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8871
8872     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8873
8874     if (CondOpcode == ISD::UMULO)
8875       Cond = X86Op.getValue(2);
8876     else
8877       Cond = X86Op.getValue(1);
8878
8879     CC = DAG.getConstant(X86Cond, MVT::i8);
8880     addTest = false;
8881   }
8882
8883   if (addTest) {
8884     // Look pass the truncate.
8885     if (Cond.getOpcode() == ISD::TRUNCATE)
8886       Cond = Cond.getOperand(0);
8887
8888     // We know the result of AND is compared against zero. Try to match
8889     // it to BT.
8890     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8891       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8892       if (NewSetCC.getNode()) {
8893         CC = NewSetCC.getOperand(0);
8894         Cond = NewSetCC.getOperand(1);
8895         addTest = false;
8896       }
8897     }
8898   }
8899
8900   if (addTest) {
8901     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8902     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8903   }
8904
8905   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8906   // a <  b ?  0 : -1 -> RES = setcc_carry
8907   // a >= b ? -1 :  0 -> RES = setcc_carry
8908   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8909   if (Cond.getOpcode() == X86ISD::CMP) {
8910     Cond = ConvertCmpIfNecessary(Cond, DAG);
8911     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8912
8913     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8914         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8915       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8916                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8917       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8918         return DAG.getNOT(DL, Res, Res.getValueType());
8919       return Res;
8920     }
8921   }
8922
8923   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8924   // condition is true.
8925   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8926   SDValue Ops[] = { Op2, Op1, CC, Cond };
8927   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8928 }
8929
8930 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8931 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8932 // from the AND / OR.
8933 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8934   Opc = Op.getOpcode();
8935   if (Opc != ISD::OR && Opc != ISD::AND)
8936     return false;
8937   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8938           Op.getOperand(0).hasOneUse() &&
8939           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8940           Op.getOperand(1).hasOneUse());
8941 }
8942
8943 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8944 // 1 and that the SETCC node has a single use.
8945 static bool isXor1OfSetCC(SDValue Op) {
8946   if (Op.getOpcode() != ISD::XOR)
8947     return false;
8948   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8949   if (N1C && N1C->getAPIntValue() == 1) {
8950     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8951       Op.getOperand(0).hasOneUse();
8952   }
8953   return false;
8954 }
8955
8956 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8957   bool addTest = true;
8958   SDValue Chain = Op.getOperand(0);
8959   SDValue Cond  = Op.getOperand(1);
8960   SDValue Dest  = Op.getOperand(2);
8961   DebugLoc dl = Op.getDebugLoc();
8962   SDValue CC;
8963   bool Inverted = false;
8964
8965   if (Cond.getOpcode() == ISD::SETCC) {
8966     // Check for setcc([su]{add,sub,mul}o == 0).
8967     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8968         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8969         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8970         Cond.getOperand(0).getResNo() == 1 &&
8971         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8972          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8973          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8974          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8975          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8976          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8977       Inverted = true;
8978       Cond = Cond.getOperand(0);
8979     } else {
8980       SDValue NewCond = LowerSETCC(Cond, DAG);
8981       if (NewCond.getNode())
8982         Cond = NewCond;
8983     }
8984   }
8985 #if 0
8986   // FIXME: LowerXALUO doesn't handle these!!
8987   else if (Cond.getOpcode() == X86ISD::ADD  ||
8988            Cond.getOpcode() == X86ISD::SUB  ||
8989            Cond.getOpcode() == X86ISD::SMUL ||
8990            Cond.getOpcode() == X86ISD::UMUL)
8991     Cond = LowerXALUO(Cond, DAG);
8992 #endif
8993
8994   // Look pass (and (setcc_carry (cmp ...)), 1).
8995   if (Cond.getOpcode() == ISD::AND &&
8996       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8997     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8998     if (C && C->getAPIntValue() == 1)
8999       Cond = Cond.getOperand(0);
9000   }
9001
9002   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9003   // setting operand in place of the X86ISD::SETCC.
9004   unsigned CondOpcode = Cond.getOpcode();
9005   if (CondOpcode == X86ISD::SETCC ||
9006       CondOpcode == X86ISD::SETCC_CARRY) {
9007     CC = Cond.getOperand(0);
9008
9009     SDValue Cmp = Cond.getOperand(1);
9010     unsigned Opc = Cmp.getOpcode();
9011     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9012     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9013       Cond = Cmp;
9014       addTest = false;
9015     } else {
9016       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9017       default: break;
9018       case X86::COND_O:
9019       case X86::COND_B:
9020         // These can only come from an arithmetic instruction with overflow,
9021         // e.g. SADDO, UADDO.
9022         Cond = Cond.getNode()->getOperand(1);
9023         addTest = false;
9024         break;
9025       }
9026     }
9027   }
9028   CondOpcode = Cond.getOpcode();
9029   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9030       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9031       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9032        Cond.getOperand(0).getValueType() != MVT::i8)) {
9033     SDValue LHS = Cond.getOperand(0);
9034     SDValue RHS = Cond.getOperand(1);
9035     unsigned X86Opcode;
9036     unsigned X86Cond;
9037     SDVTList VTs;
9038     switch (CondOpcode) {
9039     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9040     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9041     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9042     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9043     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9044     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9045     default: llvm_unreachable("unexpected overflowing operator");
9046     }
9047     if (Inverted)
9048       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9049     if (CondOpcode == ISD::UMULO)
9050       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9051                           MVT::i32);
9052     else
9053       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9054
9055     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9056
9057     if (CondOpcode == ISD::UMULO)
9058       Cond = X86Op.getValue(2);
9059     else
9060       Cond = X86Op.getValue(1);
9061
9062     CC = DAG.getConstant(X86Cond, MVT::i8);
9063     addTest = false;
9064   } else {
9065     unsigned CondOpc;
9066     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9067       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9068       if (CondOpc == ISD::OR) {
9069         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9070         // two branches instead of an explicit OR instruction with a
9071         // separate test.
9072         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9073             isX86LogicalCmp(Cmp)) {
9074           CC = Cond.getOperand(0).getOperand(0);
9075           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9076                               Chain, Dest, CC, Cmp);
9077           CC = Cond.getOperand(1).getOperand(0);
9078           Cond = Cmp;
9079           addTest = false;
9080         }
9081       } else { // ISD::AND
9082         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9083         // two branches instead of an explicit AND instruction with a
9084         // separate test. However, we only do this if this block doesn't
9085         // have a fall-through edge, because this requires an explicit
9086         // jmp when the condition is false.
9087         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9088             isX86LogicalCmp(Cmp) &&
9089             Op.getNode()->hasOneUse()) {
9090           X86::CondCode CCode =
9091             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9092           CCode = X86::GetOppositeBranchCondition(CCode);
9093           CC = DAG.getConstant(CCode, MVT::i8);
9094           SDNode *User = *Op.getNode()->use_begin();
9095           // Look for an unconditional branch following this conditional branch.
9096           // We need this because we need to reverse the successors in order
9097           // to implement FCMP_OEQ.
9098           if (User->getOpcode() == ISD::BR) {
9099             SDValue FalseBB = User->getOperand(1);
9100             SDNode *NewBR =
9101               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9102             assert(NewBR == User);
9103             (void)NewBR;
9104             Dest = FalseBB;
9105
9106             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9107                                 Chain, Dest, CC, Cmp);
9108             X86::CondCode CCode =
9109               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9110             CCode = X86::GetOppositeBranchCondition(CCode);
9111             CC = DAG.getConstant(CCode, MVT::i8);
9112             Cond = Cmp;
9113             addTest = false;
9114           }
9115         }
9116       }
9117     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9118       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9119       // It should be transformed during dag combiner except when the condition
9120       // is set by a arithmetics with overflow node.
9121       X86::CondCode CCode =
9122         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9123       CCode = X86::GetOppositeBranchCondition(CCode);
9124       CC = DAG.getConstant(CCode, MVT::i8);
9125       Cond = Cond.getOperand(0).getOperand(1);
9126       addTest = false;
9127     } else if (Cond.getOpcode() == ISD::SETCC &&
9128                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9129       // For FCMP_OEQ, we can emit
9130       // two branches instead of an explicit AND instruction with a
9131       // separate test. However, we only do this if this block doesn't
9132       // have a fall-through edge, because this requires an explicit
9133       // jmp when the condition is false.
9134       if (Op.getNode()->hasOneUse()) {
9135         SDNode *User = *Op.getNode()->use_begin();
9136         // Look for an unconditional branch following this conditional branch.
9137         // We need this because we need to reverse the successors in order
9138         // to implement FCMP_OEQ.
9139         if (User->getOpcode() == ISD::BR) {
9140           SDValue FalseBB = User->getOperand(1);
9141           SDNode *NewBR =
9142             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9143           assert(NewBR == User);
9144           (void)NewBR;
9145           Dest = FalseBB;
9146
9147           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9148                                     Cond.getOperand(0), Cond.getOperand(1));
9149           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9150           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9151           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9152                               Chain, Dest, CC, Cmp);
9153           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9154           Cond = Cmp;
9155           addTest = false;
9156         }
9157       }
9158     } else if (Cond.getOpcode() == ISD::SETCC &&
9159                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9160       // For FCMP_UNE, we can emit
9161       // two branches instead of an explicit AND instruction with a
9162       // separate test. However, we only do this if this block doesn't
9163       // have a fall-through edge, because this requires an explicit
9164       // jmp when the condition is false.
9165       if (Op.getNode()->hasOneUse()) {
9166         SDNode *User = *Op.getNode()->use_begin();
9167         // Look for an unconditional branch following this conditional branch.
9168         // We need this because we need to reverse the successors in order
9169         // to implement FCMP_UNE.
9170         if (User->getOpcode() == ISD::BR) {
9171           SDValue FalseBB = User->getOperand(1);
9172           SDNode *NewBR =
9173             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9174           assert(NewBR == User);
9175           (void)NewBR;
9176
9177           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9178                                     Cond.getOperand(0), Cond.getOperand(1));
9179           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9180           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9181           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9182                               Chain, Dest, CC, Cmp);
9183           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9184           Cond = Cmp;
9185           addTest = false;
9186           Dest = FalseBB;
9187         }
9188       }
9189     }
9190   }
9191
9192   if (addTest) {
9193     // Look pass the truncate.
9194     if (Cond.getOpcode() == ISD::TRUNCATE)
9195       Cond = Cond.getOperand(0);
9196
9197     // We know the result of AND is compared against zero. Try to match
9198     // it to BT.
9199     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9200       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9201       if (NewSetCC.getNode()) {
9202         CC = NewSetCC.getOperand(0);
9203         Cond = NewSetCC.getOperand(1);
9204         addTest = false;
9205       }
9206     }
9207   }
9208
9209   if (addTest) {
9210     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9211     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9212   }
9213   Cond = ConvertCmpIfNecessary(Cond, DAG);
9214   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9215                      Chain, Dest, CC, Cond);
9216 }
9217
9218
9219 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9220 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9221 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9222 // that the guard pages used by the OS virtual memory manager are allocated in
9223 // correct sequence.
9224 SDValue
9225 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9226                                            SelectionDAG &DAG) const {
9227   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9228           getTargetMachine().Options.EnableSegmentedStacks) &&
9229          "This should be used only on Windows targets or when segmented stacks "
9230          "are being used");
9231   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9232   DebugLoc dl = Op.getDebugLoc();
9233
9234   // Get the inputs.
9235   SDValue Chain = Op.getOperand(0);
9236   SDValue Size  = Op.getOperand(1);
9237   // FIXME: Ensure alignment here
9238
9239   bool Is64Bit = Subtarget->is64Bit();
9240   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9241
9242   if (getTargetMachine().Options.EnableSegmentedStacks) {
9243     MachineFunction &MF = DAG.getMachineFunction();
9244     MachineRegisterInfo &MRI = MF.getRegInfo();
9245
9246     if (Is64Bit) {
9247       // The 64 bit implementation of segmented stacks needs to clobber both r10
9248       // r11. This makes it impossible to use it along with nested parameters.
9249       const Function *F = MF.getFunction();
9250
9251       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9252            I != E; ++I)
9253         if (I->hasNestAttr())
9254           report_fatal_error("Cannot use segmented stacks with functions that "
9255                              "have nested arguments.");
9256     }
9257
9258     const TargetRegisterClass *AddrRegClass =
9259       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9260     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9261     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9262     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9263                                 DAG.getRegister(Vreg, SPTy));
9264     SDValue Ops1[2] = { Value, Chain };
9265     return DAG.getMergeValues(Ops1, 2, dl);
9266   } else {
9267     SDValue Flag;
9268     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9269
9270     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9271     Flag = Chain.getValue(1);
9272     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9273
9274     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9275     Flag = Chain.getValue(1);
9276
9277     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9278
9279     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9280     return DAG.getMergeValues(Ops1, 2, dl);
9281   }
9282 }
9283
9284 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9285   MachineFunction &MF = DAG.getMachineFunction();
9286   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9287
9288   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9289   DebugLoc DL = Op.getDebugLoc();
9290
9291   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9292     // vastart just stores the address of the VarArgsFrameIndex slot into the
9293     // memory location argument.
9294     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9295                                    getPointerTy());
9296     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9297                         MachinePointerInfo(SV), false, false, 0);
9298   }
9299
9300   // __va_list_tag:
9301   //   gp_offset         (0 - 6 * 8)
9302   //   fp_offset         (48 - 48 + 8 * 16)
9303   //   overflow_arg_area (point to parameters coming in memory).
9304   //   reg_save_area
9305   SmallVector<SDValue, 8> MemOps;
9306   SDValue FIN = Op.getOperand(1);
9307   // Store gp_offset
9308   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9309                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9310                                                MVT::i32),
9311                                FIN, MachinePointerInfo(SV), false, false, 0);
9312   MemOps.push_back(Store);
9313
9314   // Store fp_offset
9315   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9316                     FIN, DAG.getIntPtrConstant(4));
9317   Store = DAG.getStore(Op.getOperand(0), DL,
9318                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9319                                        MVT::i32),
9320                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9321   MemOps.push_back(Store);
9322
9323   // Store ptr to overflow_arg_area
9324   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9325                     FIN, DAG.getIntPtrConstant(4));
9326   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9327                                     getPointerTy());
9328   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9329                        MachinePointerInfo(SV, 8),
9330                        false, false, 0);
9331   MemOps.push_back(Store);
9332
9333   // Store ptr to reg_save_area.
9334   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9335                     FIN, DAG.getIntPtrConstant(8));
9336   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9337                                     getPointerTy());
9338   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9339                        MachinePointerInfo(SV, 16), false, false, 0);
9340   MemOps.push_back(Store);
9341   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9342                      &MemOps[0], MemOps.size());
9343 }
9344
9345 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9346   assert(Subtarget->is64Bit() &&
9347          "LowerVAARG only handles 64-bit va_arg!");
9348   assert((Subtarget->isTargetLinux() ||
9349           Subtarget->isTargetDarwin()) &&
9350           "Unhandled target in LowerVAARG");
9351   assert(Op.getNode()->getNumOperands() == 4);
9352   SDValue Chain = Op.getOperand(0);
9353   SDValue SrcPtr = Op.getOperand(1);
9354   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9355   unsigned Align = Op.getConstantOperandVal(3);
9356   DebugLoc dl = Op.getDebugLoc();
9357
9358   EVT ArgVT = Op.getNode()->getValueType(0);
9359   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9360   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9361   uint8_t ArgMode;
9362
9363   // Decide which area this value should be read from.
9364   // TODO: Implement the AMD64 ABI in its entirety. This simple
9365   // selection mechanism works only for the basic types.
9366   if (ArgVT == MVT::f80) {
9367     llvm_unreachable("va_arg for f80 not yet implemented");
9368   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9369     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9370   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9371     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9372   } else {
9373     llvm_unreachable("Unhandled argument type in LowerVAARG");
9374   }
9375
9376   if (ArgMode == 2) {
9377     // Sanity Check: Make sure using fp_offset makes sense.
9378     assert(!getTargetMachine().Options.UseSoftFloat &&
9379            !(DAG.getMachineFunction()
9380                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9381            Subtarget->hasSSE1());
9382   }
9383
9384   // Insert VAARG_64 node into the DAG
9385   // VAARG_64 returns two values: Variable Argument Address, Chain
9386   SmallVector<SDValue, 11> InstOps;
9387   InstOps.push_back(Chain);
9388   InstOps.push_back(SrcPtr);
9389   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9390   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9391   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9392   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9393   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9394                                           VTs, &InstOps[0], InstOps.size(),
9395                                           MVT::i64,
9396                                           MachinePointerInfo(SV),
9397                                           /*Align=*/0,
9398                                           /*Volatile=*/false,
9399                                           /*ReadMem=*/true,
9400                                           /*WriteMem=*/true);
9401   Chain = VAARG.getValue(1);
9402
9403   // Load the next argument and return it
9404   return DAG.getLoad(ArgVT, dl,
9405                      Chain,
9406                      VAARG,
9407                      MachinePointerInfo(),
9408                      false, false, false, 0);
9409 }
9410
9411 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9412   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9413   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9414   SDValue Chain = Op.getOperand(0);
9415   SDValue DstPtr = Op.getOperand(1);
9416   SDValue SrcPtr = Op.getOperand(2);
9417   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9418   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9419   DebugLoc DL = Op.getDebugLoc();
9420
9421   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9422                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9423                        false,
9424                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9425 }
9426
9427 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9428 // may or may not be a constant. Takes immediate version of shift as input.
9429 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9430                                    SDValue SrcOp, SDValue ShAmt,
9431                                    SelectionDAG &DAG) {
9432   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9433
9434   if (isa<ConstantSDNode>(ShAmt)) {
9435     switch (Opc) {
9436       default: llvm_unreachable("Unknown target vector shift node");
9437       case X86ISD::VSHLI:
9438       case X86ISD::VSRLI:
9439       case X86ISD::VSRAI:
9440         return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9441     }
9442   }
9443
9444   // Change opcode to non-immediate version
9445   switch (Opc) {
9446     default: llvm_unreachable("Unknown target vector shift node");
9447     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9448     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9449     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9450   }
9451
9452   // Need to build a vector containing shift amount
9453   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9454   SDValue ShOps[4];
9455   ShOps[0] = ShAmt;
9456   ShOps[1] = DAG.getConstant(0, MVT::i32);
9457   ShOps[2] = DAG.getUNDEF(MVT::i32);
9458   ShOps[3] = DAG.getUNDEF(MVT::i32);
9459   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9460   ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9461   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9462 }
9463
9464 SDValue
9465 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9466   DebugLoc dl = Op.getDebugLoc();
9467   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9468   switch (IntNo) {
9469   default: return SDValue();    // Don't custom lower most intrinsics.
9470   // Comparison intrinsics.
9471   case Intrinsic::x86_sse_comieq_ss:
9472   case Intrinsic::x86_sse_comilt_ss:
9473   case Intrinsic::x86_sse_comile_ss:
9474   case Intrinsic::x86_sse_comigt_ss:
9475   case Intrinsic::x86_sse_comige_ss:
9476   case Intrinsic::x86_sse_comineq_ss:
9477   case Intrinsic::x86_sse_ucomieq_ss:
9478   case Intrinsic::x86_sse_ucomilt_ss:
9479   case Intrinsic::x86_sse_ucomile_ss:
9480   case Intrinsic::x86_sse_ucomigt_ss:
9481   case Intrinsic::x86_sse_ucomige_ss:
9482   case Intrinsic::x86_sse_ucomineq_ss:
9483   case Intrinsic::x86_sse2_comieq_sd:
9484   case Intrinsic::x86_sse2_comilt_sd:
9485   case Intrinsic::x86_sse2_comile_sd:
9486   case Intrinsic::x86_sse2_comigt_sd:
9487   case Intrinsic::x86_sse2_comige_sd:
9488   case Intrinsic::x86_sse2_comineq_sd:
9489   case Intrinsic::x86_sse2_ucomieq_sd:
9490   case Intrinsic::x86_sse2_ucomilt_sd:
9491   case Intrinsic::x86_sse2_ucomile_sd:
9492   case Intrinsic::x86_sse2_ucomigt_sd:
9493   case Intrinsic::x86_sse2_ucomige_sd:
9494   case Intrinsic::x86_sse2_ucomineq_sd: {
9495     unsigned Opc = 0;
9496     ISD::CondCode CC = ISD::SETCC_INVALID;
9497     switch (IntNo) {
9498     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9499     case Intrinsic::x86_sse_comieq_ss:
9500     case Intrinsic::x86_sse2_comieq_sd:
9501       Opc = X86ISD::COMI;
9502       CC = ISD::SETEQ;
9503       break;
9504     case Intrinsic::x86_sse_comilt_ss:
9505     case Intrinsic::x86_sse2_comilt_sd:
9506       Opc = X86ISD::COMI;
9507       CC = ISD::SETLT;
9508       break;
9509     case Intrinsic::x86_sse_comile_ss:
9510     case Intrinsic::x86_sse2_comile_sd:
9511       Opc = X86ISD::COMI;
9512       CC = ISD::SETLE;
9513       break;
9514     case Intrinsic::x86_sse_comigt_ss:
9515     case Intrinsic::x86_sse2_comigt_sd:
9516       Opc = X86ISD::COMI;
9517       CC = ISD::SETGT;
9518       break;
9519     case Intrinsic::x86_sse_comige_ss:
9520     case Intrinsic::x86_sse2_comige_sd:
9521       Opc = X86ISD::COMI;
9522       CC = ISD::SETGE;
9523       break;
9524     case Intrinsic::x86_sse_comineq_ss:
9525     case Intrinsic::x86_sse2_comineq_sd:
9526       Opc = X86ISD::COMI;
9527       CC = ISD::SETNE;
9528       break;
9529     case Intrinsic::x86_sse_ucomieq_ss:
9530     case Intrinsic::x86_sse2_ucomieq_sd:
9531       Opc = X86ISD::UCOMI;
9532       CC = ISD::SETEQ;
9533       break;
9534     case Intrinsic::x86_sse_ucomilt_ss:
9535     case Intrinsic::x86_sse2_ucomilt_sd:
9536       Opc = X86ISD::UCOMI;
9537       CC = ISD::SETLT;
9538       break;
9539     case Intrinsic::x86_sse_ucomile_ss:
9540     case Intrinsic::x86_sse2_ucomile_sd:
9541       Opc = X86ISD::UCOMI;
9542       CC = ISD::SETLE;
9543       break;
9544     case Intrinsic::x86_sse_ucomigt_ss:
9545     case Intrinsic::x86_sse2_ucomigt_sd:
9546       Opc = X86ISD::UCOMI;
9547       CC = ISD::SETGT;
9548       break;
9549     case Intrinsic::x86_sse_ucomige_ss:
9550     case Intrinsic::x86_sse2_ucomige_sd:
9551       Opc = X86ISD::UCOMI;
9552       CC = ISD::SETGE;
9553       break;
9554     case Intrinsic::x86_sse_ucomineq_ss:
9555     case Intrinsic::x86_sse2_ucomineq_sd:
9556       Opc = X86ISD::UCOMI;
9557       CC = ISD::SETNE;
9558       break;
9559     }
9560
9561     SDValue LHS = Op.getOperand(1);
9562     SDValue RHS = Op.getOperand(2);
9563     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9564     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9565     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9566     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9567                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9568     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9569   }
9570   // Arithmetic intrinsics.
9571   case Intrinsic::x86_sse2_pmulu_dq:
9572   case Intrinsic::x86_avx2_pmulu_dq:
9573     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9574                        Op.getOperand(1), Op.getOperand(2));
9575   case Intrinsic::x86_sse3_hadd_ps:
9576   case Intrinsic::x86_sse3_hadd_pd:
9577   case Intrinsic::x86_avx_hadd_ps_256:
9578   case Intrinsic::x86_avx_hadd_pd_256:
9579     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9580                        Op.getOperand(1), Op.getOperand(2));
9581   case Intrinsic::x86_sse3_hsub_ps:
9582   case Intrinsic::x86_sse3_hsub_pd:
9583   case Intrinsic::x86_avx_hsub_ps_256:
9584   case Intrinsic::x86_avx_hsub_pd_256:
9585     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9586                        Op.getOperand(1), Op.getOperand(2));
9587   case Intrinsic::x86_ssse3_phadd_w_128:
9588   case Intrinsic::x86_ssse3_phadd_d_128:
9589   case Intrinsic::x86_avx2_phadd_w:
9590   case Intrinsic::x86_avx2_phadd_d:
9591     return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9592                        Op.getOperand(1), Op.getOperand(2));
9593   case Intrinsic::x86_ssse3_phsub_w_128:
9594   case Intrinsic::x86_ssse3_phsub_d_128:
9595   case Intrinsic::x86_avx2_phsub_w:
9596   case Intrinsic::x86_avx2_phsub_d:
9597     return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9598                        Op.getOperand(1), Op.getOperand(2));
9599   case Intrinsic::x86_avx2_psllv_d:
9600   case Intrinsic::x86_avx2_psllv_q:
9601   case Intrinsic::x86_avx2_psllv_d_256:
9602   case Intrinsic::x86_avx2_psllv_q_256:
9603     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9604                       Op.getOperand(1), Op.getOperand(2));
9605   case Intrinsic::x86_avx2_psrlv_d:
9606   case Intrinsic::x86_avx2_psrlv_q:
9607   case Intrinsic::x86_avx2_psrlv_d_256:
9608   case Intrinsic::x86_avx2_psrlv_q_256:
9609     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9610                       Op.getOperand(1), Op.getOperand(2));
9611   case Intrinsic::x86_avx2_psrav_d:
9612   case Intrinsic::x86_avx2_psrav_d_256:
9613     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9614                       Op.getOperand(1), Op.getOperand(2));
9615   case Intrinsic::x86_ssse3_pshuf_b_128:
9616   case Intrinsic::x86_avx2_pshuf_b:
9617     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9618                        Op.getOperand(1), Op.getOperand(2));
9619   case Intrinsic::x86_ssse3_psign_b_128:
9620   case Intrinsic::x86_ssse3_psign_w_128:
9621   case Intrinsic::x86_ssse3_psign_d_128:
9622   case Intrinsic::x86_avx2_psign_b:
9623   case Intrinsic::x86_avx2_psign_w:
9624   case Intrinsic::x86_avx2_psign_d:
9625     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9626                        Op.getOperand(1), Op.getOperand(2));
9627   case Intrinsic::x86_sse41_insertps:
9628     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9629                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9630   case Intrinsic::x86_avx_vperm2f128_ps_256:
9631   case Intrinsic::x86_avx_vperm2f128_pd_256:
9632   case Intrinsic::x86_avx_vperm2f128_si_256:
9633   case Intrinsic::x86_avx2_vperm2i128:
9634     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9635                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9636   case Intrinsic::x86_avx2_permd:
9637   case Intrinsic::x86_avx2_permps:
9638     // Operands intentionally swapped. Mask is last operand to intrinsic,
9639     // but second operand for node/intruction.
9640     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9641                        Op.getOperand(2), Op.getOperand(1));
9642
9643   // ptest and testp intrinsics. The intrinsic these come from are designed to
9644   // return an integer value, not just an instruction so lower it to the ptest
9645   // or testp pattern and a setcc for the result.
9646   case Intrinsic::x86_sse41_ptestz:
9647   case Intrinsic::x86_sse41_ptestc:
9648   case Intrinsic::x86_sse41_ptestnzc:
9649   case Intrinsic::x86_avx_ptestz_256:
9650   case Intrinsic::x86_avx_ptestc_256:
9651   case Intrinsic::x86_avx_ptestnzc_256:
9652   case Intrinsic::x86_avx_vtestz_ps:
9653   case Intrinsic::x86_avx_vtestc_ps:
9654   case Intrinsic::x86_avx_vtestnzc_ps:
9655   case Intrinsic::x86_avx_vtestz_pd:
9656   case Intrinsic::x86_avx_vtestc_pd:
9657   case Intrinsic::x86_avx_vtestnzc_pd:
9658   case Intrinsic::x86_avx_vtestz_ps_256:
9659   case Intrinsic::x86_avx_vtestc_ps_256:
9660   case Intrinsic::x86_avx_vtestnzc_ps_256:
9661   case Intrinsic::x86_avx_vtestz_pd_256:
9662   case Intrinsic::x86_avx_vtestc_pd_256:
9663   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9664     bool IsTestPacked = false;
9665     unsigned X86CC = 0;
9666     switch (IntNo) {
9667     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9668     case Intrinsic::x86_avx_vtestz_ps:
9669     case Intrinsic::x86_avx_vtestz_pd:
9670     case Intrinsic::x86_avx_vtestz_ps_256:
9671     case Intrinsic::x86_avx_vtestz_pd_256:
9672       IsTestPacked = true; // Fallthrough
9673     case Intrinsic::x86_sse41_ptestz:
9674     case Intrinsic::x86_avx_ptestz_256:
9675       // ZF = 1
9676       X86CC = X86::COND_E;
9677       break;
9678     case Intrinsic::x86_avx_vtestc_ps:
9679     case Intrinsic::x86_avx_vtestc_pd:
9680     case Intrinsic::x86_avx_vtestc_ps_256:
9681     case Intrinsic::x86_avx_vtestc_pd_256:
9682       IsTestPacked = true; // Fallthrough
9683     case Intrinsic::x86_sse41_ptestc:
9684     case Intrinsic::x86_avx_ptestc_256:
9685       // CF = 1
9686       X86CC = X86::COND_B;
9687       break;
9688     case Intrinsic::x86_avx_vtestnzc_ps:
9689     case Intrinsic::x86_avx_vtestnzc_pd:
9690     case Intrinsic::x86_avx_vtestnzc_ps_256:
9691     case Intrinsic::x86_avx_vtestnzc_pd_256:
9692       IsTestPacked = true; // Fallthrough
9693     case Intrinsic::x86_sse41_ptestnzc:
9694     case Intrinsic::x86_avx_ptestnzc_256:
9695       // ZF and CF = 0
9696       X86CC = X86::COND_A;
9697       break;
9698     }
9699
9700     SDValue LHS = Op.getOperand(1);
9701     SDValue RHS = Op.getOperand(2);
9702     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9703     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9704     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9705     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9706     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9707   }
9708
9709   // SSE/AVX shift intrinsics
9710   case Intrinsic::x86_sse2_psll_w:
9711   case Intrinsic::x86_sse2_psll_d:
9712   case Intrinsic::x86_sse2_psll_q:
9713   case Intrinsic::x86_avx2_psll_w:
9714   case Intrinsic::x86_avx2_psll_d:
9715   case Intrinsic::x86_avx2_psll_q:
9716     return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9717                        Op.getOperand(1), Op.getOperand(2));
9718   case Intrinsic::x86_sse2_psrl_w:
9719   case Intrinsic::x86_sse2_psrl_d:
9720   case Intrinsic::x86_sse2_psrl_q:
9721   case Intrinsic::x86_avx2_psrl_w:
9722   case Intrinsic::x86_avx2_psrl_d:
9723   case Intrinsic::x86_avx2_psrl_q:
9724     return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9725                        Op.getOperand(1), Op.getOperand(2));
9726   case Intrinsic::x86_sse2_psra_w:
9727   case Intrinsic::x86_sse2_psra_d:
9728   case Intrinsic::x86_avx2_psra_w:
9729   case Intrinsic::x86_avx2_psra_d:
9730     return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9731                        Op.getOperand(1), Op.getOperand(2));
9732   case Intrinsic::x86_sse2_pslli_w:
9733   case Intrinsic::x86_sse2_pslli_d:
9734   case Intrinsic::x86_sse2_pslli_q:
9735   case Intrinsic::x86_avx2_pslli_w:
9736   case Intrinsic::x86_avx2_pslli_d:
9737   case Intrinsic::x86_avx2_pslli_q:
9738     return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9739                                Op.getOperand(1), Op.getOperand(2), DAG);
9740   case Intrinsic::x86_sse2_psrli_w:
9741   case Intrinsic::x86_sse2_psrli_d:
9742   case Intrinsic::x86_sse2_psrli_q:
9743   case Intrinsic::x86_avx2_psrli_w:
9744   case Intrinsic::x86_avx2_psrli_d:
9745   case Intrinsic::x86_avx2_psrli_q:
9746     return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9747                                Op.getOperand(1), Op.getOperand(2), DAG);
9748   case Intrinsic::x86_sse2_psrai_w:
9749   case Intrinsic::x86_sse2_psrai_d:
9750   case Intrinsic::x86_avx2_psrai_w:
9751   case Intrinsic::x86_avx2_psrai_d:
9752     return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9753                                Op.getOperand(1), Op.getOperand(2), DAG);
9754   // Fix vector shift instructions where the last operand is a non-immediate
9755   // i32 value.
9756   case Intrinsic::x86_mmx_pslli_w:
9757   case Intrinsic::x86_mmx_pslli_d:
9758   case Intrinsic::x86_mmx_pslli_q:
9759   case Intrinsic::x86_mmx_psrli_w:
9760   case Intrinsic::x86_mmx_psrli_d:
9761   case Intrinsic::x86_mmx_psrli_q:
9762   case Intrinsic::x86_mmx_psrai_w:
9763   case Intrinsic::x86_mmx_psrai_d: {
9764     SDValue ShAmt = Op.getOperand(2);
9765     if (isa<ConstantSDNode>(ShAmt))
9766       return SDValue();
9767
9768     unsigned NewIntNo = 0;
9769     switch (IntNo) {
9770     case Intrinsic::x86_mmx_pslli_w:
9771       NewIntNo = Intrinsic::x86_mmx_psll_w;
9772       break;
9773     case Intrinsic::x86_mmx_pslli_d:
9774       NewIntNo = Intrinsic::x86_mmx_psll_d;
9775       break;
9776     case Intrinsic::x86_mmx_pslli_q:
9777       NewIntNo = Intrinsic::x86_mmx_psll_q;
9778       break;
9779     case Intrinsic::x86_mmx_psrli_w:
9780       NewIntNo = Intrinsic::x86_mmx_psrl_w;
9781       break;
9782     case Intrinsic::x86_mmx_psrli_d:
9783       NewIntNo = Intrinsic::x86_mmx_psrl_d;
9784       break;
9785     case Intrinsic::x86_mmx_psrli_q:
9786       NewIntNo = Intrinsic::x86_mmx_psrl_q;
9787       break;
9788     case Intrinsic::x86_mmx_psrai_w:
9789       NewIntNo = Intrinsic::x86_mmx_psra_w;
9790       break;
9791     case Intrinsic::x86_mmx_psrai_d:
9792       NewIntNo = Intrinsic::x86_mmx_psra_d;
9793       break;
9794     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9795     }
9796
9797     // The vector shift intrinsics with scalars uses 32b shift amounts but
9798     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9799     // to be zero.
9800     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9801                          DAG.getConstant(0, MVT::i32));
9802 // FIXME this must be lowered to get rid of the invalid type.
9803
9804     EVT VT = Op.getValueType();
9805     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9806     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9807                        DAG.getConstant(NewIntNo, MVT::i32),
9808                        Op.getOperand(1), ShAmt);
9809   }
9810   }
9811 }
9812
9813 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9814                                            SelectionDAG &DAG) const {
9815   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9816   MFI->setReturnAddressIsTaken(true);
9817
9818   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9819   DebugLoc dl = Op.getDebugLoc();
9820
9821   if (Depth > 0) {
9822     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9823     SDValue Offset =
9824       DAG.getConstant(TD->getPointerSize(),
9825                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9826     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9827                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9828                                    FrameAddr, Offset),
9829                        MachinePointerInfo(), false, false, false, 0);
9830   }
9831
9832   // Just load the return address.
9833   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9834   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9835                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9836 }
9837
9838 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9839   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9840   MFI->setFrameAddressIsTaken(true);
9841
9842   EVT VT = Op.getValueType();
9843   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9844   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9845   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9846   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9847   while (Depth--)
9848     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9849                             MachinePointerInfo(),
9850                             false, false, false, 0);
9851   return FrameAddr;
9852 }
9853
9854 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9855                                                      SelectionDAG &DAG) const {
9856   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9857 }
9858
9859 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9860   SDValue Chain     = Op.getOperand(0);
9861   SDValue Offset    = Op.getOperand(1);
9862   SDValue Handler   = Op.getOperand(2);
9863   DebugLoc dl       = Op.getDebugLoc();
9864
9865   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9866                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9867                                      getPointerTy());
9868   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9869
9870   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9871                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9872   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9873   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9874                        false, false, 0);
9875   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9876
9877   return DAG.getNode(X86ISD::EH_RETURN, dl,
9878                      MVT::Other,
9879                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9880 }
9881
9882 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9883                                                   SelectionDAG &DAG) const {
9884   return Op.getOperand(0);
9885 }
9886
9887 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9888                                                 SelectionDAG &DAG) const {
9889   SDValue Root = Op.getOperand(0);
9890   SDValue Trmp = Op.getOperand(1); // trampoline
9891   SDValue FPtr = Op.getOperand(2); // nested function
9892   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9893   DebugLoc dl  = Op.getDebugLoc();
9894
9895   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9896
9897   if (Subtarget->is64Bit()) {
9898     SDValue OutChains[6];
9899
9900     // Large code-model.
9901     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9902     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9903
9904     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9905     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9906
9907     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9908
9909     // Load the pointer to the nested function into R11.
9910     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9911     SDValue Addr = Trmp;
9912     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9913                                 Addr, MachinePointerInfo(TrmpAddr),
9914                                 false, false, 0);
9915
9916     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9917                        DAG.getConstant(2, MVT::i64));
9918     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9919                                 MachinePointerInfo(TrmpAddr, 2),
9920                                 false, false, 2);
9921
9922     // Load the 'nest' parameter value into R10.
9923     // R10 is specified in X86CallingConv.td
9924     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9925     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9926                        DAG.getConstant(10, MVT::i64));
9927     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9928                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9929                                 false, false, 0);
9930
9931     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9932                        DAG.getConstant(12, MVT::i64));
9933     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9934                                 MachinePointerInfo(TrmpAddr, 12),
9935                                 false, false, 2);
9936
9937     // Jump to the nested function.
9938     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9939     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9940                        DAG.getConstant(20, MVT::i64));
9941     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9942                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9943                                 false, false, 0);
9944
9945     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9946     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9947                        DAG.getConstant(22, MVT::i64));
9948     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9949                                 MachinePointerInfo(TrmpAddr, 22),
9950                                 false, false, 0);
9951
9952     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9953   } else {
9954     const Function *Func =
9955       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9956     CallingConv::ID CC = Func->getCallingConv();
9957     unsigned NestReg;
9958
9959     switch (CC) {
9960     default:
9961       llvm_unreachable("Unsupported calling convention");
9962     case CallingConv::C:
9963     case CallingConv::X86_StdCall: {
9964       // Pass 'nest' parameter in ECX.
9965       // Must be kept in sync with X86CallingConv.td
9966       NestReg = X86::ECX;
9967
9968       // Check that ECX wasn't needed by an 'inreg' parameter.
9969       FunctionType *FTy = Func->getFunctionType();
9970       const AttrListPtr &Attrs = Func->getAttributes();
9971
9972       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9973         unsigned InRegCount = 0;
9974         unsigned Idx = 1;
9975
9976         for (FunctionType::param_iterator I = FTy->param_begin(),
9977              E = FTy->param_end(); I != E; ++I, ++Idx)
9978           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9979             // FIXME: should only count parameters that are lowered to integers.
9980             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9981
9982         if (InRegCount > 2) {
9983           report_fatal_error("Nest register in use - reduce number of inreg"
9984                              " parameters!");
9985         }
9986       }
9987       break;
9988     }
9989     case CallingConv::X86_FastCall:
9990     case CallingConv::X86_ThisCall:
9991     case CallingConv::Fast:
9992       // Pass 'nest' parameter in EAX.
9993       // Must be kept in sync with X86CallingConv.td
9994       NestReg = X86::EAX;
9995       break;
9996     }
9997
9998     SDValue OutChains[4];
9999     SDValue Addr, Disp;
10000
10001     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10002                        DAG.getConstant(10, MVT::i32));
10003     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10004
10005     // This is storing the opcode for MOV32ri.
10006     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10007     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10008     OutChains[0] = DAG.getStore(Root, dl,
10009                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10010                                 Trmp, MachinePointerInfo(TrmpAddr),
10011                                 false, false, 0);
10012
10013     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10014                        DAG.getConstant(1, MVT::i32));
10015     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10016                                 MachinePointerInfo(TrmpAddr, 1),
10017                                 false, false, 1);
10018
10019     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10020     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10021                        DAG.getConstant(5, MVT::i32));
10022     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10023                                 MachinePointerInfo(TrmpAddr, 5),
10024                                 false, false, 1);
10025
10026     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10027                        DAG.getConstant(6, MVT::i32));
10028     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10029                                 MachinePointerInfo(TrmpAddr, 6),
10030                                 false, false, 1);
10031
10032     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10033   }
10034 }
10035
10036 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10037                                             SelectionDAG &DAG) const {
10038   /*
10039    The rounding mode is in bits 11:10 of FPSR, and has the following
10040    settings:
10041      00 Round to nearest
10042      01 Round to -inf
10043      10 Round to +inf
10044      11 Round to 0
10045
10046   FLT_ROUNDS, on the other hand, expects the following:
10047     -1 Undefined
10048      0 Round to 0
10049      1 Round to nearest
10050      2 Round to +inf
10051      3 Round to -inf
10052
10053   To perform the conversion, we do:
10054     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10055   */
10056
10057   MachineFunction &MF = DAG.getMachineFunction();
10058   const TargetMachine &TM = MF.getTarget();
10059   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10060   unsigned StackAlignment = TFI.getStackAlignment();
10061   EVT VT = Op.getValueType();
10062   DebugLoc DL = Op.getDebugLoc();
10063
10064   // Save FP Control Word to stack slot
10065   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10066   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10067
10068
10069   MachineMemOperand *MMO =
10070    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10071                            MachineMemOperand::MOStore, 2, 2);
10072
10073   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10074   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10075                                           DAG.getVTList(MVT::Other),
10076                                           Ops, 2, MVT::i16, MMO);
10077
10078   // Load FP Control Word from stack slot
10079   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10080                             MachinePointerInfo(), false, false, false, 0);
10081
10082   // Transform as necessary
10083   SDValue CWD1 =
10084     DAG.getNode(ISD::SRL, DL, MVT::i16,
10085                 DAG.getNode(ISD::AND, DL, MVT::i16,
10086                             CWD, DAG.getConstant(0x800, MVT::i16)),
10087                 DAG.getConstant(11, MVT::i8));
10088   SDValue CWD2 =
10089     DAG.getNode(ISD::SRL, DL, MVT::i16,
10090                 DAG.getNode(ISD::AND, DL, MVT::i16,
10091                             CWD, DAG.getConstant(0x400, MVT::i16)),
10092                 DAG.getConstant(9, MVT::i8));
10093
10094   SDValue RetVal =
10095     DAG.getNode(ISD::AND, DL, MVT::i16,
10096                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10097                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10098                             DAG.getConstant(1, MVT::i16)),
10099                 DAG.getConstant(3, MVT::i16));
10100
10101
10102   return DAG.getNode((VT.getSizeInBits() < 16 ?
10103                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10104 }
10105
10106 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10107   EVT VT = Op.getValueType();
10108   EVT OpVT = VT;
10109   unsigned NumBits = VT.getSizeInBits();
10110   DebugLoc dl = Op.getDebugLoc();
10111
10112   Op = Op.getOperand(0);
10113   if (VT == MVT::i8) {
10114     // Zero extend to i32 since there is not an i8 bsr.
10115     OpVT = MVT::i32;
10116     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10117   }
10118
10119   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10120   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10121   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10122
10123   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10124   SDValue Ops[] = {
10125     Op,
10126     DAG.getConstant(NumBits+NumBits-1, OpVT),
10127     DAG.getConstant(X86::COND_E, MVT::i8),
10128     Op.getValue(1)
10129   };
10130   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10131
10132   // Finally xor with NumBits-1.
10133   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10134
10135   if (VT == MVT::i8)
10136     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10137   return Op;
10138 }
10139
10140 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10141                                                 SelectionDAG &DAG) const {
10142   EVT VT = Op.getValueType();
10143   EVT OpVT = VT;
10144   unsigned NumBits = VT.getSizeInBits();
10145   DebugLoc dl = Op.getDebugLoc();
10146
10147   Op = Op.getOperand(0);
10148   if (VT == MVT::i8) {
10149     // Zero extend to i32 since there is not an i8 bsr.
10150     OpVT = MVT::i32;
10151     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10152   }
10153
10154   // Issue a bsr (scan bits in reverse).
10155   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10156   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10157
10158   // And xor with NumBits-1.
10159   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10160
10161   if (VT == MVT::i8)
10162     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10163   return Op;
10164 }
10165
10166 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10167   EVT VT = Op.getValueType();
10168   unsigned NumBits = VT.getSizeInBits();
10169   DebugLoc dl = Op.getDebugLoc();
10170   Op = Op.getOperand(0);
10171
10172   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10173   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10174   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10175
10176   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10177   SDValue Ops[] = {
10178     Op,
10179     DAG.getConstant(NumBits, VT),
10180     DAG.getConstant(X86::COND_E, MVT::i8),
10181     Op.getValue(1)
10182   };
10183   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10184 }
10185
10186 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10187 // ones, and then concatenate the result back.
10188 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10189   EVT VT = Op.getValueType();
10190
10191   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10192          "Unsupported value type for operation");
10193
10194   unsigned NumElems = VT.getVectorNumElements();
10195   DebugLoc dl = Op.getDebugLoc();
10196
10197   // Extract the LHS vectors
10198   SDValue LHS = Op.getOperand(0);
10199   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10200   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10201
10202   // Extract the RHS vectors
10203   SDValue RHS = Op.getOperand(1);
10204   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10205   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10206
10207   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10208   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10209
10210   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10211                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10212                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10213 }
10214
10215 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10216   assert(Op.getValueType().getSizeInBits() == 256 &&
10217          Op.getValueType().isInteger() &&
10218          "Only handle AVX 256-bit vector integer operation");
10219   return Lower256IntArith(Op, DAG);
10220 }
10221
10222 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10223   assert(Op.getValueType().getSizeInBits() == 256 &&
10224          Op.getValueType().isInteger() &&
10225          "Only handle AVX 256-bit vector integer operation");
10226   return Lower256IntArith(Op, DAG);
10227 }
10228
10229 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10230   EVT VT = Op.getValueType();
10231
10232   // Decompose 256-bit ops into smaller 128-bit ops.
10233   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10234     return Lower256IntArith(Op, DAG);
10235
10236   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10237          "Only know how to lower V2I64/V4I64 multiply");
10238
10239   DebugLoc dl = Op.getDebugLoc();
10240
10241   //  Ahi = psrlqi(a, 32);
10242   //  Bhi = psrlqi(b, 32);
10243   //
10244   //  AloBlo = pmuludq(a, b);
10245   //  AloBhi = pmuludq(a, Bhi);
10246   //  AhiBlo = pmuludq(Ahi, b);
10247
10248   //  AloBhi = psllqi(AloBhi, 32);
10249   //  AhiBlo = psllqi(AhiBlo, 32);
10250   //  return AloBlo + AloBhi + AhiBlo;
10251
10252   SDValue A = Op.getOperand(0);
10253   SDValue B = Op.getOperand(1);
10254
10255   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10256
10257   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10258   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10259
10260   // Bit cast to 32-bit vectors for MULUDQ
10261   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10262   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10263   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10264   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10265   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10266
10267   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10268   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10269   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10270
10271   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10272   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10273
10274   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10275   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10276 }
10277
10278 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10279
10280   EVT VT = Op.getValueType();
10281   DebugLoc dl = Op.getDebugLoc();
10282   SDValue R = Op.getOperand(0);
10283   SDValue Amt = Op.getOperand(1);
10284   LLVMContext *Context = DAG.getContext();
10285
10286   if (!Subtarget->hasSSE2())
10287     return SDValue();
10288
10289   // Optimize shl/srl/sra with constant shift amount.
10290   if (isSplatVector(Amt.getNode())) {
10291     SDValue SclrAmt = Amt->getOperand(0);
10292     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10293       uint64_t ShiftAmt = C->getZExtValue();
10294
10295       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10296           (Subtarget->hasAVX2() &&
10297            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10298         if (Op.getOpcode() == ISD::SHL)
10299           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10300                              DAG.getConstant(ShiftAmt, MVT::i32));
10301         if (Op.getOpcode() == ISD::SRL)
10302           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10303                              DAG.getConstant(ShiftAmt, MVT::i32));
10304         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10305           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10306                              DAG.getConstant(ShiftAmt, MVT::i32));
10307       }
10308
10309       if (VT == MVT::v16i8) {
10310         if (Op.getOpcode() == ISD::SHL) {
10311           // Make a large shift.
10312           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10313                                     DAG.getConstant(ShiftAmt, MVT::i32));
10314           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10315           // Zero out the rightmost bits.
10316           SmallVector<SDValue, 16> V(16,
10317                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10318                                                      MVT::i8));
10319           return DAG.getNode(ISD::AND, dl, VT, SHL,
10320                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10321         }
10322         if (Op.getOpcode() == ISD::SRL) {
10323           // Make a large shift.
10324           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10325                                     DAG.getConstant(ShiftAmt, MVT::i32));
10326           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10327           // Zero out the leftmost bits.
10328           SmallVector<SDValue, 16> V(16,
10329                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10330                                                      MVT::i8));
10331           return DAG.getNode(ISD::AND, dl, VT, SRL,
10332                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10333         }
10334         if (Op.getOpcode() == ISD::SRA) {
10335           if (ShiftAmt == 7) {
10336             // R s>> 7  ===  R s< 0
10337             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10338             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10339           }
10340
10341           // R s>> a === ((R u>> a) ^ m) - m
10342           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10343           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10344                                                          MVT::i8));
10345           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10346           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10347           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10348           return Res;
10349         }
10350         llvm_unreachable("Unknown shift opcode.");
10351       }
10352
10353       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10354         if (Op.getOpcode() == ISD::SHL) {
10355           // Make a large shift.
10356           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10357                                     DAG.getConstant(ShiftAmt, MVT::i32));
10358           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10359           // Zero out the rightmost bits.
10360           SmallVector<SDValue, 32> V(32,
10361                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10362                                                      MVT::i8));
10363           return DAG.getNode(ISD::AND, dl, VT, SHL,
10364                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10365         }
10366         if (Op.getOpcode() == ISD::SRL) {
10367           // Make a large shift.
10368           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10369                                     DAG.getConstant(ShiftAmt, MVT::i32));
10370           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10371           // Zero out the leftmost bits.
10372           SmallVector<SDValue, 32> V(32,
10373                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10374                                                      MVT::i8));
10375           return DAG.getNode(ISD::AND, dl, VT, SRL,
10376                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10377         }
10378         if (Op.getOpcode() == ISD::SRA) {
10379           if (ShiftAmt == 7) {
10380             // R s>> 7  ===  R s< 0
10381             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10382             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10383           }
10384
10385           // R s>> a === ((R u>> a) ^ m) - m
10386           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10387           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10388                                                          MVT::i8));
10389           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10390           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10391           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10392           return Res;
10393         }
10394         llvm_unreachable("Unknown shift opcode.");
10395       }
10396     }
10397   }
10398
10399   // Lower SHL with variable shift amount.
10400   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10401     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10402                      DAG.getConstant(23, MVT::i32));
10403
10404     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10405     Constant *C = ConstantDataVector::get(*Context, CV);
10406     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10407     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10408                                  MachinePointerInfo::getConstantPool(),
10409                                  false, false, false, 16);
10410
10411     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10412     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10413     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10414     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10415   }
10416   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10417     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10418
10419     // a = a << 5;
10420     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10421                      DAG.getConstant(5, MVT::i32));
10422     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10423
10424     // Turn 'a' into a mask suitable for VSELECT
10425     SDValue VSelM = DAG.getConstant(0x80, VT);
10426     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10427     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10428
10429     SDValue CM1 = DAG.getConstant(0x0f, VT);
10430     SDValue CM2 = DAG.getConstant(0x3f, VT);
10431
10432     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10433     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10434     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10435                             DAG.getConstant(4, MVT::i32), DAG);
10436     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10437     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10438
10439     // a += a
10440     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10441     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10442     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10443
10444     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10445     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10446     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10447                             DAG.getConstant(2, MVT::i32), DAG);
10448     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10449     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10450
10451     // a += a
10452     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10453     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10454     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10455
10456     // return VSELECT(r, r+r, a);
10457     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10458                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10459     return R;
10460   }
10461
10462   // Decompose 256-bit shifts into smaller 128-bit shifts.
10463   if (VT.getSizeInBits() == 256) {
10464     unsigned NumElems = VT.getVectorNumElements();
10465     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10466     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10467
10468     // Extract the two vectors
10469     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10470     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10471
10472     // Recreate the shift amount vectors
10473     SDValue Amt1, Amt2;
10474     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10475       // Constant shift amount
10476       SmallVector<SDValue, 4> Amt1Csts;
10477       SmallVector<SDValue, 4> Amt2Csts;
10478       for (unsigned i = 0; i != NumElems/2; ++i)
10479         Amt1Csts.push_back(Amt->getOperand(i));
10480       for (unsigned i = NumElems/2; i != NumElems; ++i)
10481         Amt2Csts.push_back(Amt->getOperand(i));
10482
10483       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10484                                  &Amt1Csts[0], NumElems/2);
10485       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10486                                  &Amt2Csts[0], NumElems/2);
10487     } else {
10488       // Variable shift amount
10489       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10490       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10491     }
10492
10493     // Issue new vector shifts for the smaller types
10494     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10495     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10496
10497     // Concatenate the result back
10498     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10499   }
10500
10501   return SDValue();
10502 }
10503
10504 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10505   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10506   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10507   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10508   // has only one use.
10509   SDNode *N = Op.getNode();
10510   SDValue LHS = N->getOperand(0);
10511   SDValue RHS = N->getOperand(1);
10512   unsigned BaseOp = 0;
10513   unsigned Cond = 0;
10514   DebugLoc DL = Op.getDebugLoc();
10515   switch (Op.getOpcode()) {
10516   default: llvm_unreachable("Unknown ovf instruction!");
10517   case ISD::SADDO:
10518     // A subtract of one will be selected as a INC. Note that INC doesn't
10519     // set CF, so we can't do this for UADDO.
10520     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10521       if (C->isOne()) {
10522         BaseOp = X86ISD::INC;
10523         Cond = X86::COND_O;
10524         break;
10525       }
10526     BaseOp = X86ISD::ADD;
10527     Cond = X86::COND_O;
10528     break;
10529   case ISD::UADDO:
10530     BaseOp = X86ISD::ADD;
10531     Cond = X86::COND_B;
10532     break;
10533   case ISD::SSUBO:
10534     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10535     // set CF, so we can't do this for USUBO.
10536     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10537       if (C->isOne()) {
10538         BaseOp = X86ISD::DEC;
10539         Cond = X86::COND_O;
10540         break;
10541       }
10542     BaseOp = X86ISD::SUB;
10543     Cond = X86::COND_O;
10544     break;
10545   case ISD::USUBO:
10546     BaseOp = X86ISD::SUB;
10547     Cond = X86::COND_B;
10548     break;
10549   case ISD::SMULO:
10550     BaseOp = X86ISD::SMUL;
10551     Cond = X86::COND_O;
10552     break;
10553   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10554     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10555                                  MVT::i32);
10556     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10557
10558     SDValue SetCC =
10559       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10560                   DAG.getConstant(X86::COND_O, MVT::i32),
10561                   SDValue(Sum.getNode(), 2));
10562
10563     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10564   }
10565   }
10566
10567   // Also sets EFLAGS.
10568   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10569   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10570
10571   SDValue SetCC =
10572     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10573                 DAG.getConstant(Cond, MVT::i32),
10574                 SDValue(Sum.getNode(), 1));
10575
10576   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10577 }
10578
10579 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10580                                                   SelectionDAG &DAG) const {
10581   DebugLoc dl = Op.getDebugLoc();
10582   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10583   EVT VT = Op.getValueType();
10584
10585   if (!Subtarget->hasSSE2() || !VT.isVector())
10586     return SDValue();
10587
10588   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10589                       ExtraVT.getScalarType().getSizeInBits();
10590   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10591
10592   switch (VT.getSimpleVT().SimpleTy) {
10593     default: return SDValue();
10594     case MVT::v8i32:
10595     case MVT::v16i16:
10596       if (!Subtarget->hasAVX())
10597         return SDValue();
10598       if (!Subtarget->hasAVX2()) {
10599         // needs to be split
10600         unsigned NumElems = VT.getVectorNumElements();
10601
10602         // Extract the LHS vectors
10603         SDValue LHS = Op.getOperand(0);
10604         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10605         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10606
10607         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10608         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10609
10610         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10611         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10612         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10613                                    ExtraNumElems/2);
10614         SDValue Extra = DAG.getValueType(ExtraVT);
10615
10616         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10617         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10618
10619         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10620       }
10621       // fall through
10622     case MVT::v4i32:
10623     case MVT::v8i16: {
10624       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10625                                          Op.getOperand(0), ShAmt, DAG);
10626       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10627     }
10628   }
10629 }
10630
10631
10632 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10633   DebugLoc dl = Op.getDebugLoc();
10634
10635   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10636   // There isn't any reason to disable it if the target processor supports it.
10637   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10638     SDValue Chain = Op.getOperand(0);
10639     SDValue Zero = DAG.getConstant(0, MVT::i32);
10640     SDValue Ops[] = {
10641       DAG.getRegister(X86::ESP, MVT::i32), // Base
10642       DAG.getTargetConstant(1, MVT::i8),   // Scale
10643       DAG.getRegister(0, MVT::i32),        // Index
10644       DAG.getTargetConstant(0, MVT::i32),  // Disp
10645       DAG.getRegister(0, MVT::i32),        // Segment.
10646       Zero,
10647       Chain
10648     };
10649     SDNode *Res =
10650       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10651                           array_lengthof(Ops));
10652     return SDValue(Res, 0);
10653   }
10654
10655   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10656   if (!isDev)
10657     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10658
10659   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10660   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10661   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10662   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10663
10664   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10665   if (!Op1 && !Op2 && !Op3 && Op4)
10666     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10667
10668   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10669   if (Op1 && !Op2 && !Op3 && !Op4)
10670     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10671
10672   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10673   //           (MFENCE)>;
10674   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10675 }
10676
10677 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10678                                              SelectionDAG &DAG) const {
10679   DebugLoc dl = Op.getDebugLoc();
10680   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10681     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10682   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10683     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10684
10685   // The only fence that needs an instruction is a sequentially-consistent
10686   // cross-thread fence.
10687   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10688     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10689     // no-sse2). There isn't any reason to disable it if the target processor
10690     // supports it.
10691     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10692       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10693
10694     SDValue Chain = Op.getOperand(0);
10695     SDValue Zero = DAG.getConstant(0, MVT::i32);
10696     SDValue Ops[] = {
10697       DAG.getRegister(X86::ESP, MVT::i32), // Base
10698       DAG.getTargetConstant(1, MVT::i8),   // Scale
10699       DAG.getRegister(0, MVT::i32),        // Index
10700       DAG.getTargetConstant(0, MVT::i32),  // Disp
10701       DAG.getRegister(0, MVT::i32),        // Segment.
10702       Zero,
10703       Chain
10704     };
10705     SDNode *Res =
10706       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10707                          array_lengthof(Ops));
10708     return SDValue(Res, 0);
10709   }
10710
10711   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10712   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10713 }
10714
10715
10716 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10717   EVT T = Op.getValueType();
10718   DebugLoc DL = Op.getDebugLoc();
10719   unsigned Reg = 0;
10720   unsigned size = 0;
10721   switch(T.getSimpleVT().SimpleTy) {
10722   default: llvm_unreachable("Invalid value type!");
10723   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10724   case MVT::i16: Reg = X86::AX;  size = 2; break;
10725   case MVT::i32: Reg = X86::EAX; size = 4; break;
10726   case MVT::i64:
10727     assert(Subtarget->is64Bit() && "Node not type legal!");
10728     Reg = X86::RAX; size = 8;
10729     break;
10730   }
10731   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10732                                     Op.getOperand(2), SDValue());
10733   SDValue Ops[] = { cpIn.getValue(0),
10734                     Op.getOperand(1),
10735                     Op.getOperand(3),
10736                     DAG.getTargetConstant(size, MVT::i8),
10737                     cpIn.getValue(1) };
10738   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10739   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10740   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10741                                            Ops, 5, T, MMO);
10742   SDValue cpOut =
10743     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10744   return cpOut;
10745 }
10746
10747 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10748                                                  SelectionDAG &DAG) const {
10749   assert(Subtarget->is64Bit() && "Result not type legalized?");
10750   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10751   SDValue TheChain = Op.getOperand(0);
10752   DebugLoc dl = Op.getDebugLoc();
10753   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10754   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10755   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10756                                    rax.getValue(2));
10757   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10758                             DAG.getConstant(32, MVT::i8));
10759   SDValue Ops[] = {
10760     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10761     rdx.getValue(1)
10762   };
10763   return DAG.getMergeValues(Ops, 2, dl);
10764 }
10765
10766 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10767                                             SelectionDAG &DAG) const {
10768   EVT SrcVT = Op.getOperand(0).getValueType();
10769   EVT DstVT = Op.getValueType();
10770   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10771          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10772   assert((DstVT == MVT::i64 ||
10773           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10774          "Unexpected custom BITCAST");
10775   // i64 <=> MMX conversions are Legal.
10776   if (SrcVT==MVT::i64 && DstVT.isVector())
10777     return Op;
10778   if (DstVT==MVT::i64 && SrcVT.isVector())
10779     return Op;
10780   // MMX <=> MMX conversions are Legal.
10781   if (SrcVT.isVector() && DstVT.isVector())
10782     return Op;
10783   // All other conversions need to be expanded.
10784   return SDValue();
10785 }
10786
10787 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10788   SDNode *Node = Op.getNode();
10789   DebugLoc dl = Node->getDebugLoc();
10790   EVT T = Node->getValueType(0);
10791   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10792                               DAG.getConstant(0, T), Node->getOperand(2));
10793   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10794                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10795                        Node->getOperand(0),
10796                        Node->getOperand(1), negOp,
10797                        cast<AtomicSDNode>(Node)->getSrcValue(),
10798                        cast<AtomicSDNode>(Node)->getAlignment(),
10799                        cast<AtomicSDNode>(Node)->getOrdering(),
10800                        cast<AtomicSDNode>(Node)->getSynchScope());
10801 }
10802
10803 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10804   SDNode *Node = Op.getNode();
10805   DebugLoc dl = Node->getDebugLoc();
10806   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10807
10808   // Convert seq_cst store -> xchg
10809   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10810   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10811   //        (The only way to get a 16-byte store is cmpxchg16b)
10812   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10813   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10814       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10815     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10816                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10817                                  Node->getOperand(0),
10818                                  Node->getOperand(1), Node->getOperand(2),
10819                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10820                                  cast<AtomicSDNode>(Node)->getOrdering(),
10821                                  cast<AtomicSDNode>(Node)->getSynchScope());
10822     return Swap.getValue(1);
10823   }
10824   // Other atomic stores have a simple pattern.
10825   return Op;
10826 }
10827
10828 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10829   EVT VT = Op.getNode()->getValueType(0);
10830
10831   // Let legalize expand this if it isn't a legal type yet.
10832   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10833     return SDValue();
10834
10835   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10836
10837   unsigned Opc;
10838   bool ExtraOp = false;
10839   switch (Op.getOpcode()) {
10840   default: llvm_unreachable("Invalid code");
10841   case ISD::ADDC: Opc = X86ISD::ADD; break;
10842   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10843   case ISD::SUBC: Opc = X86ISD::SUB; break;
10844   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10845   }
10846
10847   if (!ExtraOp)
10848     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10849                        Op.getOperand(1));
10850   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10851                      Op.getOperand(1), Op.getOperand(2));
10852 }
10853
10854 /// LowerOperation - Provide custom lowering hooks for some operations.
10855 ///
10856 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10857   switch (Op.getOpcode()) {
10858   default: llvm_unreachable("Should not custom lower this!");
10859   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10860   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10861   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10862   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10863   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10864   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10865   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10866   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10867   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10868   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10869   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10870   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10871   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10872   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10873   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10874   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10875   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10876   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10877   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10878   case ISD::SHL_PARTS:
10879   case ISD::SRA_PARTS:
10880   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10881   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10882   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10883   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10884   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10885   case ISD::FABS:               return LowerFABS(Op, DAG);
10886   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10887   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10888   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10889   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10890   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10891   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10892   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10893   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10894   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10895   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10896   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10897   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10898   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10899   case ISD::FRAME_TO_ARGS_OFFSET:
10900                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10901   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10902   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10903   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10904   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10905   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10906   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10907   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
10908   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10909   case ISD::MUL:                return LowerMUL(Op, DAG);
10910   case ISD::SRA:
10911   case ISD::SRL:
10912   case ISD::SHL:                return LowerShift(Op, DAG);
10913   case ISD::SADDO:
10914   case ISD::UADDO:
10915   case ISD::SSUBO:
10916   case ISD::USUBO:
10917   case ISD::SMULO:
10918   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10919   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10920   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10921   case ISD::ADDC:
10922   case ISD::ADDE:
10923   case ISD::SUBC:
10924   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10925   case ISD::ADD:                return LowerADD(Op, DAG);
10926   case ISD::SUB:                return LowerSUB(Op, DAG);
10927   }
10928 }
10929
10930 static void ReplaceATOMIC_LOAD(SDNode *Node,
10931                                   SmallVectorImpl<SDValue> &Results,
10932                                   SelectionDAG &DAG) {
10933   DebugLoc dl = Node->getDebugLoc();
10934   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10935
10936   // Convert wide load -> cmpxchg8b/cmpxchg16b
10937   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10938   //        (The only way to get a 16-byte load is cmpxchg16b)
10939   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10940   SDValue Zero = DAG.getConstant(0, VT);
10941   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10942                                Node->getOperand(0),
10943                                Node->getOperand(1), Zero, Zero,
10944                                cast<AtomicSDNode>(Node)->getMemOperand(),
10945                                cast<AtomicSDNode>(Node)->getOrdering(),
10946                                cast<AtomicSDNode>(Node)->getSynchScope());
10947   Results.push_back(Swap.getValue(0));
10948   Results.push_back(Swap.getValue(1));
10949 }
10950
10951 void X86TargetLowering::
10952 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10953                         SelectionDAG &DAG, unsigned NewOp) const {
10954   DebugLoc dl = Node->getDebugLoc();
10955   assert (Node->getValueType(0) == MVT::i64 &&
10956           "Only know how to expand i64 atomics");
10957
10958   SDValue Chain = Node->getOperand(0);
10959   SDValue In1 = Node->getOperand(1);
10960   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10961                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10962   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10963                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10964   SDValue Ops[] = { Chain, In1, In2L, In2H };
10965   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10966   SDValue Result =
10967     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10968                             cast<MemSDNode>(Node)->getMemOperand());
10969   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10970   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10971   Results.push_back(Result.getValue(2));
10972 }
10973
10974 /// ReplaceNodeResults - Replace a node with an illegal result type
10975 /// with a new node built out of custom code.
10976 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10977                                            SmallVectorImpl<SDValue>&Results,
10978                                            SelectionDAG &DAG) const {
10979   DebugLoc dl = N->getDebugLoc();
10980   switch (N->getOpcode()) {
10981   default:
10982     llvm_unreachable("Do not know how to custom type legalize this operation!");
10983   case ISD::SIGN_EXTEND_INREG:
10984   case ISD::ADDC:
10985   case ISD::ADDE:
10986   case ISD::SUBC:
10987   case ISD::SUBE:
10988     // We don't want to expand or promote these.
10989     return;
10990   case ISD::FP_TO_SINT:
10991   case ISD::FP_TO_UINT: {
10992     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
10993
10994     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
10995       return;
10996
10997     std::pair<SDValue,SDValue> Vals =
10998         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
10999     SDValue FIST = Vals.first, StackSlot = Vals.second;
11000     if (FIST.getNode() != 0) {
11001       EVT VT = N->getValueType(0);
11002       // Return a load from the stack slot.
11003       if (StackSlot.getNode() != 0)
11004         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11005                                       MachinePointerInfo(),
11006                                       false, false, false, 0));
11007       else
11008         Results.push_back(FIST);
11009     }
11010     return;
11011   }
11012   case ISD::READCYCLECOUNTER: {
11013     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11014     SDValue TheChain = N->getOperand(0);
11015     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11016     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11017                                      rd.getValue(1));
11018     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11019                                      eax.getValue(2));
11020     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11021     SDValue Ops[] = { eax, edx };
11022     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11023     Results.push_back(edx.getValue(1));
11024     return;
11025   }
11026   case ISD::ATOMIC_CMP_SWAP: {
11027     EVT T = N->getValueType(0);
11028     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11029     bool Regs64bit = T == MVT::i128;
11030     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11031     SDValue cpInL, cpInH;
11032     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11033                         DAG.getConstant(0, HalfT));
11034     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11035                         DAG.getConstant(1, HalfT));
11036     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11037                              Regs64bit ? X86::RAX : X86::EAX,
11038                              cpInL, SDValue());
11039     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11040                              Regs64bit ? X86::RDX : X86::EDX,
11041                              cpInH, cpInL.getValue(1));
11042     SDValue swapInL, swapInH;
11043     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11044                           DAG.getConstant(0, HalfT));
11045     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11046                           DAG.getConstant(1, HalfT));
11047     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11048                                Regs64bit ? X86::RBX : X86::EBX,
11049                                swapInL, cpInH.getValue(1));
11050     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11051                                Regs64bit ? X86::RCX : X86::ECX, 
11052                                swapInH, swapInL.getValue(1));
11053     SDValue Ops[] = { swapInH.getValue(0),
11054                       N->getOperand(1),
11055                       swapInH.getValue(1) };
11056     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11057     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11058     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11059                                   X86ISD::LCMPXCHG8_DAG;
11060     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11061                                              Ops, 3, T, MMO);
11062     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11063                                         Regs64bit ? X86::RAX : X86::EAX,
11064                                         HalfT, Result.getValue(1));
11065     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11066                                         Regs64bit ? X86::RDX : X86::EDX,
11067                                         HalfT, cpOutL.getValue(2));
11068     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11069     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11070     Results.push_back(cpOutH.getValue(1));
11071     return;
11072   }
11073   case ISD::ATOMIC_LOAD_ADD:
11074     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11075     return;
11076   case ISD::ATOMIC_LOAD_AND:
11077     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11078     return;
11079   case ISD::ATOMIC_LOAD_NAND:
11080     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11081     return;
11082   case ISD::ATOMIC_LOAD_OR:
11083     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11084     return;
11085   case ISD::ATOMIC_LOAD_SUB:
11086     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11087     return;
11088   case ISD::ATOMIC_LOAD_XOR:
11089     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11090     return;
11091   case ISD::ATOMIC_SWAP:
11092     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11093     return;
11094   case ISD::ATOMIC_LOAD:
11095     ReplaceATOMIC_LOAD(N, Results, DAG);
11096   }
11097 }
11098
11099 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11100   switch (Opcode) {
11101   default: return NULL;
11102   case X86ISD::BSF:                return "X86ISD::BSF";
11103   case X86ISD::BSR:                return "X86ISD::BSR";
11104   case X86ISD::SHLD:               return "X86ISD::SHLD";
11105   case X86ISD::SHRD:               return "X86ISD::SHRD";
11106   case X86ISD::FAND:               return "X86ISD::FAND";
11107   case X86ISD::FOR:                return "X86ISD::FOR";
11108   case X86ISD::FXOR:               return "X86ISD::FXOR";
11109   case X86ISD::FSRL:               return "X86ISD::FSRL";
11110   case X86ISD::FILD:               return "X86ISD::FILD";
11111   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11112   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11113   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11114   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11115   case X86ISD::FLD:                return "X86ISD::FLD";
11116   case X86ISD::FST:                return "X86ISD::FST";
11117   case X86ISD::CALL:               return "X86ISD::CALL";
11118   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11119   case X86ISD::BT:                 return "X86ISD::BT";
11120   case X86ISD::CMP:                return "X86ISD::CMP";
11121   case X86ISD::COMI:               return "X86ISD::COMI";
11122   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11123   case X86ISD::SETCC:              return "X86ISD::SETCC";
11124   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11125   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11126   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11127   case X86ISD::CMOV:               return "X86ISD::CMOV";
11128   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11129   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11130   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11131   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11132   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11133   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11134   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11135   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11136   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11137   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11138   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11139   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11140   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11141   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11142   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11143   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11144   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11145   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11146   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11147   case X86ISD::HADD:               return "X86ISD::HADD";
11148   case X86ISD::HSUB:               return "X86ISD::HSUB";
11149   case X86ISD::FHADD:              return "X86ISD::FHADD";
11150   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11151   case X86ISD::FMAX:               return "X86ISD::FMAX";
11152   case X86ISD::FMIN:               return "X86ISD::FMIN";
11153   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11154   case X86ISD::FRCP:               return "X86ISD::FRCP";
11155   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11156   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11157   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11158   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11159   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11160   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11161   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11162   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11163   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11164   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11165   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11166   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11167   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11168   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11169   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11170   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11171   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11172   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11173   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11174   case X86ISD::VSHL:               return "X86ISD::VSHL";
11175   case X86ISD::VSRL:               return "X86ISD::VSRL";
11176   case X86ISD::VSRA:               return "X86ISD::VSRA";
11177   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11178   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11179   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11180   case X86ISD::CMPP:               return "X86ISD::CMPP";
11181   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11182   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11183   case X86ISD::ADD:                return "X86ISD::ADD";
11184   case X86ISD::SUB:                return "X86ISD::SUB";
11185   case X86ISD::ADC:                return "X86ISD::ADC";
11186   case X86ISD::SBB:                return "X86ISD::SBB";
11187   case X86ISD::SMUL:               return "X86ISD::SMUL";
11188   case X86ISD::UMUL:               return "X86ISD::UMUL";
11189   case X86ISD::INC:                return "X86ISD::INC";
11190   case X86ISD::DEC:                return "X86ISD::DEC";
11191   case X86ISD::OR:                 return "X86ISD::OR";
11192   case X86ISD::XOR:                return "X86ISD::XOR";
11193   case X86ISD::AND:                return "X86ISD::AND";
11194   case X86ISD::ANDN:               return "X86ISD::ANDN";
11195   case X86ISD::BLSI:               return "X86ISD::BLSI";
11196   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11197   case X86ISD::BLSR:               return "X86ISD::BLSR";
11198   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11199   case X86ISD::PTEST:              return "X86ISD::PTEST";
11200   case X86ISD::TESTP:              return "X86ISD::TESTP";
11201   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11202   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11203   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11204   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11205   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11206   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11207   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11208   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11209   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11210   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11211   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11212   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11213   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11214   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11215   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11216   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11217   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11218   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11219   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11220   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11221   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11222   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11223   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11224   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11225   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11226   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11227   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11228   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11229   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11230   case X86ISD::SAHF:               return "X86ISD::SAHF";
11231   }
11232 }
11233
11234 // isLegalAddressingMode - Return true if the addressing mode represented
11235 // by AM is legal for this target, for a load/store of the specified type.
11236 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11237                                               Type *Ty) const {
11238   // X86 supports extremely general addressing modes.
11239   CodeModel::Model M = getTargetMachine().getCodeModel();
11240   Reloc::Model R = getTargetMachine().getRelocationModel();
11241
11242   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11243   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11244     return false;
11245
11246   if (AM.BaseGV) {
11247     unsigned GVFlags =
11248       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11249
11250     // If a reference to this global requires an extra load, we can't fold it.
11251     if (isGlobalStubReference(GVFlags))
11252       return false;
11253
11254     // If BaseGV requires a register for the PIC base, we cannot also have a
11255     // BaseReg specified.
11256     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11257       return false;
11258
11259     // If lower 4G is not available, then we must use rip-relative addressing.
11260     if ((M != CodeModel::Small || R != Reloc::Static) &&
11261         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11262       return false;
11263   }
11264
11265   switch (AM.Scale) {
11266   case 0:
11267   case 1:
11268   case 2:
11269   case 4:
11270   case 8:
11271     // These scales always work.
11272     break;
11273   case 3:
11274   case 5:
11275   case 9:
11276     // These scales are formed with basereg+scalereg.  Only accept if there is
11277     // no basereg yet.
11278     if (AM.HasBaseReg)
11279       return false;
11280     break;
11281   default:  // Other stuff never works.
11282     return false;
11283   }
11284
11285   return true;
11286 }
11287
11288
11289 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11290   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11291     return false;
11292   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11293   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11294   if (NumBits1 <= NumBits2)
11295     return false;
11296   return true;
11297 }
11298
11299 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11300   if (!VT1.isInteger() || !VT2.isInteger())
11301     return false;
11302   unsigned NumBits1 = VT1.getSizeInBits();
11303   unsigned NumBits2 = VT2.getSizeInBits();
11304   if (NumBits1 <= NumBits2)
11305     return false;
11306   return true;
11307 }
11308
11309 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11310   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11311   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11312 }
11313
11314 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11315   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11316   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11317 }
11318
11319 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11320   // i16 instructions are longer (0x66 prefix) and potentially slower.
11321   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11322 }
11323
11324 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11325 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11326 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11327 /// are assumed to be legal.
11328 bool
11329 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11330                                       EVT VT) const {
11331   // Very little shuffling can be done for 64-bit vectors right now.
11332   if (VT.getSizeInBits() == 64)
11333     return false;
11334
11335   // FIXME: pshufb, blends, shifts.
11336   return (VT.getVectorNumElements() == 2 ||
11337           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11338           isMOVLMask(M, VT) ||
11339           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11340           isPSHUFDMask(M, VT) ||
11341           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11342           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11343           isPALIGNRMask(M, VT, Subtarget) ||
11344           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11345           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11346           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11347           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11348 }
11349
11350 bool
11351 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11352                                           EVT VT) const {
11353   unsigned NumElts = VT.getVectorNumElements();
11354   // FIXME: This collection of masks seems suspect.
11355   if (NumElts == 2)
11356     return true;
11357   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11358     return (isMOVLMask(Mask, VT)  ||
11359             isCommutedMOVLMask(Mask, VT, true) ||
11360             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11361             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11362   }
11363   return false;
11364 }
11365
11366 //===----------------------------------------------------------------------===//
11367 //                           X86 Scheduler Hooks
11368 //===----------------------------------------------------------------------===//
11369
11370 // private utility function
11371 MachineBasicBlock *
11372 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11373                                                        MachineBasicBlock *MBB,
11374                                                        unsigned regOpc,
11375                                                        unsigned immOpc,
11376                                                        unsigned LoadOpc,
11377                                                        unsigned CXchgOpc,
11378                                                        unsigned notOpc,
11379                                                        unsigned EAXreg,
11380                                                  const TargetRegisterClass *RC,
11381                                                        bool Invert) const {
11382   // For the atomic bitwise operator, we generate
11383   //   thisMBB:
11384   //   newMBB:
11385   //     ld  t1 = [bitinstr.addr]
11386   //     op  t2 = t1, [bitinstr.val]
11387   //     not t3 = t2  (if Invert)
11388   //     mov EAX = t1
11389   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11390   //     bz  newMBB
11391   //     fallthrough -->nextMBB
11392   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11393   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11394   MachineFunction::iterator MBBIter = MBB;
11395   ++MBBIter;
11396
11397   /// First build the CFG
11398   MachineFunction *F = MBB->getParent();
11399   MachineBasicBlock *thisMBB = MBB;
11400   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11401   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11402   F->insert(MBBIter, newMBB);
11403   F->insert(MBBIter, nextMBB);
11404
11405   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11406   nextMBB->splice(nextMBB->begin(), thisMBB,
11407                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11408                   thisMBB->end());
11409   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11410
11411   // Update thisMBB to fall through to newMBB
11412   thisMBB->addSuccessor(newMBB);
11413
11414   // newMBB jumps to itself and fall through to nextMBB
11415   newMBB->addSuccessor(nextMBB);
11416   newMBB->addSuccessor(newMBB);
11417
11418   // Insert instructions into newMBB based on incoming instruction
11419   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11420          "unexpected number of operands");
11421   DebugLoc dl = bInstr->getDebugLoc();
11422   MachineOperand& destOper = bInstr->getOperand(0);
11423   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11424   int numArgs = bInstr->getNumOperands() - 1;
11425   for (int i=0; i < numArgs; ++i)
11426     argOpers[i] = &bInstr->getOperand(i+1);
11427
11428   // x86 address has 4 operands: base, index, scale, and displacement
11429   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11430   int valArgIndx = lastAddrIndx + 1;
11431
11432   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11433   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11434   for (int i=0; i <= lastAddrIndx; ++i)
11435     (*MIB).addOperand(*argOpers[i]);
11436
11437   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11438   assert((argOpers[valArgIndx]->isReg() ||
11439           argOpers[valArgIndx]->isImm()) &&
11440          "invalid operand");
11441   if (argOpers[valArgIndx]->isReg())
11442     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11443   else
11444     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11445   MIB.addReg(t1);
11446   (*MIB).addOperand(*argOpers[valArgIndx]);
11447
11448   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11449   if (Invert) {
11450     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11451   }
11452   else
11453     t3 = t2;
11454
11455   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11456   MIB.addReg(t1);
11457
11458   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11459   for (int i=0; i <= lastAddrIndx; ++i)
11460     (*MIB).addOperand(*argOpers[i]);
11461   MIB.addReg(t3);
11462   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11463   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11464                     bInstr->memoperands_end());
11465
11466   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11467   MIB.addReg(EAXreg);
11468
11469   // insert branch
11470   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11471
11472   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11473   return nextMBB;
11474 }
11475
11476 // private utility function:  64 bit atomics on 32 bit host.
11477 MachineBasicBlock *
11478 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11479                                                        MachineBasicBlock *MBB,
11480                                                        unsigned regOpcL,
11481                                                        unsigned regOpcH,
11482                                                        unsigned immOpcL,
11483                                                        unsigned immOpcH,
11484                                                        bool Invert) const {
11485   // For the atomic bitwise operator, we generate
11486   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11487   //     ld t1,t2 = [bitinstr.addr]
11488   //   newMBB:
11489   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11490   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11491   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11492   //     neg t7, t8 < t5, t6  (if Invert)
11493   //     mov ECX, EBX <- t5, t6
11494   //     mov EAX, EDX <- t1, t2
11495   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11496   //     mov t3, t4 <- EAX, EDX
11497   //     bz  newMBB
11498   //     result in out1, out2
11499   //     fallthrough -->nextMBB
11500
11501   const TargetRegisterClass *RC = &X86::GR32RegClass;
11502   const unsigned LoadOpc = X86::MOV32rm;
11503   const unsigned NotOpc = X86::NOT32r;
11504   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11505   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11506   MachineFunction::iterator MBBIter = MBB;
11507   ++MBBIter;
11508
11509   /// First build the CFG
11510   MachineFunction *F = MBB->getParent();
11511   MachineBasicBlock *thisMBB = MBB;
11512   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11513   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11514   F->insert(MBBIter, newMBB);
11515   F->insert(MBBIter, nextMBB);
11516
11517   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11518   nextMBB->splice(nextMBB->begin(), thisMBB,
11519                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11520                   thisMBB->end());
11521   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11522
11523   // Update thisMBB to fall through to newMBB
11524   thisMBB->addSuccessor(newMBB);
11525
11526   // newMBB jumps to itself and fall through to nextMBB
11527   newMBB->addSuccessor(nextMBB);
11528   newMBB->addSuccessor(newMBB);
11529
11530   DebugLoc dl = bInstr->getDebugLoc();
11531   // Insert instructions into newMBB based on incoming instruction
11532   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11533   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11534          "unexpected number of operands");
11535   MachineOperand& dest1Oper = bInstr->getOperand(0);
11536   MachineOperand& dest2Oper = bInstr->getOperand(1);
11537   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11538   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11539     argOpers[i] = &bInstr->getOperand(i+2);
11540
11541     // We use some of the operands multiple times, so conservatively just
11542     // clear any kill flags that might be present.
11543     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11544       argOpers[i]->setIsKill(false);
11545   }
11546
11547   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11548   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11549
11550   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11551   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11552   for (int i=0; i <= lastAddrIndx; ++i)
11553     (*MIB).addOperand(*argOpers[i]);
11554   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11555   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11556   // add 4 to displacement.
11557   for (int i=0; i <= lastAddrIndx-2; ++i)
11558     (*MIB).addOperand(*argOpers[i]);
11559   MachineOperand newOp3 = *(argOpers[3]);
11560   if (newOp3.isImm())
11561     newOp3.setImm(newOp3.getImm()+4);
11562   else
11563     newOp3.setOffset(newOp3.getOffset()+4);
11564   (*MIB).addOperand(newOp3);
11565   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11566
11567   // t3/4 are defined later, at the bottom of the loop
11568   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11569   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11570   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11571     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11572   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11573     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11574
11575   // The subsequent operations should be using the destination registers of
11576   // the PHI instructions.
11577   t1 = dest1Oper.getReg();
11578   t2 = dest2Oper.getReg();
11579
11580   int valArgIndx = lastAddrIndx + 1;
11581   assert((argOpers[valArgIndx]->isReg() ||
11582           argOpers[valArgIndx]->isImm()) &&
11583          "invalid operand");
11584   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11585   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11586   if (argOpers[valArgIndx]->isReg())
11587     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11588   else
11589     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11590   if (regOpcL != X86::MOV32rr)
11591     MIB.addReg(t1);
11592   (*MIB).addOperand(*argOpers[valArgIndx]);
11593   assert(argOpers[valArgIndx + 1]->isReg() ==
11594          argOpers[valArgIndx]->isReg());
11595   assert(argOpers[valArgIndx + 1]->isImm() ==
11596          argOpers[valArgIndx]->isImm());
11597   if (argOpers[valArgIndx + 1]->isReg())
11598     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11599   else
11600     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11601   if (regOpcH != X86::MOV32rr)
11602     MIB.addReg(t2);
11603   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11604
11605   unsigned t7, t8;
11606   if (Invert) {
11607     t7 = F->getRegInfo().createVirtualRegister(RC);
11608     t8 = F->getRegInfo().createVirtualRegister(RC);
11609     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11610     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11611   } else {
11612     t7 = t5;
11613     t8 = t6;
11614   }
11615
11616   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11617   MIB.addReg(t1);
11618   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11619   MIB.addReg(t2);
11620
11621   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11622   MIB.addReg(t7);
11623   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11624   MIB.addReg(t8);
11625
11626   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11627   for (int i=0; i <= lastAddrIndx; ++i)
11628     (*MIB).addOperand(*argOpers[i]);
11629
11630   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11631   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11632                     bInstr->memoperands_end());
11633
11634   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11635   MIB.addReg(X86::EAX);
11636   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11637   MIB.addReg(X86::EDX);
11638
11639   // insert branch
11640   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11641
11642   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11643   return nextMBB;
11644 }
11645
11646 // private utility function
11647 MachineBasicBlock *
11648 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11649                                                       MachineBasicBlock *MBB,
11650                                                       unsigned cmovOpc) const {
11651   // For the atomic min/max operator, we generate
11652   //   thisMBB:
11653   //   newMBB:
11654   //     ld t1 = [min/max.addr]
11655   //     mov t2 = [min/max.val]
11656   //     cmp  t1, t2
11657   //     cmov[cond] t2 = t1
11658   //     mov EAX = t1
11659   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11660   //     bz   newMBB
11661   //     fallthrough -->nextMBB
11662   //
11663   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11664   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11665   MachineFunction::iterator MBBIter = MBB;
11666   ++MBBIter;
11667
11668   /// First build the CFG
11669   MachineFunction *F = MBB->getParent();
11670   MachineBasicBlock *thisMBB = MBB;
11671   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11672   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11673   F->insert(MBBIter, newMBB);
11674   F->insert(MBBIter, nextMBB);
11675
11676   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11677   nextMBB->splice(nextMBB->begin(), thisMBB,
11678                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11679                   thisMBB->end());
11680   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11681
11682   // Update thisMBB to fall through to newMBB
11683   thisMBB->addSuccessor(newMBB);
11684
11685   // newMBB jumps to newMBB and fall through to nextMBB
11686   newMBB->addSuccessor(nextMBB);
11687   newMBB->addSuccessor(newMBB);
11688
11689   DebugLoc dl = mInstr->getDebugLoc();
11690   // Insert instructions into newMBB based on incoming instruction
11691   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11692          "unexpected number of operands");
11693   MachineOperand& destOper = mInstr->getOperand(0);
11694   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11695   int numArgs = mInstr->getNumOperands() - 1;
11696   for (int i=0; i < numArgs; ++i)
11697     argOpers[i] = &mInstr->getOperand(i+1);
11698
11699   // x86 address has 4 operands: base, index, scale, and displacement
11700   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11701   int valArgIndx = lastAddrIndx + 1;
11702
11703   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11704   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11705   for (int i=0; i <= lastAddrIndx; ++i)
11706     (*MIB).addOperand(*argOpers[i]);
11707
11708   // We only support register and immediate values
11709   assert((argOpers[valArgIndx]->isReg() ||
11710           argOpers[valArgIndx]->isImm()) &&
11711          "invalid operand");
11712
11713   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11714   if (argOpers[valArgIndx]->isReg())
11715     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11716   else
11717     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11718   (*MIB).addOperand(*argOpers[valArgIndx]);
11719
11720   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11721   MIB.addReg(t1);
11722
11723   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11724   MIB.addReg(t1);
11725   MIB.addReg(t2);
11726
11727   // Generate movc
11728   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11729   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11730   MIB.addReg(t2);
11731   MIB.addReg(t1);
11732
11733   // Cmp and exchange if none has modified the memory location
11734   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11735   for (int i=0; i <= lastAddrIndx; ++i)
11736     (*MIB).addOperand(*argOpers[i]);
11737   MIB.addReg(t3);
11738   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11739   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11740                     mInstr->memoperands_end());
11741
11742   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11743   MIB.addReg(X86::EAX);
11744
11745   // insert branch
11746   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11747
11748   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11749   return nextMBB;
11750 }
11751
11752 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11753 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11754 // in the .td file.
11755 MachineBasicBlock *
11756 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11757                             unsigned numArgs, bool memArg) const {
11758   assert(Subtarget->hasSSE42() &&
11759          "Target must have SSE4.2 or AVX features enabled");
11760
11761   DebugLoc dl = MI->getDebugLoc();
11762   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11763   unsigned Opc;
11764   if (!Subtarget->hasAVX()) {
11765     if (memArg)
11766       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11767     else
11768       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11769   } else {
11770     if (memArg)
11771       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11772     else
11773       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11774   }
11775
11776   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11777   for (unsigned i = 0; i < numArgs; ++i) {
11778     MachineOperand &Op = MI->getOperand(i+1);
11779     if (!(Op.isReg() && Op.isImplicit()))
11780       MIB.addOperand(Op);
11781   }
11782   BuildMI(*BB, MI, dl,
11783     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11784              MI->getOperand(0).getReg())
11785     .addReg(X86::XMM0);
11786
11787   MI->eraseFromParent();
11788   return BB;
11789 }
11790
11791 MachineBasicBlock *
11792 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11793   DebugLoc dl = MI->getDebugLoc();
11794   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11795
11796   // Address into RAX/EAX, other two args into ECX, EDX.
11797   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11798   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11799   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11800   for (int i = 0; i < X86::AddrNumOperands; ++i)
11801     MIB.addOperand(MI->getOperand(i));
11802
11803   unsigned ValOps = X86::AddrNumOperands;
11804   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11805     .addReg(MI->getOperand(ValOps).getReg());
11806   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11807     .addReg(MI->getOperand(ValOps+1).getReg());
11808
11809   // The instruction doesn't actually take any operands though.
11810   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11811
11812   MI->eraseFromParent(); // The pseudo is gone now.
11813   return BB;
11814 }
11815
11816 MachineBasicBlock *
11817 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11818   DebugLoc dl = MI->getDebugLoc();
11819   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11820
11821   // First arg in ECX, the second in EAX.
11822   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11823     .addReg(MI->getOperand(0).getReg());
11824   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11825     .addReg(MI->getOperand(1).getReg());
11826
11827   // The instruction doesn't actually take any operands though.
11828   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11829
11830   MI->eraseFromParent(); // The pseudo is gone now.
11831   return BB;
11832 }
11833
11834 MachineBasicBlock *
11835 X86TargetLowering::EmitVAARG64WithCustomInserter(
11836                    MachineInstr *MI,
11837                    MachineBasicBlock *MBB) const {
11838   // Emit va_arg instruction on X86-64.
11839
11840   // Operands to this pseudo-instruction:
11841   // 0  ) Output        : destination address (reg)
11842   // 1-5) Input         : va_list address (addr, i64mem)
11843   // 6  ) ArgSize       : Size (in bytes) of vararg type
11844   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11845   // 8  ) Align         : Alignment of type
11846   // 9  ) EFLAGS (implicit-def)
11847
11848   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11849   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11850
11851   unsigned DestReg = MI->getOperand(0).getReg();
11852   MachineOperand &Base = MI->getOperand(1);
11853   MachineOperand &Scale = MI->getOperand(2);
11854   MachineOperand &Index = MI->getOperand(3);
11855   MachineOperand &Disp = MI->getOperand(4);
11856   MachineOperand &Segment = MI->getOperand(5);
11857   unsigned ArgSize = MI->getOperand(6).getImm();
11858   unsigned ArgMode = MI->getOperand(7).getImm();
11859   unsigned Align = MI->getOperand(8).getImm();
11860
11861   // Memory Reference
11862   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11863   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11864   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11865
11866   // Machine Information
11867   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11868   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11869   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11870   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11871   DebugLoc DL = MI->getDebugLoc();
11872
11873   // struct va_list {
11874   //   i32   gp_offset
11875   //   i32   fp_offset
11876   //   i64   overflow_area (address)
11877   //   i64   reg_save_area (address)
11878   // }
11879   // sizeof(va_list) = 24
11880   // alignment(va_list) = 8
11881
11882   unsigned TotalNumIntRegs = 6;
11883   unsigned TotalNumXMMRegs = 8;
11884   bool UseGPOffset = (ArgMode == 1);
11885   bool UseFPOffset = (ArgMode == 2);
11886   unsigned MaxOffset = TotalNumIntRegs * 8 +
11887                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11888
11889   /* Align ArgSize to a multiple of 8 */
11890   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11891   bool NeedsAlign = (Align > 8);
11892
11893   MachineBasicBlock *thisMBB = MBB;
11894   MachineBasicBlock *overflowMBB;
11895   MachineBasicBlock *offsetMBB;
11896   MachineBasicBlock *endMBB;
11897
11898   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11899   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11900   unsigned OffsetReg = 0;
11901
11902   if (!UseGPOffset && !UseFPOffset) {
11903     // If we only pull from the overflow region, we don't create a branch.
11904     // We don't need to alter control flow.
11905     OffsetDestReg = 0; // unused
11906     OverflowDestReg = DestReg;
11907
11908     offsetMBB = NULL;
11909     overflowMBB = thisMBB;
11910     endMBB = thisMBB;
11911   } else {
11912     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11913     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11914     // If not, pull from overflow_area. (branch to overflowMBB)
11915     //
11916     //       thisMBB
11917     //         |     .
11918     //         |        .
11919     //     offsetMBB   overflowMBB
11920     //         |        .
11921     //         |     .
11922     //        endMBB
11923
11924     // Registers for the PHI in endMBB
11925     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11926     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11927
11928     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11929     MachineFunction *MF = MBB->getParent();
11930     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11931     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11932     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11933
11934     MachineFunction::iterator MBBIter = MBB;
11935     ++MBBIter;
11936
11937     // Insert the new basic blocks
11938     MF->insert(MBBIter, offsetMBB);
11939     MF->insert(MBBIter, overflowMBB);
11940     MF->insert(MBBIter, endMBB);
11941
11942     // Transfer the remainder of MBB and its successor edges to endMBB.
11943     endMBB->splice(endMBB->begin(), thisMBB,
11944                     llvm::next(MachineBasicBlock::iterator(MI)),
11945                     thisMBB->end());
11946     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11947
11948     // Make offsetMBB and overflowMBB successors of thisMBB
11949     thisMBB->addSuccessor(offsetMBB);
11950     thisMBB->addSuccessor(overflowMBB);
11951
11952     // endMBB is a successor of both offsetMBB and overflowMBB
11953     offsetMBB->addSuccessor(endMBB);
11954     overflowMBB->addSuccessor(endMBB);
11955
11956     // Load the offset value into a register
11957     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11958     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11959       .addOperand(Base)
11960       .addOperand(Scale)
11961       .addOperand(Index)
11962       .addDisp(Disp, UseFPOffset ? 4 : 0)
11963       .addOperand(Segment)
11964       .setMemRefs(MMOBegin, MMOEnd);
11965
11966     // Check if there is enough room left to pull this argument.
11967     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11968       .addReg(OffsetReg)
11969       .addImm(MaxOffset + 8 - ArgSizeA8);
11970
11971     // Branch to "overflowMBB" if offset >= max
11972     // Fall through to "offsetMBB" otherwise
11973     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11974       .addMBB(overflowMBB);
11975   }
11976
11977   // In offsetMBB, emit code to use the reg_save_area.
11978   if (offsetMBB) {
11979     assert(OffsetReg != 0);
11980
11981     // Read the reg_save_area address.
11982     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11983     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11984       .addOperand(Base)
11985       .addOperand(Scale)
11986       .addOperand(Index)
11987       .addDisp(Disp, 16)
11988       .addOperand(Segment)
11989       .setMemRefs(MMOBegin, MMOEnd);
11990
11991     // Zero-extend the offset
11992     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11993       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11994         .addImm(0)
11995         .addReg(OffsetReg)
11996         .addImm(X86::sub_32bit);
11997
11998     // Add the offset to the reg_save_area to get the final address.
11999     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12000       .addReg(OffsetReg64)
12001       .addReg(RegSaveReg);
12002
12003     // Compute the offset for the next argument
12004     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12005     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12006       .addReg(OffsetReg)
12007       .addImm(UseFPOffset ? 16 : 8);
12008
12009     // Store it back into the va_list.
12010     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12011       .addOperand(Base)
12012       .addOperand(Scale)
12013       .addOperand(Index)
12014       .addDisp(Disp, UseFPOffset ? 4 : 0)
12015       .addOperand(Segment)
12016       .addReg(NextOffsetReg)
12017       .setMemRefs(MMOBegin, MMOEnd);
12018
12019     // Jump to endMBB
12020     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12021       .addMBB(endMBB);
12022   }
12023
12024   //
12025   // Emit code to use overflow area
12026   //
12027
12028   // Load the overflow_area address into a register.
12029   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12030   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12031     .addOperand(Base)
12032     .addOperand(Scale)
12033     .addOperand(Index)
12034     .addDisp(Disp, 8)
12035     .addOperand(Segment)
12036     .setMemRefs(MMOBegin, MMOEnd);
12037
12038   // If we need to align it, do so. Otherwise, just copy the address
12039   // to OverflowDestReg.
12040   if (NeedsAlign) {
12041     // Align the overflow address
12042     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12043     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12044
12045     // aligned_addr = (addr + (align-1)) & ~(align-1)
12046     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12047       .addReg(OverflowAddrReg)
12048       .addImm(Align-1);
12049
12050     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12051       .addReg(TmpReg)
12052       .addImm(~(uint64_t)(Align-1));
12053   } else {
12054     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12055       .addReg(OverflowAddrReg);
12056   }
12057
12058   // Compute the next overflow address after this argument.
12059   // (the overflow address should be kept 8-byte aligned)
12060   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12061   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12062     .addReg(OverflowDestReg)
12063     .addImm(ArgSizeA8);
12064
12065   // Store the new overflow address.
12066   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12067     .addOperand(Base)
12068     .addOperand(Scale)
12069     .addOperand(Index)
12070     .addDisp(Disp, 8)
12071     .addOperand(Segment)
12072     .addReg(NextAddrReg)
12073     .setMemRefs(MMOBegin, MMOEnd);
12074
12075   // If we branched, emit the PHI to the front of endMBB.
12076   if (offsetMBB) {
12077     BuildMI(*endMBB, endMBB->begin(), DL,
12078             TII->get(X86::PHI), DestReg)
12079       .addReg(OffsetDestReg).addMBB(offsetMBB)
12080       .addReg(OverflowDestReg).addMBB(overflowMBB);
12081   }
12082
12083   // Erase the pseudo instruction
12084   MI->eraseFromParent();
12085
12086   return endMBB;
12087 }
12088
12089 MachineBasicBlock *
12090 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12091                                                  MachineInstr *MI,
12092                                                  MachineBasicBlock *MBB) const {
12093   // Emit code to save XMM registers to the stack. The ABI says that the
12094   // number of registers to save is given in %al, so it's theoretically
12095   // possible to do an indirect jump trick to avoid saving all of them,
12096   // however this code takes a simpler approach and just executes all
12097   // of the stores if %al is non-zero. It's less code, and it's probably
12098   // easier on the hardware branch predictor, and stores aren't all that
12099   // expensive anyway.
12100
12101   // Create the new basic blocks. One block contains all the XMM stores,
12102   // and one block is the final destination regardless of whether any
12103   // stores were performed.
12104   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12105   MachineFunction *F = MBB->getParent();
12106   MachineFunction::iterator MBBIter = MBB;
12107   ++MBBIter;
12108   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12109   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12110   F->insert(MBBIter, XMMSaveMBB);
12111   F->insert(MBBIter, EndMBB);
12112
12113   // Transfer the remainder of MBB and its successor edges to EndMBB.
12114   EndMBB->splice(EndMBB->begin(), MBB,
12115                  llvm::next(MachineBasicBlock::iterator(MI)),
12116                  MBB->end());
12117   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12118
12119   // The original block will now fall through to the XMM save block.
12120   MBB->addSuccessor(XMMSaveMBB);
12121   // The XMMSaveMBB will fall through to the end block.
12122   XMMSaveMBB->addSuccessor(EndMBB);
12123
12124   // Now add the instructions.
12125   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12126   DebugLoc DL = MI->getDebugLoc();
12127
12128   unsigned CountReg = MI->getOperand(0).getReg();
12129   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12130   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12131
12132   if (!Subtarget->isTargetWin64()) {
12133     // If %al is 0, branch around the XMM save block.
12134     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12135     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12136     MBB->addSuccessor(EndMBB);
12137   }
12138
12139   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12140   // In the XMM save block, save all the XMM argument registers.
12141   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12142     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12143     MachineMemOperand *MMO =
12144       F->getMachineMemOperand(
12145           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12146         MachineMemOperand::MOStore,
12147         /*Size=*/16, /*Align=*/16);
12148     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12149       .addFrameIndex(RegSaveFrameIndex)
12150       .addImm(/*Scale=*/1)
12151       .addReg(/*IndexReg=*/0)
12152       .addImm(/*Disp=*/Offset)
12153       .addReg(/*Segment=*/0)
12154       .addReg(MI->getOperand(i).getReg())
12155       .addMemOperand(MMO);
12156   }
12157
12158   MI->eraseFromParent();   // The pseudo instruction is gone now.
12159
12160   return EndMBB;
12161 }
12162
12163 // The EFLAGS operand of SelectItr might be missing a kill marker
12164 // because there were multiple uses of EFLAGS, and ISel didn't know
12165 // which to mark. Figure out whether SelectItr should have had a
12166 // kill marker, and set it if it should. Returns the correct kill
12167 // marker value.
12168 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12169                                      MachineBasicBlock* BB,
12170                                      const TargetRegisterInfo* TRI) {
12171   // Scan forward through BB for a use/def of EFLAGS.
12172   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12173   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12174     const MachineInstr& mi = *miI;
12175     if (mi.readsRegister(X86::EFLAGS))
12176       return false;
12177     if (mi.definesRegister(X86::EFLAGS))
12178       break; // Should have kill-flag - update below.
12179   }
12180
12181   // If we hit the end of the block, check whether EFLAGS is live into a
12182   // successor.
12183   if (miI == BB->end()) {
12184     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12185                                           sEnd = BB->succ_end();
12186          sItr != sEnd; ++sItr) {
12187       MachineBasicBlock* succ = *sItr;
12188       if (succ->isLiveIn(X86::EFLAGS))
12189         return false;
12190     }
12191   }
12192
12193   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12194   // out. SelectMI should have a kill flag on EFLAGS.
12195   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12196   return true;
12197 }
12198
12199 MachineBasicBlock *
12200 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12201                                      MachineBasicBlock *BB) const {
12202   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12203   DebugLoc DL = MI->getDebugLoc();
12204
12205   // To "insert" a SELECT_CC instruction, we actually have to insert the
12206   // diamond control-flow pattern.  The incoming instruction knows the
12207   // destination vreg to set, the condition code register to branch on, the
12208   // true/false values to select between, and a branch opcode to use.
12209   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12210   MachineFunction::iterator It = BB;
12211   ++It;
12212
12213   //  thisMBB:
12214   //  ...
12215   //   TrueVal = ...
12216   //   cmpTY ccX, r1, r2
12217   //   bCC copy1MBB
12218   //   fallthrough --> copy0MBB
12219   MachineBasicBlock *thisMBB = BB;
12220   MachineFunction *F = BB->getParent();
12221   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12222   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12223   F->insert(It, copy0MBB);
12224   F->insert(It, sinkMBB);
12225
12226   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12227   // live into the sink and copy blocks.
12228   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12229   if (!MI->killsRegister(X86::EFLAGS) &&
12230       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12231     copy0MBB->addLiveIn(X86::EFLAGS);
12232     sinkMBB->addLiveIn(X86::EFLAGS);
12233   }
12234
12235   // Transfer the remainder of BB and its successor edges to sinkMBB.
12236   sinkMBB->splice(sinkMBB->begin(), BB,
12237                   llvm::next(MachineBasicBlock::iterator(MI)),
12238                   BB->end());
12239   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12240
12241   // Add the true and fallthrough blocks as its successors.
12242   BB->addSuccessor(copy0MBB);
12243   BB->addSuccessor(sinkMBB);
12244
12245   // Create the conditional branch instruction.
12246   unsigned Opc =
12247     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12248   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12249
12250   //  copy0MBB:
12251   //   %FalseValue = ...
12252   //   # fallthrough to sinkMBB
12253   copy0MBB->addSuccessor(sinkMBB);
12254
12255   //  sinkMBB:
12256   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12257   //  ...
12258   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12259           TII->get(X86::PHI), MI->getOperand(0).getReg())
12260     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12261     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12262
12263   MI->eraseFromParent();   // The pseudo instruction is gone now.
12264   return sinkMBB;
12265 }
12266
12267 MachineBasicBlock *
12268 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12269                                         bool Is64Bit) const {
12270   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12271   DebugLoc DL = MI->getDebugLoc();
12272   MachineFunction *MF = BB->getParent();
12273   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12274
12275   assert(getTargetMachine().Options.EnableSegmentedStacks);
12276
12277   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12278   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12279
12280   // BB:
12281   //  ... [Till the alloca]
12282   // If stacklet is not large enough, jump to mallocMBB
12283   //
12284   // bumpMBB:
12285   //  Allocate by subtracting from RSP
12286   //  Jump to continueMBB
12287   //
12288   // mallocMBB:
12289   //  Allocate by call to runtime
12290   //
12291   // continueMBB:
12292   //  ...
12293   //  [rest of original BB]
12294   //
12295
12296   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12297   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12298   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12299
12300   MachineRegisterInfo &MRI = MF->getRegInfo();
12301   const TargetRegisterClass *AddrRegClass =
12302     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12303
12304   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12305     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12306     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12307     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12308     sizeVReg = MI->getOperand(1).getReg(),
12309     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12310
12311   MachineFunction::iterator MBBIter = BB;
12312   ++MBBIter;
12313
12314   MF->insert(MBBIter, bumpMBB);
12315   MF->insert(MBBIter, mallocMBB);
12316   MF->insert(MBBIter, continueMBB);
12317
12318   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12319                       (MachineBasicBlock::iterator(MI)), BB->end());
12320   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12321
12322   // Add code to the main basic block to check if the stack limit has been hit,
12323   // and if so, jump to mallocMBB otherwise to bumpMBB.
12324   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12325   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12326     .addReg(tmpSPVReg).addReg(sizeVReg);
12327   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12328     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12329     .addReg(SPLimitVReg);
12330   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12331
12332   // bumpMBB simply decreases the stack pointer, since we know the current
12333   // stacklet has enough space.
12334   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12335     .addReg(SPLimitVReg);
12336   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12337     .addReg(SPLimitVReg);
12338   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12339
12340   // Calls into a routine in libgcc to allocate more space from the heap.
12341   const uint32_t *RegMask =
12342     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12343   if (Is64Bit) {
12344     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12345       .addReg(sizeVReg);
12346     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12347       .addExternalSymbol("__morestack_allocate_stack_space")
12348       .addRegMask(RegMask)
12349       .addReg(X86::RDI, RegState::Implicit)
12350       .addReg(X86::RAX, RegState::ImplicitDefine);
12351   } else {
12352     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12353       .addImm(12);
12354     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12355     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12356       .addExternalSymbol("__morestack_allocate_stack_space")
12357       .addRegMask(RegMask)
12358       .addReg(X86::EAX, RegState::ImplicitDefine);
12359   }
12360
12361   if (!Is64Bit)
12362     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12363       .addImm(16);
12364
12365   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12366     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12367   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12368
12369   // Set up the CFG correctly.
12370   BB->addSuccessor(bumpMBB);
12371   BB->addSuccessor(mallocMBB);
12372   mallocMBB->addSuccessor(continueMBB);
12373   bumpMBB->addSuccessor(continueMBB);
12374
12375   // Take care of the PHI nodes.
12376   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12377           MI->getOperand(0).getReg())
12378     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12379     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12380
12381   // Delete the original pseudo instruction.
12382   MI->eraseFromParent();
12383
12384   // And we're done.
12385   return continueMBB;
12386 }
12387
12388 MachineBasicBlock *
12389 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12390                                           MachineBasicBlock *BB) const {
12391   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12392   DebugLoc DL = MI->getDebugLoc();
12393
12394   assert(!Subtarget->isTargetEnvMacho());
12395
12396   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12397   // non-trivial part is impdef of ESP.
12398
12399   if (Subtarget->isTargetWin64()) {
12400     if (Subtarget->isTargetCygMing()) {
12401       // ___chkstk(Mingw64):
12402       // Clobbers R10, R11, RAX and EFLAGS.
12403       // Updates RSP.
12404       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12405         .addExternalSymbol("___chkstk")
12406         .addReg(X86::RAX, RegState::Implicit)
12407         .addReg(X86::RSP, RegState::Implicit)
12408         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12409         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12410         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12411     } else {
12412       // __chkstk(MSVCRT): does not update stack pointer.
12413       // Clobbers R10, R11 and EFLAGS.
12414       // FIXME: RAX(allocated size) might be reused and not killed.
12415       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12416         .addExternalSymbol("__chkstk")
12417         .addReg(X86::RAX, RegState::Implicit)
12418         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12419       // RAX has the offset to subtracted from RSP.
12420       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12421         .addReg(X86::RSP)
12422         .addReg(X86::RAX);
12423     }
12424   } else {
12425     const char *StackProbeSymbol =
12426       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12427
12428     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12429       .addExternalSymbol(StackProbeSymbol)
12430       .addReg(X86::EAX, RegState::Implicit)
12431       .addReg(X86::ESP, RegState::Implicit)
12432       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12433       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12434       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12435   }
12436
12437   MI->eraseFromParent();   // The pseudo instruction is gone now.
12438   return BB;
12439 }
12440
12441 MachineBasicBlock *
12442 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12443                                       MachineBasicBlock *BB) const {
12444   // This is pretty easy.  We're taking the value that we received from
12445   // our load from the relocation, sticking it in either RDI (x86-64)
12446   // or EAX and doing an indirect call.  The return value will then
12447   // be in the normal return register.
12448   const X86InstrInfo *TII
12449     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12450   DebugLoc DL = MI->getDebugLoc();
12451   MachineFunction *F = BB->getParent();
12452
12453   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12454   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12455
12456   // Get a register mask for the lowered call.
12457   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12458   // proper register mask.
12459   const uint32_t *RegMask =
12460     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12461   if (Subtarget->is64Bit()) {
12462     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12463                                       TII->get(X86::MOV64rm), X86::RDI)
12464     .addReg(X86::RIP)
12465     .addImm(0).addReg(0)
12466     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12467                       MI->getOperand(3).getTargetFlags())
12468     .addReg(0);
12469     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12470     addDirectMem(MIB, X86::RDI);
12471     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12472   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12473     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12474                                       TII->get(X86::MOV32rm), X86::EAX)
12475     .addReg(0)
12476     .addImm(0).addReg(0)
12477     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12478                       MI->getOperand(3).getTargetFlags())
12479     .addReg(0);
12480     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12481     addDirectMem(MIB, X86::EAX);
12482     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12483   } else {
12484     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12485                                       TII->get(X86::MOV32rm), X86::EAX)
12486     .addReg(TII->getGlobalBaseReg(F))
12487     .addImm(0).addReg(0)
12488     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12489                       MI->getOperand(3).getTargetFlags())
12490     .addReg(0);
12491     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12492     addDirectMem(MIB, X86::EAX);
12493     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12494   }
12495
12496   MI->eraseFromParent(); // The pseudo instruction is gone now.
12497   return BB;
12498 }
12499
12500 MachineBasicBlock *
12501 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12502                                                MachineBasicBlock *BB) const {
12503   switch (MI->getOpcode()) {
12504   default: llvm_unreachable("Unexpected instr type to insert");
12505   case X86::TAILJMPd64:
12506   case X86::TAILJMPr64:
12507   case X86::TAILJMPm64:
12508     llvm_unreachable("TAILJMP64 would not be touched here.");
12509   case X86::TCRETURNdi64:
12510   case X86::TCRETURNri64:
12511   case X86::TCRETURNmi64:
12512     return BB;
12513   case X86::WIN_ALLOCA:
12514     return EmitLoweredWinAlloca(MI, BB);
12515   case X86::SEG_ALLOCA_32:
12516     return EmitLoweredSegAlloca(MI, BB, false);
12517   case X86::SEG_ALLOCA_64:
12518     return EmitLoweredSegAlloca(MI, BB, true);
12519   case X86::TLSCall_32:
12520   case X86::TLSCall_64:
12521     return EmitLoweredTLSCall(MI, BB);
12522   case X86::CMOV_GR8:
12523   case X86::CMOV_FR32:
12524   case X86::CMOV_FR64:
12525   case X86::CMOV_V4F32:
12526   case X86::CMOV_V2F64:
12527   case X86::CMOV_V2I64:
12528   case X86::CMOV_V8F32:
12529   case X86::CMOV_V4F64:
12530   case X86::CMOV_V4I64:
12531   case X86::CMOV_GR16:
12532   case X86::CMOV_GR32:
12533   case X86::CMOV_RFP32:
12534   case X86::CMOV_RFP64:
12535   case X86::CMOV_RFP80:
12536     return EmitLoweredSelect(MI, BB);
12537
12538   case X86::FP32_TO_INT16_IN_MEM:
12539   case X86::FP32_TO_INT32_IN_MEM:
12540   case X86::FP32_TO_INT64_IN_MEM:
12541   case X86::FP64_TO_INT16_IN_MEM:
12542   case X86::FP64_TO_INT32_IN_MEM:
12543   case X86::FP64_TO_INT64_IN_MEM:
12544   case X86::FP80_TO_INT16_IN_MEM:
12545   case X86::FP80_TO_INT32_IN_MEM:
12546   case X86::FP80_TO_INT64_IN_MEM: {
12547     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12548     DebugLoc DL = MI->getDebugLoc();
12549
12550     // Change the floating point control register to use "round towards zero"
12551     // mode when truncating to an integer value.
12552     MachineFunction *F = BB->getParent();
12553     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12554     addFrameReference(BuildMI(*BB, MI, DL,
12555                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12556
12557     // Load the old value of the high byte of the control word...
12558     unsigned OldCW =
12559       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12560     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12561                       CWFrameIdx);
12562
12563     // Set the high part to be round to zero...
12564     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12565       .addImm(0xC7F);
12566
12567     // Reload the modified control word now...
12568     addFrameReference(BuildMI(*BB, MI, DL,
12569                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12570
12571     // Restore the memory image of control word to original value
12572     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12573       .addReg(OldCW);
12574
12575     // Get the X86 opcode to use.
12576     unsigned Opc;
12577     switch (MI->getOpcode()) {
12578     default: llvm_unreachable("illegal opcode!");
12579     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12580     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12581     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12582     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12583     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12584     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12585     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12586     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12587     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12588     }
12589
12590     X86AddressMode AM;
12591     MachineOperand &Op = MI->getOperand(0);
12592     if (Op.isReg()) {
12593       AM.BaseType = X86AddressMode::RegBase;
12594       AM.Base.Reg = Op.getReg();
12595     } else {
12596       AM.BaseType = X86AddressMode::FrameIndexBase;
12597       AM.Base.FrameIndex = Op.getIndex();
12598     }
12599     Op = MI->getOperand(1);
12600     if (Op.isImm())
12601       AM.Scale = Op.getImm();
12602     Op = MI->getOperand(2);
12603     if (Op.isImm())
12604       AM.IndexReg = Op.getImm();
12605     Op = MI->getOperand(3);
12606     if (Op.isGlobal()) {
12607       AM.GV = Op.getGlobal();
12608     } else {
12609       AM.Disp = Op.getImm();
12610     }
12611     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12612                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12613
12614     // Reload the original control word now.
12615     addFrameReference(BuildMI(*BB, MI, DL,
12616                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12617
12618     MI->eraseFromParent();   // The pseudo instruction is gone now.
12619     return BB;
12620   }
12621     // String/text processing lowering.
12622   case X86::PCMPISTRM128REG:
12623   case X86::VPCMPISTRM128REG:
12624     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12625   case X86::PCMPISTRM128MEM:
12626   case X86::VPCMPISTRM128MEM:
12627     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12628   case X86::PCMPESTRM128REG:
12629   case X86::VPCMPESTRM128REG:
12630     return EmitPCMP(MI, BB, 5, false /* in mem */);
12631   case X86::PCMPESTRM128MEM:
12632   case X86::VPCMPESTRM128MEM:
12633     return EmitPCMP(MI, BB, 5, true /* in mem */);
12634
12635     // Thread synchronization.
12636   case X86::MONITOR:
12637     return EmitMonitor(MI, BB);
12638   case X86::MWAIT:
12639     return EmitMwait(MI, BB);
12640
12641     // Atomic Lowering.
12642   case X86::ATOMAND32:
12643     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12644                                                X86::AND32ri, X86::MOV32rm,
12645                                                X86::LCMPXCHG32,
12646                                                X86::NOT32r, X86::EAX,
12647                                                &X86::GR32RegClass);
12648   case X86::ATOMOR32:
12649     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12650                                                X86::OR32ri, X86::MOV32rm,
12651                                                X86::LCMPXCHG32,
12652                                                X86::NOT32r, X86::EAX,
12653                                                &X86::GR32RegClass);
12654   case X86::ATOMXOR32:
12655     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12656                                                X86::XOR32ri, X86::MOV32rm,
12657                                                X86::LCMPXCHG32,
12658                                                X86::NOT32r, X86::EAX,
12659                                                &X86::GR32RegClass);
12660   case X86::ATOMNAND32:
12661     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12662                                                X86::AND32ri, X86::MOV32rm,
12663                                                X86::LCMPXCHG32,
12664                                                X86::NOT32r, X86::EAX,
12665                                                &X86::GR32RegClass, true);
12666   case X86::ATOMMIN32:
12667     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12668   case X86::ATOMMAX32:
12669     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12670   case X86::ATOMUMIN32:
12671     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12672   case X86::ATOMUMAX32:
12673     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12674
12675   case X86::ATOMAND16:
12676     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12677                                                X86::AND16ri, X86::MOV16rm,
12678                                                X86::LCMPXCHG16,
12679                                                X86::NOT16r, X86::AX,
12680                                                &X86::GR16RegClass);
12681   case X86::ATOMOR16:
12682     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12683                                                X86::OR16ri, X86::MOV16rm,
12684                                                X86::LCMPXCHG16,
12685                                                X86::NOT16r, X86::AX,
12686                                                &X86::GR16RegClass);
12687   case X86::ATOMXOR16:
12688     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12689                                                X86::XOR16ri, X86::MOV16rm,
12690                                                X86::LCMPXCHG16,
12691                                                X86::NOT16r, X86::AX,
12692                                                &X86::GR16RegClass);
12693   case X86::ATOMNAND16:
12694     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12695                                                X86::AND16ri, X86::MOV16rm,
12696                                                X86::LCMPXCHG16,
12697                                                X86::NOT16r, X86::AX,
12698                                                &X86::GR16RegClass, true);
12699   case X86::ATOMMIN16:
12700     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12701   case X86::ATOMMAX16:
12702     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12703   case X86::ATOMUMIN16:
12704     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12705   case X86::ATOMUMAX16:
12706     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12707
12708   case X86::ATOMAND8:
12709     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12710                                                X86::AND8ri, X86::MOV8rm,
12711                                                X86::LCMPXCHG8,
12712                                                X86::NOT8r, X86::AL,
12713                                                &X86::GR8RegClass);
12714   case X86::ATOMOR8:
12715     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12716                                                X86::OR8ri, X86::MOV8rm,
12717                                                X86::LCMPXCHG8,
12718                                                X86::NOT8r, X86::AL,
12719                                                &X86::GR8RegClass);
12720   case X86::ATOMXOR8:
12721     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12722                                                X86::XOR8ri, X86::MOV8rm,
12723                                                X86::LCMPXCHG8,
12724                                                X86::NOT8r, X86::AL,
12725                                                &X86::GR8RegClass);
12726   case X86::ATOMNAND8:
12727     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12728                                                X86::AND8ri, X86::MOV8rm,
12729                                                X86::LCMPXCHG8,
12730                                                X86::NOT8r, X86::AL,
12731                                                &X86::GR8RegClass, true);
12732   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12733   // This group is for 64-bit host.
12734   case X86::ATOMAND64:
12735     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12736                                                X86::AND64ri32, X86::MOV64rm,
12737                                                X86::LCMPXCHG64,
12738                                                X86::NOT64r, X86::RAX,
12739                                                &X86::GR64RegClass);
12740   case X86::ATOMOR64:
12741     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12742                                                X86::OR64ri32, X86::MOV64rm,
12743                                                X86::LCMPXCHG64,
12744                                                X86::NOT64r, X86::RAX,
12745                                                &X86::GR64RegClass);
12746   case X86::ATOMXOR64:
12747     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12748                                                X86::XOR64ri32, X86::MOV64rm,
12749                                                X86::LCMPXCHG64,
12750                                                X86::NOT64r, X86::RAX,
12751                                                &X86::GR64RegClass);
12752   case X86::ATOMNAND64:
12753     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12754                                                X86::AND64ri32, X86::MOV64rm,
12755                                                X86::LCMPXCHG64,
12756                                                X86::NOT64r, X86::RAX,
12757                                                &X86::GR64RegClass, true);
12758   case X86::ATOMMIN64:
12759     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12760   case X86::ATOMMAX64:
12761     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12762   case X86::ATOMUMIN64:
12763     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12764   case X86::ATOMUMAX64:
12765     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12766
12767   // This group does 64-bit operations on a 32-bit host.
12768   case X86::ATOMAND6432:
12769     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12770                                                X86::AND32rr, X86::AND32rr,
12771                                                X86::AND32ri, X86::AND32ri,
12772                                                false);
12773   case X86::ATOMOR6432:
12774     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12775                                                X86::OR32rr, X86::OR32rr,
12776                                                X86::OR32ri, X86::OR32ri,
12777                                                false);
12778   case X86::ATOMXOR6432:
12779     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12780                                                X86::XOR32rr, X86::XOR32rr,
12781                                                X86::XOR32ri, X86::XOR32ri,
12782                                                false);
12783   case X86::ATOMNAND6432:
12784     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12785                                                X86::AND32rr, X86::AND32rr,
12786                                                X86::AND32ri, X86::AND32ri,
12787                                                true);
12788   case X86::ATOMADD6432:
12789     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12790                                                X86::ADD32rr, X86::ADC32rr,
12791                                                X86::ADD32ri, X86::ADC32ri,
12792                                                false);
12793   case X86::ATOMSUB6432:
12794     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12795                                                X86::SUB32rr, X86::SBB32rr,
12796                                                X86::SUB32ri, X86::SBB32ri,
12797                                                false);
12798   case X86::ATOMSWAP6432:
12799     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12800                                                X86::MOV32rr, X86::MOV32rr,
12801                                                X86::MOV32ri, X86::MOV32ri,
12802                                                false);
12803   case X86::VASTART_SAVE_XMM_REGS:
12804     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12805
12806   case X86::VAARG_64:
12807     return EmitVAARG64WithCustomInserter(MI, BB);
12808   }
12809 }
12810
12811 //===----------------------------------------------------------------------===//
12812 //                           X86 Optimization Hooks
12813 //===----------------------------------------------------------------------===//
12814
12815 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12816                                                        APInt &KnownZero,
12817                                                        APInt &KnownOne,
12818                                                        const SelectionDAG &DAG,
12819                                                        unsigned Depth) const {
12820   unsigned BitWidth = KnownZero.getBitWidth();
12821   unsigned Opc = Op.getOpcode();
12822   assert((Opc >= ISD::BUILTIN_OP_END ||
12823           Opc == ISD::INTRINSIC_WO_CHAIN ||
12824           Opc == ISD::INTRINSIC_W_CHAIN ||
12825           Opc == ISD::INTRINSIC_VOID) &&
12826          "Should use MaskedValueIsZero if you don't know whether Op"
12827          " is a target node!");
12828
12829   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
12830   switch (Opc) {
12831   default: break;
12832   case X86ISD::ADD:
12833   case X86ISD::SUB:
12834   case X86ISD::ADC:
12835   case X86ISD::SBB:
12836   case X86ISD::SMUL:
12837   case X86ISD::UMUL:
12838   case X86ISD::INC:
12839   case X86ISD::DEC:
12840   case X86ISD::OR:
12841   case X86ISD::XOR:
12842   case X86ISD::AND:
12843     // These nodes' second result is a boolean.
12844     if (Op.getResNo() == 0)
12845       break;
12846     // Fallthrough
12847   case X86ISD::SETCC:
12848     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12849     break;
12850   case ISD::INTRINSIC_WO_CHAIN: {
12851     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12852     unsigned NumLoBits = 0;
12853     switch (IntId) {
12854     default: break;
12855     case Intrinsic::x86_sse_movmsk_ps:
12856     case Intrinsic::x86_avx_movmsk_ps_256:
12857     case Intrinsic::x86_sse2_movmsk_pd:
12858     case Intrinsic::x86_avx_movmsk_pd_256:
12859     case Intrinsic::x86_mmx_pmovmskb:
12860     case Intrinsic::x86_sse2_pmovmskb_128:
12861     case Intrinsic::x86_avx2_pmovmskb: {
12862       // High bits of movmskp{s|d}, pmovmskb are known zero.
12863       switch (IntId) {
12864         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12865         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12866         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12867         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12868         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12869         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12870         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12871         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
12872       }
12873       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
12874       break;
12875     }
12876     }
12877     break;
12878   }
12879   }
12880 }
12881
12882 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12883                                                          unsigned Depth) const {
12884   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12885   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12886     return Op.getValueType().getScalarType().getSizeInBits();
12887
12888   // Fallback case.
12889   return 1;
12890 }
12891
12892 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12893 /// node is a GlobalAddress + offset.
12894 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12895                                        const GlobalValue* &GA,
12896                                        int64_t &Offset) const {
12897   if (N->getOpcode() == X86ISD::Wrapper) {
12898     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12899       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12900       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12901       return true;
12902     }
12903   }
12904   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12905 }
12906
12907 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12908 /// same as extracting the high 128-bit part of 256-bit vector and then
12909 /// inserting the result into the low part of a new 256-bit vector
12910 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12911   EVT VT = SVOp->getValueType(0);
12912   unsigned NumElems = VT.getVectorNumElements();
12913
12914   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12915   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
12916     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12917         SVOp->getMaskElt(j) >= 0)
12918       return false;
12919
12920   return true;
12921 }
12922
12923 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12924 /// same as extracting the low 128-bit part of 256-bit vector and then
12925 /// inserting the result into the high part of a new 256-bit vector
12926 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12927   EVT VT = SVOp->getValueType(0);
12928   unsigned NumElems = VT.getVectorNumElements();
12929
12930   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12931   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
12932     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12933         SVOp->getMaskElt(j) >= 0)
12934       return false;
12935
12936   return true;
12937 }
12938
12939 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12940 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12941                                         TargetLowering::DAGCombinerInfo &DCI,
12942                                         const X86Subtarget* Subtarget) {
12943   DebugLoc dl = N->getDebugLoc();
12944   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12945   SDValue V1 = SVOp->getOperand(0);
12946   SDValue V2 = SVOp->getOperand(1);
12947   EVT VT = SVOp->getValueType(0);
12948   unsigned NumElems = VT.getVectorNumElements();
12949
12950   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12951       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12952     //
12953     //                   0,0,0,...
12954     //                      |
12955     //    V      UNDEF    BUILD_VECTOR    UNDEF
12956     //     \      /           \           /
12957     //  CONCAT_VECTOR         CONCAT_VECTOR
12958     //         \                  /
12959     //          \                /
12960     //          RESULT: V + zero extended
12961     //
12962     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12963         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12964         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12965       return SDValue();
12966
12967     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12968       return SDValue();
12969
12970     // To match the shuffle mask, the first half of the mask should
12971     // be exactly the first vector, and all the rest a splat with the
12972     // first element of the second one.
12973     for (unsigned i = 0; i != NumElems/2; ++i)
12974       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12975           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12976         return SDValue();
12977
12978     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
12979     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
12980       if (Ld->hasNUsesOfValue(1, 0)) {
12981         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
12982         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
12983         SDValue ResNode =
12984           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
12985                                   Ld->getMemoryVT(),
12986                                   Ld->getPointerInfo(),
12987                                   Ld->getAlignment(),
12988                                   false/*isVolatile*/, true/*ReadMem*/,
12989                                   false/*WriteMem*/);
12990         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
12991       }
12992     } 
12993
12994     // Emit a zeroed vector and insert the desired subvector on its
12995     // first half.
12996     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12997     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
12998     return DCI.CombineTo(N, InsV);
12999   }
13000
13001   //===--------------------------------------------------------------------===//
13002   // Combine some shuffles into subvector extracts and inserts:
13003   //
13004
13005   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13006   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13007     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13008     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13009     return DCI.CombineTo(N, InsV);
13010   }
13011
13012   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13013   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13014     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13015     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13016     return DCI.CombineTo(N, InsV);
13017   }
13018
13019   return SDValue();
13020 }
13021
13022 /// PerformShuffleCombine - Performs several different shuffle combines.
13023 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13024                                      TargetLowering::DAGCombinerInfo &DCI,
13025                                      const X86Subtarget *Subtarget) {
13026   DebugLoc dl = N->getDebugLoc();
13027   EVT VT = N->getValueType(0);
13028
13029   // Don't create instructions with illegal types after legalize types has run.
13030   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13031   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13032     return SDValue();
13033
13034   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13035   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13036       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13037     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13038
13039   // Only handle 128 wide vector from here on.
13040   if (VT.getSizeInBits() != 128)
13041     return SDValue();
13042
13043   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13044   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13045   // consecutive, non-overlapping, and in the right order.
13046   SmallVector<SDValue, 16> Elts;
13047   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13048     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13049
13050   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13051 }
13052
13053
13054 /// DCI, PerformTruncateCombine - Converts truncate operation to
13055 /// a sequence of vector shuffle operations.
13056 /// It is possible when we truncate 256-bit vector to 128-bit vector
13057
13058 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG, 
13059                                                   DAGCombinerInfo &DCI) const {
13060   if (!DCI.isBeforeLegalizeOps())
13061     return SDValue();
13062
13063   if (!Subtarget->hasAVX())
13064     return SDValue();
13065
13066   EVT VT = N->getValueType(0);
13067   SDValue Op = N->getOperand(0);
13068   EVT OpVT = Op.getValueType();
13069   DebugLoc dl = N->getDebugLoc();
13070
13071   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13072
13073     if (Subtarget->hasAVX2()) {
13074       // AVX2: v4i64 -> v4i32
13075
13076       // VPERMD
13077       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13078
13079       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13080       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13081                                 ShufMask);
13082
13083       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13084                          DAG.getIntPtrConstant(0));
13085     }
13086
13087     // AVX: v4i64 -> v4i32
13088     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13089                                DAG.getIntPtrConstant(0));
13090
13091     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13092                                DAG.getIntPtrConstant(2));
13093
13094     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13095     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13096
13097     // PSHUFD
13098     static const int ShufMask1[] = {0, 2, 0, 0};
13099
13100     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1);
13101     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1);
13102
13103     // MOVLHPS
13104     static const int ShufMask2[] = {0, 1, 4, 5};
13105
13106     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13107   }
13108
13109   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13110
13111     if (Subtarget->hasAVX2()) {
13112       // AVX2: v8i32 -> v8i16
13113
13114       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13115
13116       // PSHUFB
13117       SmallVector<SDValue,32> pshufbMask;
13118       for (unsigned i = 0; i < 2; ++i) {
13119         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13120         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13121         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13122         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13123         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13124         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13125         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13126         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13127         for (unsigned j = 0; j < 8; ++j)
13128           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13129       }
13130       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13131                                &pshufbMask[0], 32);
13132       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13133
13134       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13135
13136       static const int ShufMask[] = {0,  2,  -1,  -1};
13137       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13138                                 &ShufMask[0]);
13139
13140       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13141                        DAG.getIntPtrConstant(0));
13142
13143       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13144     }
13145
13146     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13147                                DAG.getIntPtrConstant(0));
13148
13149     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13150                                DAG.getIntPtrConstant(4));
13151
13152     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13153     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13154
13155     // PSHUFB
13156     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13157                                    -1, -1, -1, -1, -1, -1, -1, -1};
13158
13159     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8),
13160                                 ShufMask1);
13161     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8),
13162                                 ShufMask1);
13163
13164     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13165     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13166
13167     // MOVLHPS
13168     static const int ShufMask2[] = {0, 1, 4, 5};
13169
13170     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13171     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13172   }
13173
13174   return SDValue();
13175 }
13176
13177 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13178 /// specific shuffle of a load can be folded into a single element load.
13179 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13180 /// shuffles have been customed lowered so we need to handle those here.
13181 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13182                                          TargetLowering::DAGCombinerInfo &DCI) {
13183   if (DCI.isBeforeLegalizeOps())
13184     return SDValue();
13185
13186   SDValue InVec = N->getOperand(0);
13187   SDValue EltNo = N->getOperand(1);
13188
13189   if (!isa<ConstantSDNode>(EltNo))
13190     return SDValue();
13191
13192   EVT VT = InVec.getValueType();
13193
13194   bool HasShuffleIntoBitcast = false;
13195   if (InVec.getOpcode() == ISD::BITCAST) {
13196     // Don't duplicate a load with other uses.
13197     if (!InVec.hasOneUse())
13198       return SDValue();
13199     EVT BCVT = InVec.getOperand(0).getValueType();
13200     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13201       return SDValue();
13202     InVec = InVec.getOperand(0);
13203     HasShuffleIntoBitcast = true;
13204   }
13205
13206   if (!isTargetShuffle(InVec.getOpcode()))
13207     return SDValue();
13208
13209   // Don't duplicate a load with other uses.
13210   if (!InVec.hasOneUse())
13211     return SDValue();
13212
13213   SmallVector<int, 16> ShuffleMask;
13214   bool UnaryShuffle;
13215   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13216                             UnaryShuffle))
13217     return SDValue();
13218
13219   // Select the input vector, guarding against out of range extract vector.
13220   unsigned NumElems = VT.getVectorNumElements();
13221   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13222   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13223   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13224                                          : InVec.getOperand(1);
13225
13226   // If inputs to shuffle are the same for both ops, then allow 2 uses
13227   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13228
13229   if (LdNode.getOpcode() == ISD::BITCAST) {
13230     // Don't duplicate a load with other uses.
13231     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13232       return SDValue();
13233
13234     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13235     LdNode = LdNode.getOperand(0);
13236   }
13237
13238   if (!ISD::isNormalLoad(LdNode.getNode()))
13239     return SDValue();
13240
13241   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13242
13243   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13244     return SDValue();
13245
13246   if (HasShuffleIntoBitcast) {
13247     // If there's a bitcast before the shuffle, check if the load type and
13248     // alignment is valid.
13249     unsigned Align = LN0->getAlignment();
13250     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13251     unsigned NewAlign = TLI.getTargetData()->
13252       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13253
13254     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13255       return SDValue();
13256   }
13257
13258   // All checks match so transform back to vector_shuffle so that DAG combiner
13259   // can finish the job
13260   DebugLoc dl = N->getDebugLoc();
13261
13262   // Create shuffle node taking into account the case that its a unary shuffle
13263   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13264   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13265                                  InVec.getOperand(0), Shuffle,
13266                                  &ShuffleMask[0]);
13267   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13268   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13269                      EltNo);
13270 }
13271
13272 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13273 /// generation and convert it from being a bunch of shuffles and extracts
13274 /// to a simple store and scalar loads to extract the elements.
13275 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13276                                          TargetLowering::DAGCombinerInfo &DCI) {
13277   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13278   if (NewOp.getNode())
13279     return NewOp;
13280
13281   SDValue InputVector = N->getOperand(0);
13282
13283   // Only operate on vectors of 4 elements, where the alternative shuffling
13284   // gets to be more expensive.
13285   if (InputVector.getValueType() != MVT::v4i32)
13286     return SDValue();
13287
13288   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13289   // single use which is a sign-extend or zero-extend, and all elements are
13290   // used.
13291   SmallVector<SDNode *, 4> Uses;
13292   unsigned ExtractedElements = 0;
13293   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13294        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13295     if (UI.getUse().getResNo() != InputVector.getResNo())
13296       return SDValue();
13297
13298     SDNode *Extract = *UI;
13299     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13300       return SDValue();
13301
13302     if (Extract->getValueType(0) != MVT::i32)
13303       return SDValue();
13304     if (!Extract->hasOneUse())
13305       return SDValue();
13306     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13307         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13308       return SDValue();
13309     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13310       return SDValue();
13311
13312     // Record which element was extracted.
13313     ExtractedElements |=
13314       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13315
13316     Uses.push_back(Extract);
13317   }
13318
13319   // If not all the elements were used, this may not be worthwhile.
13320   if (ExtractedElements != 15)
13321     return SDValue();
13322
13323   // Ok, we've now decided to do the transformation.
13324   DebugLoc dl = InputVector.getDebugLoc();
13325
13326   // Store the value to a temporary stack slot.
13327   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13328   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13329                             MachinePointerInfo(), false, false, 0);
13330
13331   // Replace each use (extract) with a load of the appropriate element.
13332   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13333        UE = Uses.end(); UI != UE; ++UI) {
13334     SDNode *Extract = *UI;
13335
13336     // cOMpute the element's address.
13337     SDValue Idx = Extract->getOperand(1);
13338     unsigned EltSize =
13339         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13340     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13341     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13342     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13343
13344     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13345                                      StackPtr, OffsetVal);
13346
13347     // Load the scalar.
13348     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13349                                      ScalarAddr, MachinePointerInfo(),
13350                                      false, false, false, 0);
13351
13352     // Replace the exact with the load.
13353     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13354   }
13355
13356   // The replacement was made in place; don't return anything.
13357   return SDValue();
13358 }
13359
13360 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13361 /// nodes.
13362 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13363                                     TargetLowering::DAGCombinerInfo &DCI,
13364                                     const X86Subtarget *Subtarget) {
13365   DebugLoc DL = N->getDebugLoc();
13366   SDValue Cond = N->getOperand(0);
13367   // Get the LHS/RHS of the select.
13368   SDValue LHS = N->getOperand(1);
13369   SDValue RHS = N->getOperand(2);
13370   EVT VT = LHS.getValueType();
13371
13372   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13373   // instructions match the semantics of the common C idiom x<y?x:y but not
13374   // x<=y?x:y, because of how they handle negative zero (which can be
13375   // ignored in unsafe-math mode).
13376   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13377       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13378       (Subtarget->hasSSE2() ||
13379        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13380     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13381
13382     unsigned Opcode = 0;
13383     // Check for x CC y ? x : y.
13384     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13385         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13386       switch (CC) {
13387       default: break;
13388       case ISD::SETULT:
13389         // Converting this to a min would handle NaNs incorrectly, and swapping
13390         // the operands would cause it to handle comparisons between positive
13391         // and negative zero incorrectly.
13392         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13393           if (!DAG.getTarget().Options.UnsafeFPMath &&
13394               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13395             break;
13396           std::swap(LHS, RHS);
13397         }
13398         Opcode = X86ISD::FMIN;
13399         break;
13400       case ISD::SETOLE:
13401         // Converting this to a min would handle comparisons between positive
13402         // and negative zero incorrectly.
13403         if (!DAG.getTarget().Options.UnsafeFPMath &&
13404             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13405           break;
13406         Opcode = X86ISD::FMIN;
13407         break;
13408       case ISD::SETULE:
13409         // Converting this to a min would handle both negative zeros and NaNs
13410         // incorrectly, but we can swap the operands to fix both.
13411         std::swap(LHS, RHS);
13412       case ISD::SETOLT:
13413       case ISD::SETLT:
13414       case ISD::SETLE:
13415         Opcode = X86ISD::FMIN;
13416         break;
13417
13418       case ISD::SETOGE:
13419         // Converting this to a max 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::FMAX;
13425         break;
13426       case ISD::SETUGT:
13427         // Converting this to a max would handle NaNs incorrectly, and swapping
13428         // the operands would cause it to handle comparisons between positive
13429         // and negative zero incorrectly.
13430         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13431           if (!DAG.getTarget().Options.UnsafeFPMath &&
13432               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13433             break;
13434           std::swap(LHS, RHS);
13435         }
13436         Opcode = X86ISD::FMAX;
13437         break;
13438       case ISD::SETUGE:
13439         // Converting this to a max would handle both negative zeros and NaNs
13440         // incorrectly, but we can swap the operands to fix both.
13441         std::swap(LHS, RHS);
13442       case ISD::SETOGT:
13443       case ISD::SETGT:
13444       case ISD::SETGE:
13445         Opcode = X86ISD::FMAX;
13446         break;
13447       }
13448     // Check for x CC y ? y : x -- a min/max with reversed arms.
13449     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13450                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13451       switch (CC) {
13452       default: break;
13453       case ISD::SETOGE:
13454         // Converting this to a min would handle comparisons between positive
13455         // and negative zero incorrectly, and swapping the operands would
13456         // cause it to handle NaNs incorrectly.
13457         if (!DAG.getTarget().Options.UnsafeFPMath &&
13458             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13459           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13460             break;
13461           std::swap(LHS, RHS);
13462         }
13463         Opcode = X86ISD::FMIN;
13464         break;
13465       case ISD::SETUGT:
13466         // Converting this to a min would handle NaNs incorrectly.
13467         if (!DAG.getTarget().Options.UnsafeFPMath &&
13468             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13469           break;
13470         Opcode = X86ISD::FMIN;
13471         break;
13472       case ISD::SETUGE:
13473         // Converting this to a min would handle both negative zeros and NaNs
13474         // incorrectly, but we can swap the operands to fix both.
13475         std::swap(LHS, RHS);
13476       case ISD::SETOGT:
13477       case ISD::SETGT:
13478       case ISD::SETGE:
13479         Opcode = X86ISD::FMIN;
13480         break;
13481
13482       case ISD::SETULT:
13483         // Converting this to a max would handle NaNs incorrectly.
13484         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13485           break;
13486         Opcode = X86ISD::FMAX;
13487         break;
13488       case ISD::SETOLE:
13489         // Converting this to a max would handle comparisons between positive
13490         // and negative zero incorrectly, and swapping the operands would
13491         // cause it to handle NaNs incorrectly.
13492         if (!DAG.getTarget().Options.UnsafeFPMath &&
13493             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13494           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13495             break;
13496           std::swap(LHS, RHS);
13497         }
13498         Opcode = X86ISD::FMAX;
13499         break;
13500       case ISD::SETULE:
13501         // Converting this to a max would handle both negative zeros and NaNs
13502         // incorrectly, but we can swap the operands to fix both.
13503         std::swap(LHS, RHS);
13504       case ISD::SETOLT:
13505       case ISD::SETLT:
13506       case ISD::SETLE:
13507         Opcode = X86ISD::FMAX;
13508         break;
13509       }
13510     }
13511
13512     if (Opcode)
13513       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13514   }
13515
13516   // If this is a select between two integer constants, try to do some
13517   // optimizations.
13518   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13519     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13520       // Don't do this for crazy integer types.
13521       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13522         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13523         // so that TrueC (the true value) is larger than FalseC.
13524         bool NeedsCondInvert = false;
13525
13526         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13527             // Efficiently invertible.
13528             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13529              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13530               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13531           NeedsCondInvert = true;
13532           std::swap(TrueC, FalseC);
13533         }
13534
13535         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13536         if (FalseC->getAPIntValue() == 0 &&
13537             TrueC->getAPIntValue().isPowerOf2()) {
13538           if (NeedsCondInvert) // Invert the condition if needed.
13539             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13540                                DAG.getConstant(1, Cond.getValueType()));
13541
13542           // Zero extend the condition if needed.
13543           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13544
13545           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13546           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13547                              DAG.getConstant(ShAmt, MVT::i8));
13548         }
13549
13550         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13551         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13552           if (NeedsCondInvert) // Invert the condition if needed.
13553             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13554                                DAG.getConstant(1, Cond.getValueType()));
13555
13556           // Zero extend the condition if needed.
13557           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13558                              FalseC->getValueType(0), Cond);
13559           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13560                              SDValue(FalseC, 0));
13561         }
13562
13563         // Optimize cases that will turn into an LEA instruction.  This requires
13564         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13565         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13566           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13567           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13568
13569           bool isFastMultiplier = false;
13570           if (Diff < 10) {
13571             switch ((unsigned char)Diff) {
13572               default: break;
13573               case 1:  // result = add base, cond
13574               case 2:  // result = lea base(    , cond*2)
13575               case 3:  // result = lea base(cond, cond*2)
13576               case 4:  // result = lea base(    , cond*4)
13577               case 5:  // result = lea base(cond, cond*4)
13578               case 8:  // result = lea base(    , cond*8)
13579               case 9:  // result = lea base(cond, cond*8)
13580                 isFastMultiplier = true;
13581                 break;
13582             }
13583           }
13584
13585           if (isFastMultiplier) {
13586             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13587             if (NeedsCondInvert) // Invert the condition if needed.
13588               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13589                                  DAG.getConstant(1, Cond.getValueType()));
13590
13591             // Zero extend the condition if needed.
13592             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13593                                Cond);
13594             // Scale the condition by the difference.
13595             if (Diff != 1)
13596               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13597                                  DAG.getConstant(Diff, Cond.getValueType()));
13598
13599             // Add the base if non-zero.
13600             if (FalseC->getAPIntValue() != 0)
13601               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13602                                  SDValue(FalseC, 0));
13603             return Cond;
13604           }
13605         }
13606       }
13607   }
13608
13609   // Canonicalize max and min:
13610   // (x > y) ? x : y -> (x >= y) ? x : y
13611   // (x < y) ? x : y -> (x <= y) ? x : y
13612   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13613   // the need for an extra compare
13614   // against zero. e.g.
13615   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13616   // subl   %esi, %edi
13617   // testl  %edi, %edi
13618   // movl   $0, %eax
13619   // cmovgl %edi, %eax
13620   // =>
13621   // xorl   %eax, %eax
13622   // subl   %esi, $edi
13623   // cmovsl %eax, %edi
13624   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13625       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13626       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13627     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13628     switch (CC) {
13629     default: break;
13630     case ISD::SETLT:
13631     case ISD::SETGT: {
13632       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13633       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13634                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
13635       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13636     }
13637     }
13638   }
13639
13640   // If we know that this node is legal then we know that it is going to be
13641   // matched by one of the SSE/AVX BLEND instructions. These instructions only
13642   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13643   // to simplify previous instructions.
13644   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13645   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13646       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
13647     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13648
13649     // Don't optimize vector selects that map to mask-registers.
13650     if (BitWidth == 1)
13651       return SDValue();
13652
13653     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13654     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13655
13656     APInt KnownZero, KnownOne;
13657     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13658                                           DCI.isBeforeLegalizeOps());
13659     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13660         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13661       DCI.CommitTargetLoweringOpt(TLO);
13662   }
13663
13664   return SDValue();
13665 }
13666
13667 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13668 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13669                                   TargetLowering::DAGCombinerInfo &DCI) {
13670   DebugLoc DL = N->getDebugLoc();
13671
13672   // If the flag operand isn't dead, don't touch this CMOV.
13673   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13674     return SDValue();
13675
13676   SDValue FalseOp = N->getOperand(0);
13677   SDValue TrueOp = N->getOperand(1);
13678   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13679   SDValue Cond = N->getOperand(3);
13680   if (CC == X86::COND_E || CC == X86::COND_NE) {
13681     switch (Cond.getOpcode()) {
13682     default: break;
13683     case X86ISD::BSR:
13684     case X86ISD::BSF:
13685       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13686       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13687         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13688     }
13689   }
13690
13691   // If this is a select between two integer constants, try to do some
13692   // optimizations.  Note that the operands are ordered the opposite of SELECT
13693   // operands.
13694   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13695     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13696       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13697       // larger than FalseC (the false value).
13698       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13699         CC = X86::GetOppositeBranchCondition(CC);
13700         std::swap(TrueC, FalseC);
13701       }
13702
13703       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13704       // This is efficient for any integer data type (including i8/i16) and
13705       // shift amount.
13706       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13707         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13708                            DAG.getConstant(CC, MVT::i8), Cond);
13709
13710         // Zero extend the condition if needed.
13711         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13712
13713         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13714         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13715                            DAG.getConstant(ShAmt, MVT::i8));
13716         if (N->getNumValues() == 2)  // Dead flag value?
13717           return DCI.CombineTo(N, Cond, SDValue());
13718         return Cond;
13719       }
13720
13721       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13722       // for any integer data type, including i8/i16.
13723       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13724         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13725                            DAG.getConstant(CC, MVT::i8), Cond);
13726
13727         // Zero extend the condition if needed.
13728         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13729                            FalseC->getValueType(0), Cond);
13730         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13731                            SDValue(FalseC, 0));
13732
13733         if (N->getNumValues() == 2)  // Dead flag value?
13734           return DCI.CombineTo(N, Cond, SDValue());
13735         return Cond;
13736       }
13737
13738       // Optimize cases that will turn into an LEA instruction.  This requires
13739       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13740       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13741         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13742         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13743
13744         bool isFastMultiplier = false;
13745         if (Diff < 10) {
13746           switch ((unsigned char)Diff) {
13747           default: break;
13748           case 1:  // result = add base, cond
13749           case 2:  // result = lea base(    , cond*2)
13750           case 3:  // result = lea base(cond, cond*2)
13751           case 4:  // result = lea base(    , cond*4)
13752           case 5:  // result = lea base(cond, cond*4)
13753           case 8:  // result = lea base(    , cond*8)
13754           case 9:  // result = lea base(cond, cond*8)
13755             isFastMultiplier = true;
13756             break;
13757           }
13758         }
13759
13760         if (isFastMultiplier) {
13761           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13762           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13763                              DAG.getConstant(CC, MVT::i8), Cond);
13764           // Zero extend the condition if needed.
13765           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13766                              Cond);
13767           // Scale the condition by the difference.
13768           if (Diff != 1)
13769             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13770                                DAG.getConstant(Diff, Cond.getValueType()));
13771
13772           // Add the base if non-zero.
13773           if (FalseC->getAPIntValue() != 0)
13774             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13775                                SDValue(FalseC, 0));
13776           if (N->getNumValues() == 2)  // Dead flag value?
13777             return DCI.CombineTo(N, Cond, SDValue());
13778           return Cond;
13779         }
13780       }
13781     }
13782   }
13783   return SDValue();
13784 }
13785
13786
13787 /// PerformMulCombine - Optimize a single multiply with constant into two
13788 /// in order to implement it with two cheaper instructions, e.g.
13789 /// LEA + SHL, LEA + LEA.
13790 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13791                                  TargetLowering::DAGCombinerInfo &DCI) {
13792   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13793     return SDValue();
13794
13795   EVT VT = N->getValueType(0);
13796   if (VT != MVT::i64)
13797     return SDValue();
13798
13799   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13800   if (!C)
13801     return SDValue();
13802   uint64_t MulAmt = C->getZExtValue();
13803   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13804     return SDValue();
13805
13806   uint64_t MulAmt1 = 0;
13807   uint64_t MulAmt2 = 0;
13808   if ((MulAmt % 9) == 0) {
13809     MulAmt1 = 9;
13810     MulAmt2 = MulAmt / 9;
13811   } else if ((MulAmt % 5) == 0) {
13812     MulAmt1 = 5;
13813     MulAmt2 = MulAmt / 5;
13814   } else if ((MulAmt % 3) == 0) {
13815     MulAmt1 = 3;
13816     MulAmt2 = MulAmt / 3;
13817   }
13818   if (MulAmt2 &&
13819       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13820     DebugLoc DL = N->getDebugLoc();
13821
13822     if (isPowerOf2_64(MulAmt2) &&
13823         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13824       // If second multiplifer is pow2, issue it first. We want the multiply by
13825       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13826       // is an add.
13827       std::swap(MulAmt1, MulAmt2);
13828
13829     SDValue NewMul;
13830     if (isPowerOf2_64(MulAmt1))
13831       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13832                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13833     else
13834       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13835                            DAG.getConstant(MulAmt1, VT));
13836
13837     if (isPowerOf2_64(MulAmt2))
13838       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13839                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13840     else
13841       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13842                            DAG.getConstant(MulAmt2, VT));
13843
13844     // Do not add new nodes to DAG combiner worklist.
13845     DCI.CombineTo(N, NewMul, false);
13846   }
13847   return SDValue();
13848 }
13849
13850 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13851   SDValue N0 = N->getOperand(0);
13852   SDValue N1 = N->getOperand(1);
13853   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13854   EVT VT = N0.getValueType();
13855
13856   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13857   // since the result of setcc_c is all zero's or all ones.
13858   if (VT.isInteger() && !VT.isVector() &&
13859       N1C && N0.getOpcode() == ISD::AND &&
13860       N0.getOperand(1).getOpcode() == ISD::Constant) {
13861     SDValue N00 = N0.getOperand(0);
13862     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13863         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13864           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13865          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13866       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13867       APInt ShAmt = N1C->getAPIntValue();
13868       Mask = Mask.shl(ShAmt);
13869       if (Mask != 0)
13870         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13871                            N00, DAG.getConstant(Mask, VT));
13872     }
13873   }
13874
13875
13876   // Hardware support for vector shifts is sparse which makes us scalarize the
13877   // vector operations in many cases. Also, on sandybridge ADD is faster than
13878   // shl.
13879   // (shl V, 1) -> add V,V
13880   if (isSplatVector(N1.getNode())) {
13881     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13882     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13883     // We shift all of the values by one. In many cases we do not have
13884     // hardware support for this operation. This is better expressed as an ADD
13885     // of two values.
13886     if (N1C && (1 == N1C->getZExtValue())) {
13887       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13888     }
13889   }
13890
13891   return SDValue();
13892 }
13893
13894 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13895 ///                       when possible.
13896 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13897                                    TargetLowering::DAGCombinerInfo &DCI,
13898                                    const X86Subtarget *Subtarget) {
13899   EVT VT = N->getValueType(0);
13900   if (N->getOpcode() == ISD::SHL) {
13901     SDValue V = PerformSHLCombine(N, DAG);
13902     if (V.getNode()) return V;
13903   }
13904
13905   // On X86 with SSE2 support, we can transform this to a vector shift if
13906   // all elements are shifted by the same amount.  We can't do this in legalize
13907   // because the a constant vector is typically transformed to a constant pool
13908   // so we have no knowledge of the shift amount.
13909   if (!Subtarget->hasSSE2())
13910     return SDValue();
13911
13912   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13913       (!Subtarget->hasAVX2() ||
13914        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13915     return SDValue();
13916
13917   SDValue ShAmtOp = N->getOperand(1);
13918   EVT EltVT = VT.getVectorElementType();
13919   DebugLoc DL = N->getDebugLoc();
13920   SDValue BaseShAmt = SDValue();
13921   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13922     unsigned NumElts = VT.getVectorNumElements();
13923     unsigned i = 0;
13924     for (; i != NumElts; ++i) {
13925       SDValue Arg = ShAmtOp.getOperand(i);
13926       if (Arg.getOpcode() == ISD::UNDEF) continue;
13927       BaseShAmt = Arg;
13928       break;
13929     }
13930     // Handle the case where the build_vector is all undef
13931     // FIXME: Should DAG allow this?
13932     if (i == NumElts)
13933       return SDValue();
13934
13935     for (; i != NumElts; ++i) {
13936       SDValue Arg = ShAmtOp.getOperand(i);
13937       if (Arg.getOpcode() == ISD::UNDEF) continue;
13938       if (Arg != BaseShAmt) {
13939         return SDValue();
13940       }
13941     }
13942   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13943              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13944     SDValue InVec = ShAmtOp.getOperand(0);
13945     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13946       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13947       unsigned i = 0;
13948       for (; i != NumElts; ++i) {
13949         SDValue Arg = InVec.getOperand(i);
13950         if (Arg.getOpcode() == ISD::UNDEF) continue;
13951         BaseShAmt = Arg;
13952         break;
13953       }
13954     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13955        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13956          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13957          if (C->getZExtValue() == SplatIdx)
13958            BaseShAmt = InVec.getOperand(1);
13959        }
13960     }
13961     if (BaseShAmt.getNode() == 0) {
13962       // Don't create instructions with illegal types after legalize
13963       // types has run.
13964       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
13965           !DCI.isBeforeLegalize())
13966         return SDValue();
13967
13968       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13969                               DAG.getIntPtrConstant(0));
13970     }
13971   } else
13972     return SDValue();
13973
13974   // The shift amount is an i32.
13975   if (EltVT.bitsGT(MVT::i32))
13976     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13977   else if (EltVT.bitsLT(MVT::i32))
13978     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13979
13980   // The shift amount is identical so we can do a vector shift.
13981   SDValue  ValOp = N->getOperand(0);
13982   switch (N->getOpcode()) {
13983   default:
13984     llvm_unreachable("Unknown shift opcode!");
13985   case ISD::SHL:
13986     switch (VT.getSimpleVT().SimpleTy) {
13987     default: return SDValue();
13988     case MVT::v2i64:
13989     case MVT::v4i32:
13990     case MVT::v8i16:
13991     case MVT::v4i64:
13992     case MVT::v8i32:
13993     case MVT::v16i16:
13994       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
13995     }
13996   case ISD::SRA:
13997     switch (VT.getSimpleVT().SimpleTy) {
13998     default: return SDValue();
13999     case MVT::v4i32:
14000     case MVT::v8i16:
14001     case MVT::v8i32:
14002     case MVT::v16i16:
14003       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14004     }
14005   case ISD::SRL:
14006     switch (VT.getSimpleVT().SimpleTy) {
14007     default: return SDValue();
14008     case MVT::v2i64:
14009     case MVT::v4i32:
14010     case MVT::v8i16:
14011     case MVT::v4i64:
14012     case MVT::v8i32:
14013     case MVT::v16i16:
14014       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14015     }
14016   }
14017 }
14018
14019
14020 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14021 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14022 // and friends.  Likewise for OR -> CMPNEQSS.
14023 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14024                             TargetLowering::DAGCombinerInfo &DCI,
14025                             const X86Subtarget *Subtarget) {
14026   unsigned opcode;
14027
14028   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14029   // we're requiring SSE2 for both.
14030   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14031     SDValue N0 = N->getOperand(0);
14032     SDValue N1 = N->getOperand(1);
14033     SDValue CMP0 = N0->getOperand(1);
14034     SDValue CMP1 = N1->getOperand(1);
14035     DebugLoc DL = N->getDebugLoc();
14036
14037     // The SETCCs should both refer to the same CMP.
14038     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14039       return SDValue();
14040
14041     SDValue CMP00 = CMP0->getOperand(0);
14042     SDValue CMP01 = CMP0->getOperand(1);
14043     EVT     VT    = CMP00.getValueType();
14044
14045     if (VT == MVT::f32 || VT == MVT::f64) {
14046       bool ExpectingFlags = false;
14047       // Check for any users that want flags:
14048       for (SDNode::use_iterator UI = N->use_begin(),
14049              UE = N->use_end();
14050            !ExpectingFlags && UI != UE; ++UI)
14051         switch (UI->getOpcode()) {
14052         default:
14053         case ISD::BR_CC:
14054         case ISD::BRCOND:
14055         case ISD::SELECT:
14056           ExpectingFlags = true;
14057           break;
14058         case ISD::CopyToReg:
14059         case ISD::SIGN_EXTEND:
14060         case ISD::ZERO_EXTEND:
14061         case ISD::ANY_EXTEND:
14062           break;
14063         }
14064
14065       if (!ExpectingFlags) {
14066         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14067         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14068
14069         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14070           X86::CondCode tmp = cc0;
14071           cc0 = cc1;
14072           cc1 = tmp;
14073         }
14074
14075         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14076             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14077           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14078           X86ISD::NodeType NTOperator = is64BitFP ?
14079             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14080           // FIXME: need symbolic constants for these magic numbers.
14081           // See X86ATTInstPrinter.cpp:printSSECC().
14082           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14083           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14084                                               DAG.getConstant(x86cc, MVT::i8));
14085           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14086                                               OnesOrZeroesF);
14087           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14088                                       DAG.getConstant(1, MVT::i32));
14089           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14090           return OneBitOfTruth;
14091         }
14092       }
14093     }
14094   }
14095   return SDValue();
14096 }
14097
14098 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14099 /// so it can be folded inside ANDNP.
14100 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14101   EVT VT = N->getValueType(0);
14102
14103   // Match direct AllOnes for 128 and 256-bit vectors
14104   if (ISD::isBuildVectorAllOnes(N))
14105     return true;
14106
14107   // Look through a bit convert.
14108   if (N->getOpcode() == ISD::BITCAST)
14109     N = N->getOperand(0).getNode();
14110
14111   // Sometimes the operand may come from a insert_subvector building a 256-bit
14112   // allones vector
14113   if (VT.getSizeInBits() == 256 &&
14114       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14115     SDValue V1 = N->getOperand(0);
14116     SDValue V2 = N->getOperand(1);
14117
14118     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14119         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14120         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14121         ISD::isBuildVectorAllOnes(V2.getNode()))
14122       return true;
14123   }
14124
14125   return false;
14126 }
14127
14128 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14129                                  TargetLowering::DAGCombinerInfo &DCI,
14130                                  const X86Subtarget *Subtarget) {
14131   if (DCI.isBeforeLegalizeOps())
14132     return SDValue();
14133
14134   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14135   if (R.getNode())
14136     return R;
14137
14138   EVT VT = N->getValueType(0);
14139
14140   // Create ANDN, BLSI, and BLSR instructions
14141   // BLSI is X & (-X)
14142   // BLSR is X & (X-1)
14143   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14144     SDValue N0 = N->getOperand(0);
14145     SDValue N1 = N->getOperand(1);
14146     DebugLoc DL = N->getDebugLoc();
14147
14148     // Check LHS for not
14149     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14150       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14151     // Check RHS for not
14152     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14153       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14154
14155     // Check LHS for neg
14156     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14157         isZero(N0.getOperand(0)))
14158       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14159
14160     // Check RHS for neg
14161     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14162         isZero(N1.getOperand(0)))
14163       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14164
14165     // Check LHS for X-1
14166     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14167         isAllOnes(N0.getOperand(1)))
14168       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14169
14170     // Check RHS for X-1
14171     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14172         isAllOnes(N1.getOperand(1)))
14173       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14174
14175     return SDValue();
14176   }
14177
14178   // Want to form ANDNP nodes:
14179   // 1) In the hopes of then easily combining them with OR and AND nodes
14180   //    to form PBLEND/PSIGN.
14181   // 2) To match ANDN packed intrinsics
14182   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14183     return SDValue();
14184
14185   SDValue N0 = N->getOperand(0);
14186   SDValue N1 = N->getOperand(1);
14187   DebugLoc DL = N->getDebugLoc();
14188
14189   // Check LHS for vnot
14190   if (N0.getOpcode() == ISD::XOR &&
14191       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14192       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14193     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14194
14195   // Check RHS for vnot
14196   if (N1.getOpcode() == ISD::XOR &&
14197       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14198       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14199     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14200
14201   return SDValue();
14202 }
14203
14204 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14205                                 TargetLowering::DAGCombinerInfo &DCI,
14206                                 const X86Subtarget *Subtarget) {
14207   if (DCI.isBeforeLegalizeOps())
14208     return SDValue();
14209
14210   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14211   if (R.getNode())
14212     return R;
14213
14214   EVT VT = N->getValueType(0);
14215
14216   SDValue N0 = N->getOperand(0);
14217   SDValue N1 = N->getOperand(1);
14218
14219   // look for psign/blend
14220   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14221     if (!Subtarget->hasSSSE3() ||
14222         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14223       return SDValue();
14224
14225     // Canonicalize pandn to RHS
14226     if (N0.getOpcode() == X86ISD::ANDNP)
14227       std::swap(N0, N1);
14228     // or (and (m, y), (pandn m, x))
14229     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14230       SDValue Mask = N1.getOperand(0);
14231       SDValue X    = N1.getOperand(1);
14232       SDValue Y;
14233       if (N0.getOperand(0) == Mask)
14234         Y = N0.getOperand(1);
14235       if (N0.getOperand(1) == Mask)
14236         Y = N0.getOperand(0);
14237
14238       // Check to see if the mask appeared in both the AND and ANDNP and
14239       if (!Y.getNode())
14240         return SDValue();
14241
14242       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14243       // Look through mask bitcast.
14244       if (Mask.getOpcode() == ISD::BITCAST)
14245         Mask = Mask.getOperand(0);
14246       if (X.getOpcode() == ISD::BITCAST)
14247         X = X.getOperand(0);
14248       if (Y.getOpcode() == ISD::BITCAST)
14249         Y = Y.getOperand(0);
14250
14251       EVT MaskVT = Mask.getValueType();
14252
14253       // Validate that the Mask operand is a vector sra node.
14254       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14255       // there is no psrai.b
14256       if (Mask.getOpcode() != X86ISD::VSRAI)
14257         return SDValue();
14258
14259       // Check that the SRA is all signbits.
14260       SDValue SraC = Mask.getOperand(1);
14261       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14262       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14263       if ((SraAmt + 1) != EltBits)
14264         return SDValue();
14265
14266       DebugLoc DL = N->getDebugLoc();
14267
14268       // Now we know we at least have a plendvb with the mask val.  See if
14269       // we can form a psignb/w/d.
14270       // psign = x.type == y.type == mask.type && y = sub(0, x);
14271       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14272           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14273           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14274         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14275                "Unsupported VT for PSIGN");
14276         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14277         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14278       }
14279       // PBLENDVB only available on SSE 4.1
14280       if (!Subtarget->hasSSE41())
14281         return SDValue();
14282
14283       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14284
14285       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14286       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14287       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14288       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14289       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14290     }
14291   }
14292
14293   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14294     return SDValue();
14295
14296   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14297   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14298     std::swap(N0, N1);
14299   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14300     return SDValue();
14301   if (!N0.hasOneUse() || !N1.hasOneUse())
14302     return SDValue();
14303
14304   SDValue ShAmt0 = N0.getOperand(1);
14305   if (ShAmt0.getValueType() != MVT::i8)
14306     return SDValue();
14307   SDValue ShAmt1 = N1.getOperand(1);
14308   if (ShAmt1.getValueType() != MVT::i8)
14309     return SDValue();
14310   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14311     ShAmt0 = ShAmt0.getOperand(0);
14312   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14313     ShAmt1 = ShAmt1.getOperand(0);
14314
14315   DebugLoc DL = N->getDebugLoc();
14316   unsigned Opc = X86ISD::SHLD;
14317   SDValue Op0 = N0.getOperand(0);
14318   SDValue Op1 = N1.getOperand(0);
14319   if (ShAmt0.getOpcode() == ISD::SUB) {
14320     Opc = X86ISD::SHRD;
14321     std::swap(Op0, Op1);
14322     std::swap(ShAmt0, ShAmt1);
14323   }
14324
14325   unsigned Bits = VT.getSizeInBits();
14326   if (ShAmt1.getOpcode() == ISD::SUB) {
14327     SDValue Sum = ShAmt1.getOperand(0);
14328     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14329       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14330       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14331         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14332       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14333         return DAG.getNode(Opc, DL, VT,
14334                            Op0, Op1,
14335                            DAG.getNode(ISD::TRUNCATE, DL,
14336                                        MVT::i8, ShAmt0));
14337     }
14338   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14339     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14340     if (ShAmt0C &&
14341         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14342       return DAG.getNode(Opc, DL, VT,
14343                          N0.getOperand(0), N1.getOperand(0),
14344                          DAG.getNode(ISD::TRUNCATE, DL,
14345                                        MVT::i8, ShAmt0));
14346   }
14347
14348   return SDValue();
14349 }
14350
14351 // Generate NEG and CMOV for integer abs.
14352 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14353   EVT VT = N->getValueType(0);
14354
14355   // Since X86 does not have CMOV for 8-bit integer, we don't convert
14356   // 8-bit integer abs to NEG and CMOV.
14357   if (VT.isInteger() && VT.getSizeInBits() == 8)
14358     return SDValue();
14359
14360   SDValue N0 = N->getOperand(0);
14361   SDValue N1 = N->getOperand(1);
14362   DebugLoc DL = N->getDebugLoc();
14363
14364   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14365   // and change it to SUB and CMOV.
14366   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14367       N0.getOpcode() == ISD::ADD &&
14368       N0.getOperand(1) == N1 &&
14369       N1.getOpcode() == ISD::SRA &&
14370       N1.getOperand(0) == N0.getOperand(0))
14371     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14372       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14373         // Generate SUB & CMOV.
14374         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14375                                   DAG.getConstant(0, VT), N0.getOperand(0));
14376
14377         SDValue Ops[] = { N0.getOperand(0), Neg,
14378                           DAG.getConstant(X86::COND_GE, MVT::i8),
14379                           SDValue(Neg.getNode(), 1) };
14380         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14381                            Ops, array_lengthof(Ops));
14382       }
14383   return SDValue();
14384 }
14385
14386 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14387 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14388                                  TargetLowering::DAGCombinerInfo &DCI,
14389                                  const X86Subtarget *Subtarget) {
14390   if (DCI.isBeforeLegalizeOps())
14391     return SDValue();
14392
14393   if (Subtarget->hasCMov()) {
14394     SDValue RV = performIntegerAbsCombine(N, DAG);
14395     if (RV.getNode())
14396       return RV;
14397   }
14398
14399   // Try forming BMI if it is available.
14400   if (!Subtarget->hasBMI())
14401     return SDValue();
14402
14403   EVT VT = N->getValueType(0);
14404
14405   if (VT != MVT::i32 && VT != MVT::i64)
14406     return SDValue();
14407
14408   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14409
14410   // Create BLSMSK instructions by finding X ^ (X-1)
14411   SDValue N0 = N->getOperand(0);
14412   SDValue N1 = N->getOperand(1);
14413   DebugLoc DL = N->getDebugLoc();
14414
14415   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14416       isAllOnes(N0.getOperand(1)))
14417     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14418
14419   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14420       isAllOnes(N1.getOperand(1)))
14421     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14422
14423   return SDValue();
14424 }
14425
14426 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14427 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14428                                   TargetLowering::DAGCombinerInfo &DCI,
14429                                   const X86Subtarget *Subtarget) {
14430   LoadSDNode *Ld = cast<LoadSDNode>(N);
14431   EVT RegVT = Ld->getValueType(0);
14432   EVT MemVT = Ld->getMemoryVT();
14433   DebugLoc dl = Ld->getDebugLoc();
14434   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14435
14436   ISD::LoadExtType Ext = Ld->getExtensionType();
14437
14438   // If this is a vector EXT Load then attempt to optimize it using a
14439   // shuffle. We need SSE4 for the shuffles.
14440   // TODO: It is possible to support ZExt by zeroing the undef values
14441   // during the shuffle phase or after the shuffle.
14442   if (RegVT.isVector() && RegVT.isInteger() &&
14443       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14444     assert(MemVT != RegVT && "Cannot extend to the same type");
14445     assert(MemVT.isVector() && "Must load a vector from memory");
14446
14447     unsigned NumElems = RegVT.getVectorNumElements();
14448     unsigned RegSz = RegVT.getSizeInBits();
14449     unsigned MemSz = MemVT.getSizeInBits();
14450     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14451
14452     // All sizes must be a power of two.
14453     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
14454       return SDValue();
14455
14456     // Attempt to load the original value using scalar loads.
14457     // Find the largest scalar type that divides the total loaded size.
14458     MVT SclrLoadTy = MVT::i8;
14459     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14460          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14461       MVT Tp = (MVT::SimpleValueType)tp;
14462       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14463         SclrLoadTy = Tp;
14464       }
14465     }
14466
14467     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14468     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14469         (64 <= MemSz))
14470       SclrLoadTy = MVT::f64;
14471
14472     // Calculate the number of scalar loads that we need to perform
14473     // in order to load our vector from memory.
14474     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14475
14476     // Represent our vector as a sequence of elements which are the
14477     // largest scalar that we can load.
14478     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14479       RegSz/SclrLoadTy.getSizeInBits());
14480
14481     // Represent the data using the same element type that is stored in
14482     // memory. In practice, we ''widen'' MemVT.
14483     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14484                                   RegSz/MemVT.getScalarType().getSizeInBits());
14485
14486     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14487       "Invalid vector type");
14488
14489     // We can't shuffle using an illegal type.
14490     if (!TLI.isTypeLegal(WideVecVT))
14491       return SDValue();
14492
14493     SmallVector<SDValue, 8> Chains;
14494     SDValue Ptr = Ld->getBasePtr();
14495     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
14496                                         TLI.getPointerTy());
14497     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14498
14499     for (unsigned i = 0; i < NumLoads; ++i) {
14500       // Perform a single load.
14501       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14502                                        Ptr, Ld->getPointerInfo(),
14503                                        Ld->isVolatile(), Ld->isNonTemporal(),
14504                                        Ld->isInvariant(), Ld->getAlignment());
14505       Chains.push_back(ScalarLoad.getValue(1));
14506       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14507       // another round of DAGCombining.
14508       if (i == 0)
14509         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14510       else
14511         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14512                           ScalarLoad, DAG.getIntPtrConstant(i));
14513
14514       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14515     }
14516
14517     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14518                                Chains.size());
14519
14520     // Bitcast the loaded value to a vector of the original element type, in
14521     // the size of the target vector type.
14522     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14523     unsigned SizeRatio = RegSz/MemSz;
14524
14525     // Redistribute the loaded elements into the different locations.
14526     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14527     for (unsigned i = 0; i != NumElems; ++i)
14528       ShuffleVec[i*SizeRatio] = i;
14529
14530     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14531                                          DAG.getUNDEF(WideVecVT),
14532                                          &ShuffleVec[0]);
14533
14534     // Bitcast to the requested type.
14535     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14536     // Replace the original load with the new sequence
14537     // and return the new chain.
14538     return DCI.CombineTo(N, Shuff, TF, true);
14539   }
14540
14541   return SDValue();
14542 }
14543
14544 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14545 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14546                                    const X86Subtarget *Subtarget) {
14547   StoreSDNode *St = cast<StoreSDNode>(N);
14548   EVT VT = St->getValue().getValueType();
14549   EVT StVT = St->getMemoryVT();
14550   DebugLoc dl = St->getDebugLoc();
14551   SDValue StoredVal = St->getOperand(1);
14552   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14553
14554   // If we are saving a concatenation of two XMM registers, perform two stores.
14555   // On Sandy Bridge, 256-bit memory operations are executed by two
14556   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
14557   // memory  operation.
14558   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2() &&
14559       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14560       StoredVal.getNumOperands() == 2) {
14561     SDValue Value0 = StoredVal.getOperand(0);
14562     SDValue Value1 = StoredVal.getOperand(1);
14563
14564     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14565     SDValue Ptr0 = St->getBasePtr();
14566     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14567
14568     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14569                                 St->getPointerInfo(), St->isVolatile(),
14570                                 St->isNonTemporal(), St->getAlignment());
14571     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14572                                 St->getPointerInfo(), St->isVolatile(),
14573                                 St->isNonTemporal(), St->getAlignment());
14574     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14575   }
14576
14577   // Optimize trunc store (of multiple scalars) to shuffle and store.
14578   // First, pack all of the elements in one place. Next, store to memory
14579   // in fewer chunks.
14580   if (St->isTruncatingStore() && VT.isVector()) {
14581     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14582     unsigned NumElems = VT.getVectorNumElements();
14583     assert(StVT != VT && "Cannot truncate to the same type");
14584     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14585     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14586
14587     // From, To sizes and ElemCount must be pow of two
14588     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14589     // We are going to use the original vector elt for storing.
14590     // Accumulated smaller vector elements must be a multiple of the store size.
14591     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14592
14593     unsigned SizeRatio  = FromSz / ToSz;
14594
14595     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14596
14597     // Create a type on which we perform the shuffle
14598     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14599             StVT.getScalarType(), NumElems*SizeRatio);
14600
14601     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14602
14603     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14604     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14605     for (unsigned i = 0; i != NumElems; ++i)
14606       ShuffleVec[i] = i * SizeRatio;
14607
14608     // Can't shuffle using an illegal type.
14609     if (!TLI.isTypeLegal(WideVecVT))
14610       return SDValue();
14611
14612     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14613                                          DAG.getUNDEF(WideVecVT),
14614                                          &ShuffleVec[0]);
14615     // At this point all of the data is stored at the bottom of the
14616     // register. We now need to save it to mem.
14617
14618     // Find the largest store unit
14619     MVT StoreType = MVT::i8;
14620     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14621          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14622       MVT Tp = (MVT::SimpleValueType)tp;
14623       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
14624         StoreType = Tp;
14625     }
14626
14627     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14628     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
14629         (64 <= NumElems * ToSz))
14630       StoreType = MVT::f64;
14631
14632     // Bitcast the original vector into a vector of store-size units
14633     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14634             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
14635     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14636     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14637     SmallVector<SDValue, 8> Chains;
14638     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14639                                         TLI.getPointerTy());
14640     SDValue Ptr = St->getBasePtr();
14641
14642     // Perform one or more big stores into memory.
14643     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
14644       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14645                                    StoreType, ShuffWide,
14646                                    DAG.getIntPtrConstant(i));
14647       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14648                                 St->getPointerInfo(), St->isVolatile(),
14649                                 St->isNonTemporal(), St->getAlignment());
14650       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14651       Chains.push_back(Ch);
14652     }
14653
14654     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14655                                Chains.size());
14656   }
14657
14658
14659   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14660   // the FP state in cases where an emms may be missing.
14661   // A preferable solution to the general problem is to figure out the right
14662   // places to insert EMMS.  This qualifies as a quick hack.
14663
14664   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14665   if (VT.getSizeInBits() != 64)
14666     return SDValue();
14667
14668   const Function *F = DAG.getMachineFunction().getFunction();
14669   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14670   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14671                      && Subtarget->hasSSE2();
14672   if ((VT.isVector() ||
14673        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14674       isa<LoadSDNode>(St->getValue()) &&
14675       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14676       St->getChain().hasOneUse() && !St->isVolatile()) {
14677     SDNode* LdVal = St->getValue().getNode();
14678     LoadSDNode *Ld = 0;
14679     int TokenFactorIndex = -1;
14680     SmallVector<SDValue, 8> Ops;
14681     SDNode* ChainVal = St->getChain().getNode();
14682     // Must be a store of a load.  We currently handle two cases:  the load
14683     // is a direct child, and it's under an intervening TokenFactor.  It is
14684     // possible to dig deeper under nested TokenFactors.
14685     if (ChainVal == LdVal)
14686       Ld = cast<LoadSDNode>(St->getChain());
14687     else if (St->getValue().hasOneUse() &&
14688              ChainVal->getOpcode() == ISD::TokenFactor) {
14689       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14690         if (ChainVal->getOperand(i).getNode() == LdVal) {
14691           TokenFactorIndex = i;
14692           Ld = cast<LoadSDNode>(St->getValue());
14693         } else
14694           Ops.push_back(ChainVal->getOperand(i));
14695       }
14696     }
14697
14698     if (!Ld || !ISD::isNormalLoad(Ld))
14699       return SDValue();
14700
14701     // If this is not the MMX case, i.e. we are just turning i64 load/store
14702     // into f64 load/store, avoid the transformation if there are multiple
14703     // uses of the loaded value.
14704     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14705       return SDValue();
14706
14707     DebugLoc LdDL = Ld->getDebugLoc();
14708     DebugLoc StDL = N->getDebugLoc();
14709     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14710     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14711     // pair instead.
14712     if (Subtarget->is64Bit() || F64IsLegal) {
14713       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14714       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14715                                   Ld->getPointerInfo(), Ld->isVolatile(),
14716                                   Ld->isNonTemporal(), Ld->isInvariant(),
14717                                   Ld->getAlignment());
14718       SDValue NewChain = NewLd.getValue(1);
14719       if (TokenFactorIndex != -1) {
14720         Ops.push_back(NewChain);
14721         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14722                                Ops.size());
14723       }
14724       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14725                           St->getPointerInfo(),
14726                           St->isVolatile(), St->isNonTemporal(),
14727                           St->getAlignment());
14728     }
14729
14730     // Otherwise, lower to two pairs of 32-bit loads / stores.
14731     SDValue LoAddr = Ld->getBasePtr();
14732     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14733                                  DAG.getConstant(4, MVT::i32));
14734
14735     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14736                                Ld->getPointerInfo(),
14737                                Ld->isVolatile(), Ld->isNonTemporal(),
14738                                Ld->isInvariant(), Ld->getAlignment());
14739     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14740                                Ld->getPointerInfo().getWithOffset(4),
14741                                Ld->isVolatile(), Ld->isNonTemporal(),
14742                                Ld->isInvariant(),
14743                                MinAlign(Ld->getAlignment(), 4));
14744
14745     SDValue NewChain = LoLd.getValue(1);
14746     if (TokenFactorIndex != -1) {
14747       Ops.push_back(LoLd);
14748       Ops.push_back(HiLd);
14749       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14750                              Ops.size());
14751     }
14752
14753     LoAddr = St->getBasePtr();
14754     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14755                          DAG.getConstant(4, MVT::i32));
14756
14757     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14758                                 St->getPointerInfo(),
14759                                 St->isVolatile(), St->isNonTemporal(),
14760                                 St->getAlignment());
14761     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14762                                 St->getPointerInfo().getWithOffset(4),
14763                                 St->isVolatile(),
14764                                 St->isNonTemporal(),
14765                                 MinAlign(St->getAlignment(), 4));
14766     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14767   }
14768   return SDValue();
14769 }
14770
14771 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14772 /// and return the operands for the horizontal operation in LHS and RHS.  A
14773 /// horizontal operation performs the binary operation on successive elements
14774 /// of its first operand, then on successive elements of its second operand,
14775 /// returning the resulting values in a vector.  For example, if
14776 ///   A = < float a0, float a1, float a2, float a3 >
14777 /// and
14778 ///   B = < float b0, float b1, float b2, float b3 >
14779 /// then the result of doing a horizontal operation on A and B is
14780 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14781 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14782 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14783 /// set to A, RHS to B, and the routine returns 'true'.
14784 /// Note that the binary operation should have the property that if one of the
14785 /// operands is UNDEF then the result is UNDEF.
14786 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14787   // Look for the following pattern: if
14788   //   A = < float a0, float a1, float a2, float a3 >
14789   //   B = < float b0, float b1, float b2, float b3 >
14790   // and
14791   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14792   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14793   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14794   // which is A horizontal-op B.
14795
14796   // At least one of the operands should be a vector shuffle.
14797   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14798       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14799     return false;
14800
14801   EVT VT = LHS.getValueType();
14802
14803   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14804          "Unsupported vector type for horizontal add/sub");
14805
14806   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14807   // operate independently on 128-bit lanes.
14808   unsigned NumElts = VT.getVectorNumElements();
14809   unsigned NumLanes = VT.getSizeInBits()/128;
14810   unsigned NumLaneElts = NumElts / NumLanes;
14811   assert((NumLaneElts % 2 == 0) &&
14812          "Vector type should have an even number of elements in each lane");
14813   unsigned HalfLaneElts = NumLaneElts/2;
14814
14815   // View LHS in the form
14816   //   LHS = VECTOR_SHUFFLE A, B, LMask
14817   // If LHS is not a shuffle then pretend it is the shuffle
14818   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14819   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14820   // type VT.
14821   SDValue A, B;
14822   SmallVector<int, 16> LMask(NumElts);
14823   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14824     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14825       A = LHS.getOperand(0);
14826     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14827       B = LHS.getOperand(1);
14828     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
14829     std::copy(Mask.begin(), Mask.end(), LMask.begin());
14830   } else {
14831     if (LHS.getOpcode() != ISD::UNDEF)
14832       A = LHS;
14833     for (unsigned i = 0; i != NumElts; ++i)
14834       LMask[i] = i;
14835   }
14836
14837   // Likewise, view RHS in the form
14838   //   RHS = VECTOR_SHUFFLE C, D, RMask
14839   SDValue C, D;
14840   SmallVector<int, 16> RMask(NumElts);
14841   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14842     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14843       C = RHS.getOperand(0);
14844     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14845       D = RHS.getOperand(1);
14846     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
14847     std::copy(Mask.begin(), Mask.end(), RMask.begin());
14848   } else {
14849     if (RHS.getOpcode() != ISD::UNDEF)
14850       C = RHS;
14851     for (unsigned i = 0; i != NumElts; ++i)
14852       RMask[i] = i;
14853   }
14854
14855   // Check that the shuffles are both shuffling the same vectors.
14856   if (!(A == C && B == D) && !(A == D && B == C))
14857     return false;
14858
14859   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14860   if (!A.getNode() && !B.getNode())
14861     return false;
14862
14863   // If A and B occur in reverse order in RHS, then "swap" them (which means
14864   // rewriting the mask).
14865   if (A != C)
14866     CommuteVectorShuffleMask(RMask, NumElts);
14867
14868   // At this point LHS and RHS are equivalent to
14869   //   LHS = VECTOR_SHUFFLE A, B, LMask
14870   //   RHS = VECTOR_SHUFFLE A, B, RMask
14871   // Check that the masks correspond to performing a horizontal operation.
14872   for (unsigned i = 0; i != NumElts; ++i) {
14873     int LIdx = LMask[i], RIdx = RMask[i];
14874
14875     // Ignore any UNDEF components.
14876     if (LIdx < 0 || RIdx < 0 ||
14877         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14878         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14879       continue;
14880
14881     // Check that successive elements are being operated on.  If not, this is
14882     // not a horizontal operation.
14883     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14884     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14885     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14886     if (!(LIdx == Index && RIdx == Index + 1) &&
14887         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14888       return false;
14889   }
14890
14891   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14892   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14893   return true;
14894 }
14895
14896 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14897 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14898                                   const X86Subtarget *Subtarget) {
14899   EVT VT = N->getValueType(0);
14900   SDValue LHS = N->getOperand(0);
14901   SDValue RHS = N->getOperand(1);
14902
14903   // Try to synthesize horizontal adds from adds of shuffles.
14904   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14905        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14906       isHorizontalBinOp(LHS, RHS, true))
14907     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14908   return SDValue();
14909 }
14910
14911 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14912 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14913                                   const X86Subtarget *Subtarget) {
14914   EVT VT = N->getValueType(0);
14915   SDValue LHS = N->getOperand(0);
14916   SDValue RHS = N->getOperand(1);
14917
14918   // Try to synthesize horizontal subs from subs of shuffles.
14919   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14920        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14921       isHorizontalBinOp(LHS, RHS, false))
14922     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14923   return SDValue();
14924 }
14925
14926 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14927 /// X86ISD::FXOR nodes.
14928 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14929   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14930   // F[X]OR(0.0, x) -> x
14931   // F[X]OR(x, 0.0) -> x
14932   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14933     if (C->getValueAPF().isPosZero())
14934       return N->getOperand(1);
14935   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14936     if (C->getValueAPF().isPosZero())
14937       return N->getOperand(0);
14938   return SDValue();
14939 }
14940
14941 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14942 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14943   // FAND(0.0, x) -> 0.0
14944   // FAND(x, 0.0) -> 0.0
14945   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14946     if (C->getValueAPF().isPosZero())
14947       return N->getOperand(0);
14948   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14949     if (C->getValueAPF().isPosZero())
14950       return N->getOperand(1);
14951   return SDValue();
14952 }
14953
14954 static SDValue PerformBTCombine(SDNode *N,
14955                                 SelectionDAG &DAG,
14956                                 TargetLowering::DAGCombinerInfo &DCI) {
14957   // BT ignores high bits in the bit index operand.
14958   SDValue Op1 = N->getOperand(1);
14959   if (Op1.hasOneUse()) {
14960     unsigned BitWidth = Op1.getValueSizeInBits();
14961     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14962     APInt KnownZero, KnownOne;
14963     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14964                                           !DCI.isBeforeLegalizeOps());
14965     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14966     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14967         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14968       DCI.CommitTargetLoweringOpt(TLO);
14969   }
14970   return SDValue();
14971 }
14972
14973 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14974   SDValue Op = N->getOperand(0);
14975   if (Op.getOpcode() == ISD::BITCAST)
14976     Op = Op.getOperand(0);
14977   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14978   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14979       VT.getVectorElementType().getSizeInBits() ==
14980       OpVT.getVectorElementType().getSizeInBits()) {
14981     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14982   }
14983   return SDValue();
14984 }
14985
14986 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
14987                                   TargetLowering::DAGCombinerInfo &DCI,
14988                                   const X86Subtarget *Subtarget) {
14989   if (!DCI.isBeforeLegalizeOps())
14990     return SDValue();
14991
14992   if (!Subtarget->hasAVX())
14993     return SDValue();
14994
14995   EVT VT = N->getValueType(0);
14996   SDValue Op = N->getOperand(0);
14997   EVT OpVT = Op.getValueType();
14998   DebugLoc dl = N->getDebugLoc();
14999
15000   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15001       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15002
15003     if (Subtarget->hasAVX2())
15004       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15005
15006     // Optimize vectors in AVX mode
15007     // Sign extend  v8i16 to v8i32 and
15008     //              v4i32 to v4i64
15009     //
15010     // Divide input vector into two parts
15011     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15012     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15013     // concat the vectors to original VT
15014
15015     unsigned NumElems = OpVT.getVectorNumElements();
15016     SmallVector<int,8> ShufMask1(NumElems, -1);
15017     for (unsigned i = 0; i != NumElems/2; ++i)
15018       ShufMask1[i] = i;
15019
15020     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15021                                         &ShufMask1[0]);
15022
15023     SmallVector<int,8> ShufMask2(NumElems, -1);
15024     for (unsigned i = 0; i != NumElems/2; ++i)
15025       ShufMask2[i] = i + NumElems/2;
15026
15027     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15028                                         &ShufMask2[0]);
15029
15030     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15031                                   VT.getVectorNumElements()/2);
15032
15033     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15034     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15035
15036     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15037   }
15038   return SDValue();
15039 }
15040
15041 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15042                                   TargetLowering::DAGCombinerInfo &DCI,
15043                                   const X86Subtarget *Subtarget) {
15044   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15045   //           (and (i32 x86isd::setcc_carry), 1)
15046   // This eliminates the zext. This transformation is necessary because
15047   // ISD::SETCC is always legalized to i8.
15048   DebugLoc dl = N->getDebugLoc();
15049   SDValue N0 = N->getOperand(0);
15050   EVT VT = N->getValueType(0);
15051   EVT OpVT = N0.getValueType();
15052
15053   if (N0.getOpcode() == ISD::AND &&
15054       N0.hasOneUse() &&
15055       N0.getOperand(0).hasOneUse()) {
15056     SDValue N00 = N0.getOperand(0);
15057     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15058       return SDValue();
15059     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15060     if (!C || C->getZExtValue() != 1)
15061       return SDValue();
15062     return DAG.getNode(ISD::AND, dl, VT,
15063                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15064                                    N00.getOperand(0), N00.getOperand(1)),
15065                        DAG.getConstant(1, VT));
15066   }
15067
15068   // Optimize vectors in AVX mode:
15069   //
15070   //   v8i16 -> v8i32
15071   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15072   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15073   //   Concat upper and lower parts.
15074   //
15075   //   v4i32 -> v4i64
15076   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15077   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15078   //   Concat upper and lower parts.
15079   //
15080   if (!DCI.isBeforeLegalizeOps())
15081     return SDValue();
15082
15083   if (!Subtarget->hasAVX())
15084     return SDValue();
15085
15086   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15087       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15088
15089     if (Subtarget->hasAVX2())
15090       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15091
15092     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15093     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15094     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15095
15096     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15097                                VT.getVectorNumElements()/2);
15098
15099     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15100     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15101
15102     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15103   }
15104
15105   return SDValue();
15106 }
15107
15108 // Optimize x == -y --> x+y == 0
15109 //          x != -y --> x+y != 0
15110 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15111   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15112   SDValue LHS = N->getOperand(0);
15113   SDValue RHS = N->getOperand(1); 
15114
15115   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15116     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15117       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15118         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15119                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15120         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15121                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15122       }
15123   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15124     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15125       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15126         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15127                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15128         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15129                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15130       }
15131   return SDValue();
15132 }
15133
15134 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15135 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15136   unsigned X86CC = N->getConstantOperandVal(0);
15137   SDValue EFLAG = N->getOperand(1);
15138   DebugLoc DL = N->getDebugLoc();
15139
15140   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15141   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15142   // cases.
15143   if (X86CC == X86::COND_B)
15144     return DAG.getNode(ISD::AND, DL, MVT::i8,
15145                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15146                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
15147                        DAG.getConstant(1, MVT::i8));
15148
15149   return SDValue();
15150 }
15151
15152 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15153   SDValue Op0 = N->getOperand(0);
15154   EVT InVT = Op0->getValueType(0);
15155
15156   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15157   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15158     DebugLoc dl = N->getDebugLoc();
15159     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15160     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15161     // Notice that we use SINT_TO_FP because we know that the high bits
15162     // are zero and SINT_TO_FP is better supported by the hardware.
15163     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15164   }
15165
15166   return SDValue();
15167 }
15168
15169 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15170                                         const X86TargetLowering *XTLI) {
15171   SDValue Op0 = N->getOperand(0);
15172   EVT InVT = Op0->getValueType(0);
15173
15174   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15175   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15176     DebugLoc dl = N->getDebugLoc();
15177     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15178     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15179     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15180   }
15181
15182   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15183   // a 32-bit target where SSE doesn't support i64->FP operations.
15184   if (Op0.getOpcode() == ISD::LOAD) {
15185     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15186     EVT VT = Ld->getValueType(0);
15187     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15188         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15189         !XTLI->getSubtarget()->is64Bit() &&
15190         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15191       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15192                                           Ld->getChain(), Op0, DAG);
15193       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15194       return FILDChain;
15195     }
15196   }
15197   return SDValue();
15198 }
15199
15200 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15201   EVT VT = N->getValueType(0);
15202
15203   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15204   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15205     DebugLoc dl = N->getDebugLoc();
15206     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15207     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15208     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15209   }
15210
15211   return SDValue();
15212 }
15213
15214 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15215 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15216                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15217   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15218   // the result is either zero or one (depending on the input carry bit).
15219   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15220   if (X86::isZeroNode(N->getOperand(0)) &&
15221       X86::isZeroNode(N->getOperand(1)) &&
15222       // We don't have a good way to replace an EFLAGS use, so only do this when
15223       // dead right now.
15224       SDValue(N, 1).use_empty()) {
15225     DebugLoc DL = N->getDebugLoc();
15226     EVT VT = N->getValueType(0);
15227     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15228     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15229                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15230                                            DAG.getConstant(X86::COND_B,MVT::i8),
15231                                            N->getOperand(2)),
15232                                DAG.getConstant(1, VT));
15233     return DCI.CombineTo(N, Res1, CarryOut);
15234   }
15235
15236   return SDValue();
15237 }
15238
15239 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15240 //      (add Y, (setne X, 0)) -> sbb -1, Y
15241 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15242 //      (sub (setne X, 0), Y) -> adc -1, Y
15243 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15244   DebugLoc DL = N->getDebugLoc();
15245
15246   // Look through ZExts.
15247   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15248   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15249     return SDValue();
15250
15251   SDValue SetCC = Ext.getOperand(0);
15252   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15253     return SDValue();
15254
15255   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15256   if (CC != X86::COND_E && CC != X86::COND_NE)
15257     return SDValue();
15258
15259   SDValue Cmp = SetCC.getOperand(1);
15260   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15261       !X86::isZeroNode(Cmp.getOperand(1)) ||
15262       !Cmp.getOperand(0).getValueType().isInteger())
15263     return SDValue();
15264
15265   SDValue CmpOp0 = Cmp.getOperand(0);
15266   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15267                                DAG.getConstant(1, CmpOp0.getValueType()));
15268
15269   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15270   if (CC == X86::COND_NE)
15271     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15272                        DL, OtherVal.getValueType(), OtherVal,
15273                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15274   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15275                      DL, OtherVal.getValueType(), OtherVal,
15276                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15277 }
15278
15279 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15280 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15281                                  const X86Subtarget *Subtarget) {
15282   EVT VT = N->getValueType(0);
15283   SDValue Op0 = N->getOperand(0);
15284   SDValue Op1 = N->getOperand(1);
15285
15286   // Try to synthesize horizontal adds from adds of shuffles.
15287   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15288        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15289       isHorizontalBinOp(Op0, Op1, true))
15290     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15291
15292   return OptimizeConditionalInDecrement(N, DAG);
15293 }
15294
15295 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15296                                  const X86Subtarget *Subtarget) {
15297   SDValue Op0 = N->getOperand(0);
15298   SDValue Op1 = N->getOperand(1);
15299
15300   // X86 can't encode an immediate LHS of a sub. See if we can push the
15301   // negation into a preceding instruction.
15302   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15303     // If the RHS of the sub is a XOR with one use and a constant, invert the
15304     // immediate. Then add one to the LHS of the sub so we can turn
15305     // X-Y -> X+~Y+1, saving one register.
15306     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15307         isa<ConstantSDNode>(Op1.getOperand(1))) {
15308       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15309       EVT VT = Op0.getValueType();
15310       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15311                                    Op1.getOperand(0),
15312                                    DAG.getConstant(~XorC, VT));
15313       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15314                          DAG.getConstant(C->getAPIntValue()+1, VT));
15315     }
15316   }
15317
15318   // Try to synthesize horizontal adds from adds of shuffles.
15319   EVT VT = N->getValueType(0);
15320   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15321        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15322       isHorizontalBinOp(Op0, Op1, true))
15323     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15324
15325   return OptimizeConditionalInDecrement(N, DAG);
15326 }
15327
15328 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15329                                              DAGCombinerInfo &DCI) const {
15330   SelectionDAG &DAG = DCI.DAG;
15331   switch (N->getOpcode()) {
15332   default: break;
15333   case ISD::EXTRACT_VECTOR_ELT:
15334     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15335   case ISD::VSELECT:
15336   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15337   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
15338   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
15339   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
15340   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
15341   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
15342   case ISD::SHL:
15343   case ISD::SRA:
15344   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
15345   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
15346   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
15347   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
15348   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
15349   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
15350   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
15351   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
15352   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
15353   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
15354   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
15355   case X86ISD::FXOR:
15356   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
15357   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
15358   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
15359   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
15360   case ISD::ANY_EXTEND:
15361   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
15362   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
15363   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
15364   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
15365   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
15366   case X86ISD::SHUFP:       // Handle all target specific shuffles
15367   case X86ISD::PALIGN:
15368   case X86ISD::UNPCKH:
15369   case X86ISD::UNPCKL:
15370   case X86ISD::MOVHLPS:
15371   case X86ISD::MOVLHPS:
15372   case X86ISD::PSHUFD:
15373   case X86ISD::PSHUFHW:
15374   case X86ISD::PSHUFLW:
15375   case X86ISD::MOVSS:
15376   case X86ISD::MOVSD:
15377   case X86ISD::VPERMILP:
15378   case X86ISD::VPERM2X128:
15379   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
15380   }
15381
15382   return SDValue();
15383 }
15384
15385 /// isTypeDesirableForOp - Return true if the target has native support for
15386 /// the specified value type and it is 'desirable' to use the type for the
15387 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
15388 /// instruction encodings are longer and some i16 instructions are slow.
15389 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
15390   if (!isTypeLegal(VT))
15391     return false;
15392   if (VT != MVT::i16)
15393     return true;
15394
15395   switch (Opc) {
15396   default:
15397     return true;
15398   case ISD::LOAD:
15399   case ISD::SIGN_EXTEND:
15400   case ISD::ZERO_EXTEND:
15401   case ISD::ANY_EXTEND:
15402   case ISD::SHL:
15403   case ISD::SRL:
15404   case ISD::SUB:
15405   case ISD::ADD:
15406   case ISD::MUL:
15407   case ISD::AND:
15408   case ISD::OR:
15409   case ISD::XOR:
15410     return false;
15411   }
15412 }
15413
15414 /// IsDesirableToPromoteOp - This method query the target whether it is
15415 /// beneficial for dag combiner to promote the specified node. If true, it
15416 /// should return the desired promotion type by reference.
15417 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
15418   EVT VT = Op.getValueType();
15419   if (VT != MVT::i16)
15420     return false;
15421
15422   bool Promote = false;
15423   bool Commute = false;
15424   switch (Op.getOpcode()) {
15425   default: break;
15426   case ISD::LOAD: {
15427     LoadSDNode *LD = cast<LoadSDNode>(Op);
15428     // If the non-extending load has a single use and it's not live out, then it
15429     // might be folded.
15430     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
15431                                                      Op.hasOneUse()*/) {
15432       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15433              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
15434         // The only case where we'd want to promote LOAD (rather then it being
15435         // promoted as an operand is when it's only use is liveout.
15436         if (UI->getOpcode() != ISD::CopyToReg)
15437           return false;
15438       }
15439     }
15440     Promote = true;
15441     break;
15442   }
15443   case ISD::SIGN_EXTEND:
15444   case ISD::ZERO_EXTEND:
15445   case ISD::ANY_EXTEND:
15446     Promote = true;
15447     break;
15448   case ISD::SHL:
15449   case ISD::SRL: {
15450     SDValue N0 = Op.getOperand(0);
15451     // Look out for (store (shl (load), x)).
15452     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15453       return false;
15454     Promote = true;
15455     break;
15456   }
15457   case ISD::ADD:
15458   case ISD::MUL:
15459   case ISD::AND:
15460   case ISD::OR:
15461   case ISD::XOR:
15462     Commute = true;
15463     // fallthrough
15464   case ISD::SUB: {
15465     SDValue N0 = Op.getOperand(0);
15466     SDValue N1 = Op.getOperand(1);
15467     if (!Commute && MayFoldLoad(N1))
15468       return false;
15469     // Avoid disabling potential load folding opportunities.
15470     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15471       return false;
15472     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15473       return false;
15474     Promote = true;
15475   }
15476   }
15477
15478   PVT = MVT::i32;
15479   return Promote;
15480 }
15481
15482 //===----------------------------------------------------------------------===//
15483 //                           X86 Inline Assembly Support
15484 //===----------------------------------------------------------------------===//
15485
15486 namespace {
15487   // Helper to match a string separated by whitespace.
15488   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15489     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15490
15491     for (unsigned i = 0, e = args.size(); i != e; ++i) {
15492       StringRef piece(*args[i]);
15493       if (!s.startswith(piece)) // Check if the piece matches.
15494         return false;
15495
15496       s = s.substr(piece.size());
15497       StringRef::size_type pos = s.find_first_not_of(" \t");
15498       if (pos == 0) // We matched a prefix.
15499         return false;
15500
15501       s = s.substr(pos);
15502     }
15503
15504     return s.empty();
15505   }
15506   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15507 }
15508
15509 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15510   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15511
15512   std::string AsmStr = IA->getAsmString();
15513
15514   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15515   if (!Ty || Ty->getBitWidth() % 16 != 0)
15516     return false;
15517
15518   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15519   SmallVector<StringRef, 4> AsmPieces;
15520   SplitString(AsmStr, AsmPieces, ";\n");
15521
15522   switch (AsmPieces.size()) {
15523   default: return false;
15524   case 1:
15525     // FIXME: this should verify that we are targeting a 486 or better.  If not,
15526     // we will turn this bswap into something that will be lowered to logical
15527     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
15528     // lower so don't worry about this.
15529     // bswap $0
15530     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15531         matchAsm(AsmPieces[0], "bswapl", "$0") ||
15532         matchAsm(AsmPieces[0], "bswapq", "$0") ||
15533         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15534         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15535         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15536       // No need to check constraints, nothing other than the equivalent of
15537       // "=r,0" would be valid here.
15538       return IntrinsicLowering::LowerToByteSwap(CI);
15539     }
15540
15541     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15542     if (CI->getType()->isIntegerTy(16) &&
15543         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15544         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15545          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15546       AsmPieces.clear();
15547       const std::string &ConstraintsStr = IA->getConstraintString();
15548       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15549       std::sort(AsmPieces.begin(), AsmPieces.end());
15550       if (AsmPieces.size() == 4 &&
15551           AsmPieces[0] == "~{cc}" &&
15552           AsmPieces[1] == "~{dirflag}" &&
15553           AsmPieces[2] == "~{flags}" &&
15554           AsmPieces[3] == "~{fpsr}")
15555       return IntrinsicLowering::LowerToByteSwap(CI);
15556     }
15557     break;
15558   case 3:
15559     if (CI->getType()->isIntegerTy(32) &&
15560         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15561         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15562         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15563         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15564       AsmPieces.clear();
15565       const std::string &ConstraintsStr = IA->getConstraintString();
15566       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15567       std::sort(AsmPieces.begin(), AsmPieces.end());
15568       if (AsmPieces.size() == 4 &&
15569           AsmPieces[0] == "~{cc}" &&
15570           AsmPieces[1] == "~{dirflag}" &&
15571           AsmPieces[2] == "~{flags}" &&
15572           AsmPieces[3] == "~{fpsr}")
15573         return IntrinsicLowering::LowerToByteSwap(CI);
15574     }
15575
15576     if (CI->getType()->isIntegerTy(64)) {
15577       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15578       if (Constraints.size() >= 2 &&
15579           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15580           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15581         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15582         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15583             matchAsm(AsmPieces[1], "bswap", "%edx") &&
15584             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15585           return IntrinsicLowering::LowerToByteSwap(CI);
15586       }
15587     }
15588     break;
15589   }
15590   return false;
15591 }
15592
15593
15594
15595 /// getConstraintType - Given a constraint letter, return the type of
15596 /// constraint it is for this target.
15597 X86TargetLowering::ConstraintType
15598 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15599   if (Constraint.size() == 1) {
15600     switch (Constraint[0]) {
15601     case 'R':
15602     case 'q':
15603     case 'Q':
15604     case 'f':
15605     case 't':
15606     case 'u':
15607     case 'y':
15608     case 'x':
15609     case 'Y':
15610     case 'l':
15611       return C_RegisterClass;
15612     case 'a':
15613     case 'b':
15614     case 'c':
15615     case 'd':
15616     case 'S':
15617     case 'D':
15618     case 'A':
15619       return C_Register;
15620     case 'I':
15621     case 'J':
15622     case 'K':
15623     case 'L':
15624     case 'M':
15625     case 'N':
15626     case 'G':
15627     case 'C':
15628     case 'e':
15629     case 'Z':
15630       return C_Other;
15631     default:
15632       break;
15633     }
15634   }
15635   return TargetLowering::getConstraintType(Constraint);
15636 }
15637
15638 /// Examine constraint type and operand type and determine a weight value.
15639 /// This object must already have been set up with the operand type
15640 /// and the current alternative constraint selected.
15641 TargetLowering::ConstraintWeight
15642   X86TargetLowering::getSingleConstraintMatchWeight(
15643     AsmOperandInfo &info, const char *constraint) const {
15644   ConstraintWeight weight = CW_Invalid;
15645   Value *CallOperandVal = info.CallOperandVal;
15646     // If we don't have a value, we can't do a match,
15647     // but allow it at the lowest weight.
15648   if (CallOperandVal == NULL)
15649     return CW_Default;
15650   Type *type = CallOperandVal->getType();
15651   // Look at the constraint type.
15652   switch (*constraint) {
15653   default:
15654     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15655   case 'R':
15656   case 'q':
15657   case 'Q':
15658   case 'a':
15659   case 'b':
15660   case 'c':
15661   case 'd':
15662   case 'S':
15663   case 'D':
15664   case 'A':
15665     if (CallOperandVal->getType()->isIntegerTy())
15666       weight = CW_SpecificReg;
15667     break;
15668   case 'f':
15669   case 't':
15670   case 'u':
15671       if (type->isFloatingPointTy())
15672         weight = CW_SpecificReg;
15673       break;
15674   case 'y':
15675       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15676         weight = CW_SpecificReg;
15677       break;
15678   case 'x':
15679   case 'Y':
15680     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15681         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15682       weight = CW_Register;
15683     break;
15684   case 'I':
15685     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15686       if (C->getZExtValue() <= 31)
15687         weight = CW_Constant;
15688     }
15689     break;
15690   case 'J':
15691     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15692       if (C->getZExtValue() <= 63)
15693         weight = CW_Constant;
15694     }
15695     break;
15696   case 'K':
15697     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15698       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15699         weight = CW_Constant;
15700     }
15701     break;
15702   case 'L':
15703     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15704       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15705         weight = CW_Constant;
15706     }
15707     break;
15708   case 'M':
15709     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15710       if (C->getZExtValue() <= 3)
15711         weight = CW_Constant;
15712     }
15713     break;
15714   case 'N':
15715     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15716       if (C->getZExtValue() <= 0xff)
15717         weight = CW_Constant;
15718     }
15719     break;
15720   case 'G':
15721   case 'C':
15722     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15723       weight = CW_Constant;
15724     }
15725     break;
15726   case 'e':
15727     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15728       if ((C->getSExtValue() >= -0x80000000LL) &&
15729           (C->getSExtValue() <= 0x7fffffffLL))
15730         weight = CW_Constant;
15731     }
15732     break;
15733   case 'Z':
15734     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15735       if (C->getZExtValue() <= 0xffffffff)
15736         weight = CW_Constant;
15737     }
15738     break;
15739   }
15740   return weight;
15741 }
15742
15743 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15744 /// with another that has more specific requirements based on the type of the
15745 /// corresponding operand.
15746 const char *X86TargetLowering::
15747 LowerXConstraint(EVT ConstraintVT) const {
15748   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15749   // 'f' like normal targets.
15750   if (ConstraintVT.isFloatingPoint()) {
15751     if (Subtarget->hasSSE2())
15752       return "Y";
15753     if (Subtarget->hasSSE1())
15754       return "x";
15755   }
15756
15757   return TargetLowering::LowerXConstraint(ConstraintVT);
15758 }
15759
15760 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15761 /// vector.  If it is invalid, don't add anything to Ops.
15762 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15763                                                      std::string &Constraint,
15764                                                      std::vector<SDValue>&Ops,
15765                                                      SelectionDAG &DAG) const {
15766   SDValue Result(0, 0);
15767
15768   // Only support length 1 constraints for now.
15769   if (Constraint.length() > 1) return;
15770
15771   char ConstraintLetter = Constraint[0];
15772   switch (ConstraintLetter) {
15773   default: break;
15774   case 'I':
15775     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15776       if (C->getZExtValue() <= 31) {
15777         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15778         break;
15779       }
15780     }
15781     return;
15782   case 'J':
15783     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15784       if (C->getZExtValue() <= 63) {
15785         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15786         break;
15787       }
15788     }
15789     return;
15790   case 'K':
15791     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15792       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15793         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15794         break;
15795       }
15796     }
15797     return;
15798   case 'N':
15799     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15800       if (C->getZExtValue() <= 255) {
15801         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15802         break;
15803       }
15804     }
15805     return;
15806   case 'e': {
15807     // 32-bit signed value
15808     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15809       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15810                                            C->getSExtValue())) {
15811         // Widen to 64 bits here to get it sign extended.
15812         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15813         break;
15814       }
15815     // FIXME gcc accepts some relocatable values here too, but only in certain
15816     // memory models; it's complicated.
15817     }
15818     return;
15819   }
15820   case 'Z': {
15821     // 32-bit unsigned value
15822     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15823       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15824                                            C->getZExtValue())) {
15825         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15826         break;
15827       }
15828     }
15829     // FIXME gcc accepts some relocatable values here too, but only in certain
15830     // memory models; it's complicated.
15831     return;
15832   }
15833   case 'i': {
15834     // Literal immediates are always ok.
15835     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15836       // Widen to 64 bits here to get it sign extended.
15837       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15838       break;
15839     }
15840
15841     // In any sort of PIC mode addresses need to be computed at runtime by
15842     // adding in a register or some sort of table lookup.  These can't
15843     // be used as immediates.
15844     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15845       return;
15846
15847     // If we are in non-pic codegen mode, we allow the address of a global (with
15848     // an optional displacement) to be used with 'i'.
15849     GlobalAddressSDNode *GA = 0;
15850     int64_t Offset = 0;
15851
15852     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15853     while (1) {
15854       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15855         Offset += GA->getOffset();
15856         break;
15857       } else if (Op.getOpcode() == ISD::ADD) {
15858         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15859           Offset += C->getZExtValue();
15860           Op = Op.getOperand(0);
15861           continue;
15862         }
15863       } else if (Op.getOpcode() == ISD::SUB) {
15864         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15865           Offset += -C->getZExtValue();
15866           Op = Op.getOperand(0);
15867           continue;
15868         }
15869       }
15870
15871       // Otherwise, this isn't something we can handle, reject it.
15872       return;
15873     }
15874
15875     const GlobalValue *GV = GA->getGlobal();
15876     // If we require an extra load to get this address, as in PIC mode, we
15877     // can't accept it.
15878     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15879                                                         getTargetMachine())))
15880       return;
15881
15882     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15883                                         GA->getValueType(0), Offset);
15884     break;
15885   }
15886   }
15887
15888   if (Result.getNode()) {
15889     Ops.push_back(Result);
15890     return;
15891   }
15892   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15893 }
15894
15895 std::pair<unsigned, const TargetRegisterClass*>
15896 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15897                                                 EVT VT) const {
15898   // First, see if this is a constraint that directly corresponds to an LLVM
15899   // register class.
15900   if (Constraint.size() == 1) {
15901     // GCC Constraint Letters
15902     switch (Constraint[0]) {
15903     default: break;
15904       // TODO: Slight differences here in allocation order and leaving
15905       // RIP in the class. Do they matter any more here than they do
15906       // in the normal allocation?
15907     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15908       if (Subtarget->is64Bit()) {
15909         if (VT == MVT::i32 || VT == MVT::f32)
15910           return std::make_pair(0U, &X86::GR32RegClass);
15911         if (VT == MVT::i16)
15912           return std::make_pair(0U, &X86::GR16RegClass);
15913         if (VT == MVT::i8 || VT == MVT::i1)
15914           return std::make_pair(0U, &X86::GR8RegClass);
15915         if (VT == MVT::i64 || VT == MVT::f64)
15916           return std::make_pair(0U, &X86::GR64RegClass);
15917         break;
15918       }
15919       // 32-bit fallthrough
15920     case 'Q':   // Q_REGS
15921       if (VT == MVT::i32 || VT == MVT::f32)
15922         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
15923       if (VT == MVT::i16)
15924         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
15925       if (VT == MVT::i8 || VT == MVT::i1)
15926         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
15927       if (VT == MVT::i64)
15928         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
15929       break;
15930     case 'r':   // GENERAL_REGS
15931     case 'l':   // INDEX_REGS
15932       if (VT == MVT::i8 || VT == MVT::i1)
15933         return std::make_pair(0U, &X86::GR8RegClass);
15934       if (VT == MVT::i16)
15935         return std::make_pair(0U, &X86::GR16RegClass);
15936       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15937         return std::make_pair(0U, &X86::GR32RegClass);
15938       return std::make_pair(0U, &X86::GR64RegClass);
15939     case 'R':   // LEGACY_REGS
15940       if (VT == MVT::i8 || VT == MVT::i1)
15941         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
15942       if (VT == MVT::i16)
15943         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
15944       if (VT == MVT::i32 || !Subtarget->is64Bit())
15945         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
15946       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
15947     case 'f':  // FP Stack registers.
15948       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15949       // value to the correct fpstack register class.
15950       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15951         return std::make_pair(0U, &X86::RFP32RegClass);
15952       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15953         return std::make_pair(0U, &X86::RFP64RegClass);
15954       return std::make_pair(0U, &X86::RFP80RegClass);
15955     case 'y':   // MMX_REGS if MMX allowed.
15956       if (!Subtarget->hasMMX()) break;
15957       return std::make_pair(0U, &X86::VR64RegClass);
15958     case 'Y':   // SSE_REGS if SSE2 allowed
15959       if (!Subtarget->hasSSE2()) break;
15960       // FALL THROUGH.
15961     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
15962       if (!Subtarget->hasSSE1()) break;
15963
15964       switch (VT.getSimpleVT().SimpleTy) {
15965       default: break;
15966       // Scalar SSE types.
15967       case MVT::f32:
15968       case MVT::i32:
15969         return std::make_pair(0U, &X86::FR32RegClass);
15970       case MVT::f64:
15971       case MVT::i64:
15972         return std::make_pair(0U, &X86::FR64RegClass);
15973       // Vector types.
15974       case MVT::v16i8:
15975       case MVT::v8i16:
15976       case MVT::v4i32:
15977       case MVT::v2i64:
15978       case MVT::v4f32:
15979       case MVT::v2f64:
15980         return std::make_pair(0U, &X86::VR128RegClass);
15981       // AVX types.
15982       case MVT::v32i8:
15983       case MVT::v16i16:
15984       case MVT::v8i32:
15985       case MVT::v4i64:
15986       case MVT::v8f32:
15987       case MVT::v4f64:
15988         return std::make_pair(0U, &X86::VR256RegClass);
15989       }
15990       break;
15991     }
15992   }
15993
15994   // Use the default implementation in TargetLowering to convert the register
15995   // constraint into a member of a register class.
15996   std::pair<unsigned, const TargetRegisterClass*> Res;
15997   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15998
15999   // Not found as a standard register?
16000   if (Res.second == 0) {
16001     // Map st(0) -> st(7) -> ST0
16002     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16003         tolower(Constraint[1]) == 's' &&
16004         tolower(Constraint[2]) == 't' &&
16005         Constraint[3] == '(' &&
16006         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16007         Constraint[5] == ')' &&
16008         Constraint[6] == '}') {
16009
16010       Res.first = X86::ST0+Constraint[4]-'0';
16011       Res.second = &X86::RFP80RegClass;
16012       return Res;
16013     }
16014
16015     // GCC allows "st(0)" to be called just plain "st".
16016     if (StringRef("{st}").equals_lower(Constraint)) {
16017       Res.first = X86::ST0;
16018       Res.second = &X86::RFP80RegClass;
16019       return Res;
16020     }
16021
16022     // flags -> EFLAGS
16023     if (StringRef("{flags}").equals_lower(Constraint)) {
16024       Res.first = X86::EFLAGS;
16025       Res.second = &X86::CCRRegClass;
16026       return Res;
16027     }
16028
16029     // 'A' means EAX + EDX.
16030     if (Constraint == "A") {
16031       Res.first = X86::EAX;
16032       Res.second = &X86::GR32_ADRegClass;
16033       return Res;
16034     }
16035     return Res;
16036   }
16037
16038   // Otherwise, check to see if this is a register class of the wrong value
16039   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16040   // turn into {ax},{dx}.
16041   if (Res.second->hasType(VT))
16042     return Res;   // Correct type already, nothing to do.
16043
16044   // All of the single-register GCC register classes map their values onto
16045   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16046   // really want an 8-bit or 32-bit register, map to the appropriate register
16047   // class and return the appropriate register.
16048   if (Res.second == &X86::GR16RegClass) {
16049     if (VT == MVT::i8) {
16050       unsigned DestReg = 0;
16051       switch (Res.first) {
16052       default: break;
16053       case X86::AX: DestReg = X86::AL; break;
16054       case X86::DX: DestReg = X86::DL; break;
16055       case X86::CX: DestReg = X86::CL; break;
16056       case X86::BX: DestReg = X86::BL; break;
16057       }
16058       if (DestReg) {
16059         Res.first = DestReg;
16060         Res.second = &X86::GR8RegClass;
16061       }
16062     } else if (VT == MVT::i32) {
16063       unsigned DestReg = 0;
16064       switch (Res.first) {
16065       default: break;
16066       case X86::AX: DestReg = X86::EAX; break;
16067       case X86::DX: DestReg = X86::EDX; break;
16068       case X86::CX: DestReg = X86::ECX; break;
16069       case X86::BX: DestReg = X86::EBX; break;
16070       case X86::SI: DestReg = X86::ESI; break;
16071       case X86::DI: DestReg = X86::EDI; break;
16072       case X86::BP: DestReg = X86::EBP; break;
16073       case X86::SP: DestReg = X86::ESP; break;
16074       }
16075       if (DestReg) {
16076         Res.first = DestReg;
16077         Res.second = &X86::GR32RegClass;
16078       }
16079     } else if (VT == MVT::i64) {
16080       unsigned DestReg = 0;
16081       switch (Res.first) {
16082       default: break;
16083       case X86::AX: DestReg = X86::RAX; break;
16084       case X86::DX: DestReg = X86::RDX; break;
16085       case X86::CX: DestReg = X86::RCX; break;
16086       case X86::BX: DestReg = X86::RBX; break;
16087       case X86::SI: DestReg = X86::RSI; break;
16088       case X86::DI: DestReg = X86::RDI; break;
16089       case X86::BP: DestReg = X86::RBP; break;
16090       case X86::SP: DestReg = X86::RSP; break;
16091       }
16092       if (DestReg) {
16093         Res.first = DestReg;
16094         Res.second = &X86::GR64RegClass;
16095       }
16096     }
16097   } else if (Res.second == &X86::FR32RegClass ||
16098              Res.second == &X86::FR64RegClass ||
16099              Res.second == &X86::VR128RegClass) {
16100     // Handle references to XMM physical registers that got mapped into the
16101     // wrong class.  This can happen with constraints like {xmm0} where the
16102     // target independent register mapper will just pick the first match it can
16103     // find, ignoring the required type.
16104
16105     if (VT == MVT::f32 || VT == MVT::i32)
16106       Res.second = &X86::FR32RegClass;
16107     else if (VT == MVT::f64 || VT == MVT::i64)
16108       Res.second = &X86::FR64RegClass;
16109     else if (X86::VR128RegClass.hasType(VT))
16110       Res.second = &X86::VR128RegClass;
16111     else if (X86::VR256RegClass.hasType(VT))
16112       Res.second = &X86::VR256RegClass;
16113   }
16114
16115   return Res;
16116 }