Simplify code. No functionality change.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "X86.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference.  Idx is an index in the 128 bits we
64 /// want.  It need not be aligned to a 128-bit bounday.  That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67                                    SelectionDAG &DAG, DebugLoc dl) {
68   EVT VT = Vec.getValueType();
69   assert(VT.is256BitVector() && "Unexpected vector size!");
70   EVT ElVT = VT.getVectorElementType();
71   unsigned Factor = VT.getSizeInBits()/128;
72   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                   VT.getVectorNumElements()/Factor);
74
75   // Extract from UNDEF is UNDEF.
76   if (Vec.getOpcode() == ISD::UNDEF)
77     return DAG.getUNDEF(ResultVT);
78
79   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80   // we can match to VEXTRACTF128.
81   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83   // This is the index of the first element of the 128-bit chunk
84   // we want.
85   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                                * ElemsPerChunk);
87
88   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
90                                VecIdx);
91
92   return Result;
93 }
94
95 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference.  Idx is an index in the 128 bits
98 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101                                   unsigned IdxVal, SelectionDAG &DAG,
102                                   DebugLoc dl) {
103   // Inserting UNDEF is Result
104   if (Vec.getOpcode() == ISD::UNDEF)
105     return Result;
106
107   EVT VT = Vec.getValueType();
108   assert(VT.is128BitVector() && "Unexpected vector size!");
109
110   EVT ElVT = VT.getVectorElementType();
111   EVT ResultVT = Result.getValueType();
112
113   // Insert the relevant 128 bits.
114   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
115
116   // This is the index of the first element of the 128-bit chunk
117   // we want.
118   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
119                                * ElemsPerChunk);
120
121   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
123                      VecIdx);
124 }
125
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131                                    unsigned NumElems, SelectionDAG &DAG,
132                                    DebugLoc dl) {
133   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
135 }
136
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139   bool is64Bit = Subtarget->is64Bit();
140
141   if (Subtarget->isTargetEnvMacho()) {
142     if (is64Bit)
143       return new X86_64MachoTargetObjectFile();
144     return new TargetLoweringObjectFileMachO();
145   }
146
147   if (Subtarget->isTargetLinux())
148     return new X86LinuxTargetObjectFile();
149   if (Subtarget->isTargetELF())
150     return new TargetLoweringObjectFileELF();
151   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152     return new TargetLoweringObjectFileCOFF();
153   llvm_unreachable("unknown subtarget type");
154 }
155
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157   : TargetLowering(TM, createTLOF(TM)) {
158   Subtarget = &TM.getSubtarget<X86Subtarget>();
159   X86ScalarSSEf64 = Subtarget->hasSSE2();
160   X86ScalarSSEf32 = Subtarget->hasSSE1();
161   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
162
163   RegInfo = TM.getRegisterInfo();
164   TD = getDataLayout();
165
166   // Set up the TargetLowering object.
167   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168
169   // X86 is weird, it always uses i8 for shift amounts and setcc results.
170   setBooleanContents(ZeroOrOneBooleanContent);
171   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174   // For 64-bit since we have so many registers use the ILP scheduler, for
175   // 32-bit code use the register pressure specific scheduling.
176   // For Atom, always use ILP scheduling.
177   if (Subtarget->isAtom())
178     setSchedulingPreference(Sched::ILP);
179   else if (Subtarget->is64Bit())
180     setSchedulingPreference(Sched::ILP);
181   else
182     setSchedulingPreference(Sched::RegPressure);
183   setStackPointerRegisterToSaveRestore(X86StackPtr);
184
185   // Bypass i32 with i8 on Atom when compiling with O2
186   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
187     addBypassSlowDiv(32, 8);
188
189   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
190     // Setup Windows compiler runtime calls.
191     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
192     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
193     setLibcallName(RTLIB::SREM_I64, "_allrem");
194     setLibcallName(RTLIB::UREM_I64, "_aullrem");
195     setLibcallName(RTLIB::MUL_I64, "_allmul");
196     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
197     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
198     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
199     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
200     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
201
202     // The _ftol2 runtime function has an unusual calling conv, which
203     // is modeled by a special pseudo-instruction.
204     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
205     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
206     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
207     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
208   }
209
210   if (Subtarget->isTargetDarwin()) {
211     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
212     setUseUnderscoreSetJmp(false);
213     setUseUnderscoreLongJmp(false);
214   } else if (Subtarget->isTargetMingw()) {
215     // MS runtime is weird: it exports _setjmp, but longjmp!
216     setUseUnderscoreSetJmp(true);
217     setUseUnderscoreLongJmp(false);
218   } else {
219     setUseUnderscoreSetJmp(true);
220     setUseUnderscoreLongJmp(true);
221   }
222
223   // Set up the register classes.
224   addRegisterClass(MVT::i8, &X86::GR8RegClass);
225   addRegisterClass(MVT::i16, &X86::GR16RegClass);
226   addRegisterClass(MVT::i32, &X86::GR32RegClass);
227   if (Subtarget->is64Bit())
228     addRegisterClass(MVT::i64, &X86::GR64RegClass);
229
230   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
231
232   // We don't accept any truncstore of integer registers.
233   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
234   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
235   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
236   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
237   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
238   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
239
240   // SETOEQ and SETUNE require checking two conditions.
241   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
242   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
243   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
244   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
245   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
246   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
247
248   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
249   // operation.
250   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
251   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
252   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
253
254   if (Subtarget->is64Bit()) {
255     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
256     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
257   } else if (!TM.Options.UseSoftFloat) {
258     // We have an algorithm for SSE2->double, and we turn this into a
259     // 64-bit FILD followed by conditional FADD for other targets.
260     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
261     // We have an algorithm for SSE2, and we turn this into a 64-bit
262     // FILD for other targets.
263     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
264   }
265
266   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
267   // this operation.
268   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
269   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
270
271   if (!TM.Options.UseSoftFloat) {
272     // SSE has no i16 to fp conversion, only i32
273     if (X86ScalarSSEf32) {
274       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
275       // f32 and f64 cases are Legal, f80 case is not
276       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
277     } else {
278       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
279       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280     }
281   } else {
282     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
283     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
284   }
285
286   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
287   // are Legal, f80 is custom lowered.
288   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
289   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
290
291   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
292   // this operation.
293   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
294   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
295
296   if (X86ScalarSSEf32) {
297     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
298     // f32 and f64 cases are Legal, f80 case is not
299     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
300   } else {
301     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
302     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303   }
304
305   // Handle FP_TO_UINT by promoting the destination to a larger signed
306   // conversion.
307   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
308   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
309   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
310
311   if (Subtarget->is64Bit()) {
312     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
313     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
314   } else if (!TM.Options.UseSoftFloat) {
315     // Since AVX is a superset of SSE3, only check for SSE here.
316     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
317       // Expand FP_TO_UINT into a select.
318       // FIXME: We would like to use a Custom expander here eventually to do
319       // the optimal thing for SSE vs. the default expansion in the legalizer.
320       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
321     else
322       // With SSE3 we can use fisttpll to convert to a signed i64; without
323       // SSE, we're stuck with a fistpll.
324       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
325   }
326
327   if (isTargetFTOL()) {
328     // Use the _ftol2 runtime function, which has a pseudo-instruction
329     // to handle its weird calling convention.
330     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
331   }
332
333   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
334   if (!X86ScalarSSEf64) {
335     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
336     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
337     if (Subtarget->is64Bit()) {
338       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
339       // Without SSE, i64->f64 goes through memory.
340       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
341     }
342   }
343
344   // Scalar integer divide and remainder are lowered to use operations that
345   // produce two results, to match the available instructions. This exposes
346   // the two-result form to trivial CSE, which is able to combine x/y and x%y
347   // into a single instruction.
348   //
349   // Scalar integer multiply-high is also lowered to use two-result
350   // operations, to match the available instructions. However, plain multiply
351   // (low) operations are left as Legal, as there are single-result
352   // instructions for this in x86. Using the two-result multiply instructions
353   // when both high and low results are needed must be arranged by dagcombine.
354   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
355     MVT VT = IntVTs[i];
356     setOperationAction(ISD::MULHS, VT, Expand);
357     setOperationAction(ISD::MULHU, VT, Expand);
358     setOperationAction(ISD::SDIV, VT, Expand);
359     setOperationAction(ISD::UDIV, VT, Expand);
360     setOperationAction(ISD::SREM, VT, Expand);
361     setOperationAction(ISD::UREM, VT, Expand);
362
363     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
364     setOperationAction(ISD::ADDC, VT, Custom);
365     setOperationAction(ISD::ADDE, VT, Custom);
366     setOperationAction(ISD::SUBC, VT, Custom);
367     setOperationAction(ISD::SUBE, VT, Custom);
368   }
369
370   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
371   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
372   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
373   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
374   if (Subtarget->is64Bit())
375     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
376   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
377   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
378   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
379   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
380   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
381   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
382   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
383   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
384
385   // Promote the i8 variants and force them on up to i32 which has a shorter
386   // encoding.
387   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
388   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
389   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
390   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
391   if (Subtarget->hasBMI()) {
392     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
393     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
394     if (Subtarget->is64Bit())
395       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
396   } else {
397     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
398     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
399     if (Subtarget->is64Bit())
400       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
401   }
402
403   if (Subtarget->hasLZCNT()) {
404     // When promoting the i8 variants, force them to i32 for a shorter
405     // encoding.
406     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
407     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
408     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
409     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
410     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
411     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
412     if (Subtarget->is64Bit())
413       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
414   } else {
415     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
416     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
417     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
418     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
419     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
420     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
421     if (Subtarget->is64Bit()) {
422       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
423       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
424     }
425   }
426
427   if (Subtarget->hasPOPCNT()) {
428     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
429   } else {
430     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
431     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
432     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
433     if (Subtarget->is64Bit())
434       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
435   }
436
437   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
438   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
439
440   // These should be promoted to a larger select which is supported.
441   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
442   // X86 wants to expand cmov itself.
443   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
444   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
446   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
447   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
448   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
450   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
452   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
453   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
454   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
455   if (Subtarget->is64Bit()) {
456     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
457     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
458   }
459   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
460   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
461   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
462   // support continuation, user-level threading, and etc.. As a result, no
463   // other SjLj exception interfaces are implemented and please don't build
464   // your own exception handling based on them.
465   // LLVM/Clang supports zero-cost DWARF exception handling.
466   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
467   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
468
469   // Darwin ABI issue.
470   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
471   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
472   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
473   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
474   if (Subtarget->is64Bit())
475     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
476   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
477   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
478   if (Subtarget->is64Bit()) {
479     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
480     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
481     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
482     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
483     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
484   }
485   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
486   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
487   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
488   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
489   if (Subtarget->is64Bit()) {
490     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
491     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
492     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
493   }
494
495   if (Subtarget->hasSSE1())
496     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
497
498   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
499   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
500
501   // On X86 and X86-64, atomic operations are lowered to locked instructions.
502   // Locked instructions, in turn, have implicit fence semantics (all memory
503   // operations are flushed before issuing the locked instruction, and they
504   // are not buffered), so we can fold away the common pattern of
505   // fence-atomic-fence.
506   setShouldFoldAtomicFences(true);
507
508   // Expand certain atomics
509   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
510     MVT VT = IntVTs[i];
511     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
512     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
513     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
514   }
515
516   if (!Subtarget->is64Bit()) {
517     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
518     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
519     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
520     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
521     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
522     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
523     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
524     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
525     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
526     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
527     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
528     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
529   }
530
531   if (Subtarget->hasCmpxchg16b()) {
532     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
533   }
534
535   // FIXME - use subtarget debug flags
536   if (!Subtarget->isTargetDarwin() &&
537       !Subtarget->isTargetELF() &&
538       !Subtarget->isTargetCygMing()) {
539     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
540   }
541
542   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
543   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
544   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
545   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
546   if (Subtarget->is64Bit()) {
547     setExceptionPointerRegister(X86::RAX);
548     setExceptionSelectorRegister(X86::RDX);
549   } else {
550     setExceptionPointerRegister(X86::EAX);
551     setExceptionSelectorRegister(X86::EDX);
552   }
553   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
554   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
555
556   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
557   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
558
559   setOperationAction(ISD::TRAP, MVT::Other, Legal);
560   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
561
562   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
563   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
564   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
565   if (Subtarget->is64Bit()) {
566     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
567     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
568   } else {
569     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
570     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
571   }
572
573   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
574   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
575
576   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
577     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
578                        MVT::i64 : MVT::i32, Custom);
579   else if (TM.Options.EnableSegmentedStacks)
580     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
581                        MVT::i64 : MVT::i32, Custom);
582   else
583     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
584                        MVT::i64 : MVT::i32, Expand);
585
586   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
587     // f32 and f64 use SSE.
588     // Set up the FP register classes.
589     addRegisterClass(MVT::f32, &X86::FR32RegClass);
590     addRegisterClass(MVT::f64, &X86::FR64RegClass);
591
592     // Use ANDPD to simulate FABS.
593     setOperationAction(ISD::FABS , MVT::f64, Custom);
594     setOperationAction(ISD::FABS , MVT::f32, Custom);
595
596     // Use XORP to simulate FNEG.
597     setOperationAction(ISD::FNEG , MVT::f64, Custom);
598     setOperationAction(ISD::FNEG , MVT::f32, Custom);
599
600     // Use ANDPD and ORPD to simulate FCOPYSIGN.
601     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
602     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
603
604     // Lower this to FGETSIGNx86 plus an AND.
605     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
606     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
607
608     // We don't support sin/cos/fmod
609     setOperationAction(ISD::FSIN , MVT::f64, Expand);
610     setOperationAction(ISD::FCOS , MVT::f64, Expand);
611     setOperationAction(ISD::FSIN , MVT::f32, Expand);
612     setOperationAction(ISD::FCOS , MVT::f32, Expand);
613
614     // Expand FP immediates into loads from the stack, except for the special
615     // cases we handle.
616     addLegalFPImmediate(APFloat(+0.0)); // xorpd
617     addLegalFPImmediate(APFloat(+0.0f)); // xorps
618   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
619     // Use SSE for f32, x87 for f64.
620     // Set up the FP register classes.
621     addRegisterClass(MVT::f32, &X86::FR32RegClass);
622     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
623
624     // Use ANDPS to simulate FABS.
625     setOperationAction(ISD::FABS , MVT::f32, Custom);
626
627     // Use XORP to simulate FNEG.
628     setOperationAction(ISD::FNEG , MVT::f32, Custom);
629
630     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
631
632     // Use ANDPS and ORPS to simulate FCOPYSIGN.
633     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
634     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
635
636     // We don't support sin/cos/fmod
637     setOperationAction(ISD::FSIN , MVT::f32, Expand);
638     setOperationAction(ISD::FCOS , MVT::f32, Expand);
639
640     // Special cases we handle for FP constants.
641     addLegalFPImmediate(APFloat(+0.0f)); // xorps
642     addLegalFPImmediate(APFloat(+0.0)); // FLD0
643     addLegalFPImmediate(APFloat(+1.0)); // FLD1
644     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
645     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
646
647     if (!TM.Options.UnsafeFPMath) {
648       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
649       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
650     }
651   } else if (!TM.Options.UseSoftFloat) {
652     // f32 and f64 in x87.
653     // Set up the FP register classes.
654     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
655     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
656
657     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
658     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
659     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
660     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
661
662     if (!TM.Options.UnsafeFPMath) {
663       setOperationAction(ISD::FSIN           , MVT::f32  , Expand);
664       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
665       setOperationAction(ISD::FCOS           , MVT::f32  , Expand);
666       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
667     }
668     addLegalFPImmediate(APFloat(+0.0)); // FLD0
669     addLegalFPImmediate(APFloat(+1.0)); // FLD1
670     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
671     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
672     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
673     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
674     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
675     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
676   }
677
678   // We don't support FMA.
679   setOperationAction(ISD::FMA, MVT::f64, Expand);
680   setOperationAction(ISD::FMA, MVT::f32, Expand);
681
682   // Long double always uses X87.
683   if (!TM.Options.UseSoftFloat) {
684     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
685     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
686     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
687     {
688       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
689       addLegalFPImmediate(TmpFlt);  // FLD0
690       TmpFlt.changeSign();
691       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
692
693       bool ignored;
694       APFloat TmpFlt2(+1.0);
695       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
696                       &ignored);
697       addLegalFPImmediate(TmpFlt2);  // FLD1
698       TmpFlt2.changeSign();
699       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
700     }
701
702     if (!TM.Options.UnsafeFPMath) {
703       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
704       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
705     }
706
707     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
708     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
709     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
710     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
711     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
712     setOperationAction(ISD::FMA, MVT::f80, Expand);
713   }
714
715   // Always use a library call for pow.
716   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
717   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
718   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
719
720   setOperationAction(ISD::FLOG, MVT::f80, Expand);
721   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
722   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
723   setOperationAction(ISD::FEXP, MVT::f80, Expand);
724   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
725
726   // First set operation action for all vector types to either promote
727   // (for widening) or expand (for scalarization). Then we will selectively
728   // turn on ones that can be effectively codegen'd.
729   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
730            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
731     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
746     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
748     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
749     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
770     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
771     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
772     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
773     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
774     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
775     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
776     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
777     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
778     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
779     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
780     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
781     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
782     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
783     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
784     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
785     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
786     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
787     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
788     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
789     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
790     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
791              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
792       setTruncStoreAction((MVT::SimpleValueType)VT,
793                           (MVT::SimpleValueType)InnerVT, Expand);
794     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
795     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
796     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
797   }
798
799   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
800   // with -msoft-float, disable use of MMX as well.
801   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
802     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
803     // No operations on x86mmx supported, everything uses intrinsics.
804   }
805
806   // MMX-sized vectors (other than x86mmx) are expected to be expanded
807   // into smaller operations.
808   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
809   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
810   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
811   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
812   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
813   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
814   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
815   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
816   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
817   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
818   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
819   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
820   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
821   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
822   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
823   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
824   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
825   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
826   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
827   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
828   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
829   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
830   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
831   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
832   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
833   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
834   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
835   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
836   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
837
838   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
839     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
840
841     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
842     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
843     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
844     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
845     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
846     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
847     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
848     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
849     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
850     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
851     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
852     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
853   }
854
855   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
856     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
857
858     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
859     // registers cannot be used even for integer operations.
860     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
861     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
862     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
863     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
864
865     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
866     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
867     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
868     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
869     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
870     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
871     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
872     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
873     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
874     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
875     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
876     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
877     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
878     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
879     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
880     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
881     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
882
883     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
884     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
885     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
886     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
887
888     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
889     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
891     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
892     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
893
894     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
895     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896       MVT VT = (MVT::SimpleValueType)i;
897       // Do not attempt to custom lower non-power-of-2 vectors
898       if (!isPowerOf2_32(VT.getVectorNumElements()))
899         continue;
900       // Do not attempt to custom lower non-128-bit vectors
901       if (!VT.is128BitVector())
902         continue;
903       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
904       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
905       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
906     }
907
908     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
909     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
910     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
911     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
912     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
913     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
914
915     if (Subtarget->is64Bit()) {
916       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
917       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
918     }
919
920     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
921     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
922       MVT VT = (MVT::SimpleValueType)i;
923
924       // Do not attempt to promote non-128-bit vectors
925       if (!VT.is128BitVector())
926         continue;
927
928       setOperationAction(ISD::AND,    VT, Promote);
929       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
930       setOperationAction(ISD::OR,     VT, Promote);
931       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
932       setOperationAction(ISD::XOR,    VT, Promote);
933       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
934       setOperationAction(ISD::LOAD,   VT, Promote);
935       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
936       setOperationAction(ISD::SELECT, VT, Promote);
937       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
938     }
939
940     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
941
942     // Custom lower v2i64 and v2f64 selects.
943     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
944     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
945     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
946     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
947
948     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
949     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
950
951     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
952     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
953     // As there is no 64-bit GPR available, we need build a special custom
954     // sequence to convert from v2i32 to v2f32.
955     if (!Subtarget->is64Bit())
956       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
957
958     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
959     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
960
961     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
962   }
963
964   if (Subtarget->hasSSE41()) {
965     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
966     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
967     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
968     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
969     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
970     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
971     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
972     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
973     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
974     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
975
976     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
977     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
978
979     // FIXME: Do we need to handle scalar-to-vector here?
980     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
981
982     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
983     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
984     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
985     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
986     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
987
988     // i8 and i16 vectors are custom , because the source register and source
989     // source memory operand types are not the same width.  f32 vectors are
990     // custom since the immediate controlling the insert encodes additional
991     // information.
992     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
993     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
994     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
996
997     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
998     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
999     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1000     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1001
1002     // FIXME: these should be Legal but thats only for the case where
1003     // the index is constant.  For now custom expand to deal with that.
1004     if (Subtarget->is64Bit()) {
1005       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1006       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1007     }
1008   }
1009
1010   if (Subtarget->hasSSE2()) {
1011     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1012     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1013
1014     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1015     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1016
1017     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1018     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1019
1020     if (Subtarget->hasAVX2()) {
1021       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1022       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1023
1024       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1025       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1026
1027       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1028     } else {
1029       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1030       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1031
1032       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1033       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1034
1035       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1036     }
1037   }
1038
1039   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1040     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1041     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1042     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1043     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1044     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1045     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1046
1047     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1049     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1050
1051     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1052     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1053     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1054     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1055     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1056     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1057     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1058     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1059
1060     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1061     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1062     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1063     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1064     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1065     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1066     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1067     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1068
1069     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1070
1071     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1072
1073     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1074     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1075     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1076
1077     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1078     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1079     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1080
1081     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1082
1083     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1084     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1085
1086     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1087     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1088
1089     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1090     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1091
1092     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1093     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1094     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1095     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1096
1097     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1098     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1099     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1100
1101     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1102     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1103     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1104     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1105
1106     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1107       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1108       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1109       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1110       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1111       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1112       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1113     }
1114
1115     if (Subtarget->hasAVX2()) {
1116       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1117       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1118       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1119       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1120
1121       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1122       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1123       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1124       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1125
1126       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1127       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1128       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1129       // Don't lower v32i8 because there is no 128-bit byte mul
1130
1131       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1132
1133       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1134       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1135
1136       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1137       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1138
1139       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1140     } else {
1141       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1142       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1143       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1144       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1145
1146       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1147       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1148       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1149       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1150
1151       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1152       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1153       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1154       // Don't lower v32i8 because there is no 128-bit byte mul
1155
1156       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1157       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1158
1159       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1160       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1161
1162       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1163     }
1164
1165     // Custom lower several nodes for 256-bit types.
1166     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1167              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1168       MVT VT = (MVT::SimpleValueType)i;
1169
1170       // Extract subvector is special because the value type
1171       // (result) is 128-bit but the source is 256-bit wide.
1172       if (VT.is128BitVector())
1173         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1174
1175       // Do not attempt to custom lower other non-256-bit vectors
1176       if (!VT.is256BitVector())
1177         continue;
1178
1179       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1180       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1181       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1182       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1183       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1184       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1185       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1186     }
1187
1188     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1189     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1190       MVT VT = (MVT::SimpleValueType)i;
1191
1192       // Do not attempt to promote non-256-bit vectors
1193       if (!VT.is256BitVector())
1194         continue;
1195
1196       setOperationAction(ISD::AND,    VT, Promote);
1197       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1198       setOperationAction(ISD::OR,     VT, Promote);
1199       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1200       setOperationAction(ISD::XOR,    VT, Promote);
1201       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1202       setOperationAction(ISD::LOAD,   VT, Promote);
1203       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1204       setOperationAction(ISD::SELECT, VT, Promote);
1205       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1206     }
1207   }
1208
1209   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1210   // of this type with custom code.
1211   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1212            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1213     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1214                        Custom);
1215   }
1216
1217   // We want to custom lower some of our intrinsics.
1218   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1219   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1220
1221
1222   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1223   // handle type legalization for these operations here.
1224   //
1225   // FIXME: We really should do custom legalization for addition and
1226   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1227   // than generic legalization for 64-bit multiplication-with-overflow, though.
1228   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1229     // Add/Sub/Mul with overflow operations are custom lowered.
1230     MVT VT = IntVTs[i];
1231     setOperationAction(ISD::SADDO, VT, Custom);
1232     setOperationAction(ISD::UADDO, VT, Custom);
1233     setOperationAction(ISD::SSUBO, VT, Custom);
1234     setOperationAction(ISD::USUBO, VT, Custom);
1235     setOperationAction(ISD::SMULO, VT, Custom);
1236     setOperationAction(ISD::UMULO, VT, Custom);
1237   }
1238
1239   // There are no 8-bit 3-address imul/mul instructions
1240   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1241   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1242
1243   if (!Subtarget->is64Bit()) {
1244     // These libcalls are not available in 32-bit.
1245     setLibcallName(RTLIB::SHL_I128, 0);
1246     setLibcallName(RTLIB::SRL_I128, 0);
1247     setLibcallName(RTLIB::SRA_I128, 0);
1248   }
1249
1250   // We have target-specific dag combine patterns for the following nodes:
1251   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1252   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1253   setTargetDAGCombine(ISD::VSELECT);
1254   setTargetDAGCombine(ISD::SELECT);
1255   setTargetDAGCombine(ISD::SHL);
1256   setTargetDAGCombine(ISD::SRA);
1257   setTargetDAGCombine(ISD::SRL);
1258   setTargetDAGCombine(ISD::OR);
1259   setTargetDAGCombine(ISD::AND);
1260   setTargetDAGCombine(ISD::ADD);
1261   setTargetDAGCombine(ISD::FADD);
1262   setTargetDAGCombine(ISD::FSUB);
1263   setTargetDAGCombine(ISD::FMA);
1264   setTargetDAGCombine(ISD::SUB);
1265   setTargetDAGCombine(ISD::LOAD);
1266   setTargetDAGCombine(ISD::STORE);
1267   setTargetDAGCombine(ISD::ZERO_EXTEND);
1268   setTargetDAGCombine(ISD::ANY_EXTEND);
1269   setTargetDAGCombine(ISD::SIGN_EXTEND);
1270   setTargetDAGCombine(ISD::TRUNCATE);
1271   setTargetDAGCombine(ISD::SINT_TO_FP);
1272   setTargetDAGCombine(ISD::SETCC);
1273   if (Subtarget->is64Bit())
1274     setTargetDAGCombine(ISD::MUL);
1275   setTargetDAGCombine(ISD::XOR);
1276
1277   computeRegisterProperties();
1278
1279   // On Darwin, -Os means optimize for size without hurting performance,
1280   // do not reduce the limit.
1281   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1282   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1283   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1284   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1285   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1286   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1287   setPrefLoopAlignment(4); // 2^4 bytes.
1288   benefitFromCodePlacementOpt = true;
1289
1290   // Predictable cmov don't hurt on atom because it's in-order.
1291   predictableSelectIsExpensive = !Subtarget->isAtom();
1292
1293   setPrefFunctionAlignment(4); // 2^4 bytes.
1294 }
1295
1296
1297 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1298   if (!VT.isVector()) return MVT::i8;
1299   return VT.changeVectorElementTypeToInteger();
1300 }
1301
1302
1303 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1304 /// the desired ByVal argument alignment.
1305 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1306   if (MaxAlign == 16)
1307     return;
1308   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1309     if (VTy->getBitWidth() == 128)
1310       MaxAlign = 16;
1311   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1312     unsigned EltAlign = 0;
1313     getMaxByValAlign(ATy->getElementType(), EltAlign);
1314     if (EltAlign > MaxAlign)
1315       MaxAlign = EltAlign;
1316   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1317     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1318       unsigned EltAlign = 0;
1319       getMaxByValAlign(STy->getElementType(i), EltAlign);
1320       if (EltAlign > MaxAlign)
1321         MaxAlign = EltAlign;
1322       if (MaxAlign == 16)
1323         break;
1324     }
1325   }
1326 }
1327
1328 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1329 /// function arguments in the caller parameter area. For X86, aggregates
1330 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1331 /// are at 4-byte boundaries.
1332 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1333   if (Subtarget->is64Bit()) {
1334     // Max of 8 and alignment of type.
1335     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1336     if (TyAlign > 8)
1337       return TyAlign;
1338     return 8;
1339   }
1340
1341   unsigned Align = 4;
1342   if (Subtarget->hasSSE1())
1343     getMaxByValAlign(Ty, Align);
1344   return Align;
1345 }
1346
1347 /// getOptimalMemOpType - Returns the target specific optimal type for load
1348 /// and store operations as a result of memset, memcpy, and memmove
1349 /// lowering. If DstAlign is zero that means it's safe to destination
1350 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1351 /// means there isn't a need to check it against alignment requirement,
1352 /// probably because the source does not need to be loaded. If
1353 /// 'IsZeroVal' is true, that means it's safe to return a
1354 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1355 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1356 /// constant so it does not need to be loaded.
1357 /// It returns EVT::Other if the type should be determined using generic
1358 /// target-independent logic.
1359 EVT
1360 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1361                                        unsigned DstAlign, unsigned SrcAlign,
1362                                        bool IsZeroVal,
1363                                        bool MemcpyStrSrc,
1364                                        MachineFunction &MF) const {
1365   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1366   // linux.  This is because the stack realignment code can't handle certain
1367   // cases like PR2962.  This should be removed when PR2962 is fixed.
1368   const Function *F = MF.getFunction();
1369   if (IsZeroVal &&
1370       !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1371     if (Size >= 16 &&
1372         (Subtarget->isUnalignedMemAccessFast() ||
1373          ((DstAlign == 0 || DstAlign >= 16) &&
1374           (SrcAlign == 0 || SrcAlign >= 16))) &&
1375         Subtarget->getStackAlignment() >= 16) {
1376       if (Subtarget->getStackAlignment() >= 32) {
1377         if (Subtarget->hasAVX2())
1378           return MVT::v8i32;
1379         if (Subtarget->hasAVX())
1380           return MVT::v8f32;
1381       }
1382       if (Subtarget->hasSSE2())
1383         return MVT::v4i32;
1384       if (Subtarget->hasSSE1())
1385         return MVT::v4f32;
1386     } else if (!MemcpyStrSrc && Size >= 8 &&
1387                !Subtarget->is64Bit() &&
1388                Subtarget->getStackAlignment() >= 8 &&
1389                Subtarget->hasSSE2()) {
1390       // Do not use f64 to lower memcpy if source is string constant. It's
1391       // better to use i32 to avoid the loads.
1392       return MVT::f64;
1393     }
1394   }
1395   if (Subtarget->is64Bit() && Size >= 8)
1396     return MVT::i64;
1397   return MVT::i32;
1398 }
1399
1400 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1401 /// current function.  The returned value is a member of the
1402 /// MachineJumpTableInfo::JTEntryKind enum.
1403 unsigned X86TargetLowering::getJumpTableEncoding() const {
1404   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1405   // symbol.
1406   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1407       Subtarget->isPICStyleGOT())
1408     return MachineJumpTableInfo::EK_Custom32;
1409
1410   // Otherwise, use the normal jump table encoding heuristics.
1411   return TargetLowering::getJumpTableEncoding();
1412 }
1413
1414 const MCExpr *
1415 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1416                                              const MachineBasicBlock *MBB,
1417                                              unsigned uid,MCContext &Ctx) const{
1418   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1419          Subtarget->isPICStyleGOT());
1420   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1421   // entries.
1422   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1423                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1424 }
1425
1426 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1427 /// jumptable.
1428 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1429                                                     SelectionDAG &DAG) const {
1430   if (!Subtarget->is64Bit())
1431     // This doesn't have DebugLoc associated with it, but is not really the
1432     // same as a Register.
1433     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1434   return Table;
1435 }
1436
1437 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1438 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1439 /// MCExpr.
1440 const MCExpr *X86TargetLowering::
1441 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1442                              MCContext &Ctx) const {
1443   // X86-64 uses RIP relative addressing based on the jump table label.
1444   if (Subtarget->isPICStyleRIPRel())
1445     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1446
1447   // Otherwise, the reference is relative to the PIC base.
1448   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1449 }
1450
1451 // FIXME: Why this routine is here? Move to RegInfo!
1452 std::pair<const TargetRegisterClass*, uint8_t>
1453 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1454   const TargetRegisterClass *RRC = 0;
1455   uint8_t Cost = 1;
1456   switch (VT.getSimpleVT().SimpleTy) {
1457   default:
1458     return TargetLowering::findRepresentativeClass(VT);
1459   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1460     RRC = Subtarget->is64Bit() ?
1461       (const TargetRegisterClass*)&X86::GR64RegClass :
1462       (const TargetRegisterClass*)&X86::GR32RegClass;
1463     break;
1464   case MVT::x86mmx:
1465     RRC = &X86::VR64RegClass;
1466     break;
1467   case MVT::f32: case MVT::f64:
1468   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1469   case MVT::v4f32: case MVT::v2f64:
1470   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1471   case MVT::v4f64:
1472     RRC = &X86::VR128RegClass;
1473     break;
1474   }
1475   return std::make_pair(RRC, Cost);
1476 }
1477
1478 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1479                                                unsigned &Offset) const {
1480   if (!Subtarget->isTargetLinux())
1481     return false;
1482
1483   if (Subtarget->is64Bit()) {
1484     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1485     Offset = 0x28;
1486     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1487       AddressSpace = 256;
1488     else
1489       AddressSpace = 257;
1490   } else {
1491     // %gs:0x14 on i386
1492     Offset = 0x14;
1493     AddressSpace = 256;
1494   }
1495   return true;
1496 }
1497
1498
1499 //===----------------------------------------------------------------------===//
1500 //               Return Value Calling Convention Implementation
1501 //===----------------------------------------------------------------------===//
1502
1503 #include "X86GenCallingConv.inc"
1504
1505 bool
1506 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1507                                   MachineFunction &MF, bool isVarArg,
1508                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1509                         LLVMContext &Context) const {
1510   SmallVector<CCValAssign, 16> RVLocs;
1511   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1512                  RVLocs, Context);
1513   return CCInfo.CheckReturn(Outs, RetCC_X86);
1514 }
1515
1516 SDValue
1517 X86TargetLowering::LowerReturn(SDValue Chain,
1518                                CallingConv::ID CallConv, bool isVarArg,
1519                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1520                                const SmallVectorImpl<SDValue> &OutVals,
1521                                DebugLoc dl, SelectionDAG &DAG) const {
1522   MachineFunction &MF = DAG.getMachineFunction();
1523   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1524
1525   SmallVector<CCValAssign, 16> RVLocs;
1526   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1527                  RVLocs, *DAG.getContext());
1528   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1529
1530   // Add the regs to the liveout set for the function.
1531   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1532   for (unsigned i = 0; i != RVLocs.size(); ++i)
1533     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1534       MRI.addLiveOut(RVLocs[i].getLocReg());
1535
1536   SDValue Flag;
1537
1538   SmallVector<SDValue, 6> RetOps;
1539   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1540   // Operand #1 = Bytes To Pop
1541   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1542                    MVT::i16));
1543
1544   // Copy the result values into the output registers.
1545   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1546     CCValAssign &VA = RVLocs[i];
1547     assert(VA.isRegLoc() && "Can only return in registers!");
1548     SDValue ValToCopy = OutVals[i];
1549     EVT ValVT = ValToCopy.getValueType();
1550
1551     // Promote values to the appropriate types
1552     if (VA.getLocInfo() == CCValAssign::SExt)
1553       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1554     else if (VA.getLocInfo() == CCValAssign::ZExt)
1555       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1556     else if (VA.getLocInfo() == CCValAssign::AExt)
1557       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1558     else if (VA.getLocInfo() == CCValAssign::BCvt)
1559       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1560
1561     // If this is x86-64, and we disabled SSE, we can't return FP values,
1562     // or SSE or MMX vectors.
1563     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1564          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1565           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1566       report_fatal_error("SSE register return with SSE disabled");
1567     }
1568     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1569     // llvm-gcc has never done it right and no one has noticed, so this
1570     // should be OK for now.
1571     if (ValVT == MVT::f64 &&
1572         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1573       report_fatal_error("SSE2 register return with SSE2 disabled");
1574
1575     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1576     // the RET instruction and handled by the FP Stackifier.
1577     if (VA.getLocReg() == X86::ST0 ||
1578         VA.getLocReg() == X86::ST1) {
1579       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1580       // change the value to the FP stack register class.
1581       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1582         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1583       RetOps.push_back(ValToCopy);
1584       // Don't emit a copytoreg.
1585       continue;
1586     }
1587
1588     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1589     // which is returned in RAX / RDX.
1590     if (Subtarget->is64Bit()) {
1591       if (ValVT == MVT::x86mmx) {
1592         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1593           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1594           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1595                                   ValToCopy);
1596           // If we don't have SSE2 available, convert to v4f32 so the generated
1597           // register is legal.
1598           if (!Subtarget->hasSSE2())
1599             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1600         }
1601       }
1602     }
1603
1604     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1605     Flag = Chain.getValue(1);
1606   }
1607
1608   // The x86-64 ABI for returning structs by value requires that we copy
1609   // the sret argument into %rax for the return. We saved the argument into
1610   // a virtual register in the entry block, so now we copy the value out
1611   // and into %rax.
1612   if (Subtarget->is64Bit() &&
1613       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1614     MachineFunction &MF = DAG.getMachineFunction();
1615     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1616     unsigned Reg = FuncInfo->getSRetReturnReg();
1617     assert(Reg &&
1618            "SRetReturnReg should have been set in LowerFormalArguments().");
1619     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1620
1621     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1622     Flag = Chain.getValue(1);
1623
1624     // RAX now acts like a return value.
1625     MRI.addLiveOut(X86::RAX);
1626   }
1627
1628   RetOps[0] = Chain;  // Update chain.
1629
1630   // Add the flag if we have it.
1631   if (Flag.getNode())
1632     RetOps.push_back(Flag);
1633
1634   return DAG.getNode(X86ISD::RET_FLAG, dl,
1635                      MVT::Other, &RetOps[0], RetOps.size());
1636 }
1637
1638 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1639   if (N->getNumValues() != 1)
1640     return false;
1641   if (!N->hasNUsesOfValue(1, 0))
1642     return false;
1643
1644   SDValue TCChain = Chain;
1645   SDNode *Copy = *N->use_begin();
1646   if (Copy->getOpcode() == ISD::CopyToReg) {
1647     // If the copy has a glue operand, we conservatively assume it isn't safe to
1648     // perform a tail call.
1649     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1650       return false;
1651     TCChain = Copy->getOperand(0);
1652   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1653     return false;
1654
1655   bool HasRet = false;
1656   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1657        UI != UE; ++UI) {
1658     if (UI->getOpcode() != X86ISD::RET_FLAG)
1659       return false;
1660     HasRet = true;
1661   }
1662
1663   if (!HasRet)
1664     return false;
1665
1666   Chain = TCChain;
1667   return true;
1668 }
1669
1670 EVT
1671 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1672                                             ISD::NodeType ExtendKind) const {
1673   MVT ReturnMVT;
1674   // TODO: Is this also valid on 32-bit?
1675   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1676     ReturnMVT = MVT::i8;
1677   else
1678     ReturnMVT = MVT::i32;
1679
1680   EVT MinVT = getRegisterType(Context, ReturnMVT);
1681   return VT.bitsLT(MinVT) ? MinVT : VT;
1682 }
1683
1684 /// LowerCallResult - Lower the result values of a call into the
1685 /// appropriate copies out of appropriate physical registers.
1686 ///
1687 SDValue
1688 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1689                                    CallingConv::ID CallConv, bool isVarArg,
1690                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1691                                    DebugLoc dl, SelectionDAG &DAG,
1692                                    SmallVectorImpl<SDValue> &InVals) const {
1693
1694   // Assign locations to each value returned by this call.
1695   SmallVector<CCValAssign, 16> RVLocs;
1696   bool Is64Bit = Subtarget->is64Bit();
1697   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1698                  getTargetMachine(), RVLocs, *DAG.getContext());
1699   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1700
1701   // Copy all of the result registers out of their specified physreg.
1702   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1703     CCValAssign &VA = RVLocs[i];
1704     EVT CopyVT = VA.getValVT();
1705
1706     // If this is x86-64, and we disabled SSE, we can't return FP values
1707     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1708         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1709       report_fatal_error("SSE register return with SSE disabled");
1710     }
1711
1712     SDValue Val;
1713
1714     // If this is a call to a function that returns an fp value on the floating
1715     // point stack, we must guarantee the value is popped from the stack, so
1716     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1717     // if the return value is not used. We use the FpPOP_RETVAL instruction
1718     // instead.
1719     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1720       // If we prefer to use the value in xmm registers, copy it out as f80 and
1721       // use a truncate to move it from fp stack reg to xmm reg.
1722       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1723       SDValue Ops[] = { Chain, InFlag };
1724       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1725                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1726       Val = Chain.getValue(0);
1727
1728       // Round the f80 to the right size, which also moves it to the appropriate
1729       // xmm register.
1730       if (CopyVT != VA.getValVT())
1731         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1732                           // This truncation won't change the value.
1733                           DAG.getIntPtrConstant(1));
1734     } else {
1735       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1736                                  CopyVT, InFlag).getValue(1);
1737       Val = Chain.getValue(0);
1738     }
1739     InFlag = Chain.getValue(2);
1740     InVals.push_back(Val);
1741   }
1742
1743   return Chain;
1744 }
1745
1746
1747 //===----------------------------------------------------------------------===//
1748 //                C & StdCall & Fast Calling Convention implementation
1749 //===----------------------------------------------------------------------===//
1750 //  StdCall calling convention seems to be standard for many Windows' API
1751 //  routines and around. It differs from C calling convention just a little:
1752 //  callee should clean up the stack, not caller. Symbols should be also
1753 //  decorated in some fancy way :) It doesn't support any vector arguments.
1754 //  For info on fast calling convention see Fast Calling Convention (tail call)
1755 //  implementation LowerX86_32FastCCCallTo.
1756
1757 /// CallIsStructReturn - Determines whether a call uses struct return
1758 /// semantics.
1759 enum StructReturnType {
1760   NotStructReturn,
1761   RegStructReturn,
1762   StackStructReturn
1763 };
1764 static StructReturnType
1765 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1766   if (Outs.empty())
1767     return NotStructReturn;
1768
1769   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1770   if (!Flags.isSRet())
1771     return NotStructReturn;
1772   if (Flags.isInReg())
1773     return RegStructReturn;
1774   return StackStructReturn;
1775 }
1776
1777 /// ArgsAreStructReturn - Determines whether a function uses struct
1778 /// return semantics.
1779 static StructReturnType
1780 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1781   if (Ins.empty())
1782     return NotStructReturn;
1783
1784   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1785   if (!Flags.isSRet())
1786     return NotStructReturn;
1787   if (Flags.isInReg())
1788     return RegStructReturn;
1789   return StackStructReturn;
1790 }
1791
1792 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1793 /// by "Src" to address "Dst" with size and alignment information specified by
1794 /// the specific parameter attribute. The copy will be passed as a byval
1795 /// function parameter.
1796 static SDValue
1797 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1798                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1799                           DebugLoc dl) {
1800   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1801
1802   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1803                        /*isVolatile*/false, /*AlwaysInline=*/true,
1804                        MachinePointerInfo(), MachinePointerInfo());
1805 }
1806
1807 /// IsTailCallConvention - Return true if the calling convention is one that
1808 /// supports tail call optimization.
1809 static bool IsTailCallConvention(CallingConv::ID CC) {
1810   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1811 }
1812
1813 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1814   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1815     return false;
1816
1817   CallSite CS(CI);
1818   CallingConv::ID CalleeCC = CS.getCallingConv();
1819   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1820     return false;
1821
1822   return true;
1823 }
1824
1825 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1826 /// a tailcall target by changing its ABI.
1827 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1828                                    bool GuaranteedTailCallOpt) {
1829   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1830 }
1831
1832 SDValue
1833 X86TargetLowering::LowerMemArgument(SDValue Chain,
1834                                     CallingConv::ID CallConv,
1835                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1836                                     DebugLoc dl, SelectionDAG &DAG,
1837                                     const CCValAssign &VA,
1838                                     MachineFrameInfo *MFI,
1839                                     unsigned i) const {
1840   // Create the nodes corresponding to a load from this parameter slot.
1841   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1842   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1843                               getTargetMachine().Options.GuaranteedTailCallOpt);
1844   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1845   EVT ValVT;
1846
1847   // If value is passed by pointer we have address passed instead of the value
1848   // itself.
1849   if (VA.getLocInfo() == CCValAssign::Indirect)
1850     ValVT = VA.getLocVT();
1851   else
1852     ValVT = VA.getValVT();
1853
1854   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1855   // changed with more analysis.
1856   // In case of tail call optimization mark all arguments mutable. Since they
1857   // could be overwritten by lowering of arguments in case of a tail call.
1858   if (Flags.isByVal()) {
1859     unsigned Bytes = Flags.getByValSize();
1860     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1861     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1862     return DAG.getFrameIndex(FI, getPointerTy());
1863   } else {
1864     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1865                                     VA.getLocMemOffset(), isImmutable);
1866     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1867     return DAG.getLoad(ValVT, dl, Chain, FIN,
1868                        MachinePointerInfo::getFixedStack(FI),
1869                        false, false, false, 0);
1870   }
1871 }
1872
1873 SDValue
1874 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1875                                         CallingConv::ID CallConv,
1876                                         bool isVarArg,
1877                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1878                                         DebugLoc dl,
1879                                         SelectionDAG &DAG,
1880                                         SmallVectorImpl<SDValue> &InVals)
1881                                           const {
1882   MachineFunction &MF = DAG.getMachineFunction();
1883   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1884
1885   const Function* Fn = MF.getFunction();
1886   if (Fn->hasExternalLinkage() &&
1887       Subtarget->isTargetCygMing() &&
1888       Fn->getName() == "main")
1889     FuncInfo->setForceFramePointer(true);
1890
1891   MachineFrameInfo *MFI = MF.getFrameInfo();
1892   bool Is64Bit = Subtarget->is64Bit();
1893   bool IsWindows = Subtarget->isTargetWindows();
1894   bool IsWin64 = Subtarget->isTargetWin64();
1895
1896   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1897          "Var args not supported with calling convention fastcc or ghc");
1898
1899   // Assign locations to all of the incoming arguments.
1900   SmallVector<CCValAssign, 16> ArgLocs;
1901   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1902                  ArgLocs, *DAG.getContext());
1903
1904   // Allocate shadow area for Win64
1905   if (IsWin64) {
1906     CCInfo.AllocateStack(32, 8);
1907   }
1908
1909   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1910
1911   unsigned LastVal = ~0U;
1912   SDValue ArgValue;
1913   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1914     CCValAssign &VA = ArgLocs[i];
1915     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1916     // places.
1917     assert(VA.getValNo() != LastVal &&
1918            "Don't support value assigned to multiple locs yet");
1919     (void)LastVal;
1920     LastVal = VA.getValNo();
1921
1922     if (VA.isRegLoc()) {
1923       EVT RegVT = VA.getLocVT();
1924       const TargetRegisterClass *RC;
1925       if (RegVT == MVT::i32)
1926         RC = &X86::GR32RegClass;
1927       else if (Is64Bit && RegVT == MVT::i64)
1928         RC = &X86::GR64RegClass;
1929       else if (RegVT == MVT::f32)
1930         RC = &X86::FR32RegClass;
1931       else if (RegVT == MVT::f64)
1932         RC = &X86::FR64RegClass;
1933       else if (RegVT.is256BitVector())
1934         RC = &X86::VR256RegClass;
1935       else if (RegVT.is128BitVector())
1936         RC = &X86::VR128RegClass;
1937       else if (RegVT == MVT::x86mmx)
1938         RC = &X86::VR64RegClass;
1939       else
1940         llvm_unreachable("Unknown argument type!");
1941
1942       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1943       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1944
1945       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1946       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1947       // right size.
1948       if (VA.getLocInfo() == CCValAssign::SExt)
1949         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1950                                DAG.getValueType(VA.getValVT()));
1951       else if (VA.getLocInfo() == CCValAssign::ZExt)
1952         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1953                                DAG.getValueType(VA.getValVT()));
1954       else if (VA.getLocInfo() == CCValAssign::BCvt)
1955         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1956
1957       if (VA.isExtInLoc()) {
1958         // Handle MMX values passed in XMM regs.
1959         if (RegVT.isVector()) {
1960           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1961                                  ArgValue);
1962         } else
1963           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1964       }
1965     } else {
1966       assert(VA.isMemLoc());
1967       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1968     }
1969
1970     // If value is passed via pointer - do a load.
1971     if (VA.getLocInfo() == CCValAssign::Indirect)
1972       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1973                              MachinePointerInfo(), false, false, false, 0);
1974
1975     InVals.push_back(ArgValue);
1976   }
1977
1978   // The x86-64 ABI for returning structs by value requires that we copy
1979   // the sret argument into %rax for the return. Save the argument into
1980   // a virtual register so that we can access it from the return points.
1981   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1982     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1983     unsigned Reg = FuncInfo->getSRetReturnReg();
1984     if (!Reg) {
1985       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1986       FuncInfo->setSRetReturnReg(Reg);
1987     }
1988     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1989     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1990   }
1991
1992   unsigned StackSize = CCInfo.getNextStackOffset();
1993   // Align stack specially for tail calls.
1994   if (FuncIsMadeTailCallSafe(CallConv,
1995                              MF.getTarget().Options.GuaranteedTailCallOpt))
1996     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1997
1998   // If the function takes variable number of arguments, make a frame index for
1999   // the start of the first vararg value... for expansion of llvm.va_start.
2000   if (isVarArg) {
2001     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2002                     CallConv != CallingConv::X86_ThisCall)) {
2003       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2004     }
2005     if (Is64Bit) {
2006       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2007
2008       // FIXME: We should really autogenerate these arrays
2009       static const uint16_t GPR64ArgRegsWin64[] = {
2010         X86::RCX, X86::RDX, X86::R8,  X86::R9
2011       };
2012       static const uint16_t GPR64ArgRegs64Bit[] = {
2013         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2014       };
2015       static const uint16_t XMMArgRegs64Bit[] = {
2016         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2017         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2018       };
2019       const uint16_t *GPR64ArgRegs;
2020       unsigned NumXMMRegs = 0;
2021
2022       if (IsWin64) {
2023         // The XMM registers which might contain var arg parameters are shadowed
2024         // in their paired GPR.  So we only need to save the GPR to their home
2025         // slots.
2026         TotalNumIntRegs = 4;
2027         GPR64ArgRegs = GPR64ArgRegsWin64;
2028       } else {
2029         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2030         GPR64ArgRegs = GPR64ArgRegs64Bit;
2031
2032         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2033                                                 TotalNumXMMRegs);
2034       }
2035       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2036                                                        TotalNumIntRegs);
2037
2038       bool NoImplicitFloatOps = Fn->getFnAttributes().
2039         hasAttribute(Attributes::NoImplicitFloat);
2040       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2041              "SSE register cannot be used when SSE is disabled!");
2042       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2043                NoImplicitFloatOps) &&
2044              "SSE register cannot be used when SSE is disabled!");
2045       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2046           !Subtarget->hasSSE1())
2047         // Kernel mode asks for SSE to be disabled, so don't push them
2048         // on the stack.
2049         TotalNumXMMRegs = 0;
2050
2051       if (IsWin64) {
2052         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2053         // Get to the caller-allocated home save location.  Add 8 to account
2054         // for the return address.
2055         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2056         FuncInfo->setRegSaveFrameIndex(
2057           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2058         // Fixup to set vararg frame on shadow area (4 x i64).
2059         if (NumIntRegs < 4)
2060           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2061       } else {
2062         // For X86-64, if there are vararg parameters that are passed via
2063         // registers, then we must store them to their spots on the stack so
2064         // they may be loaded by deferencing the result of va_next.
2065         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2066         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2067         FuncInfo->setRegSaveFrameIndex(
2068           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2069                                false));
2070       }
2071
2072       // Store the integer parameter registers.
2073       SmallVector<SDValue, 8> MemOps;
2074       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2075                                         getPointerTy());
2076       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2077       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2078         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2079                                   DAG.getIntPtrConstant(Offset));
2080         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2081                                      &X86::GR64RegClass);
2082         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2083         SDValue Store =
2084           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2085                        MachinePointerInfo::getFixedStack(
2086                          FuncInfo->getRegSaveFrameIndex(), Offset),
2087                        false, false, 0);
2088         MemOps.push_back(Store);
2089         Offset += 8;
2090       }
2091
2092       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2093         // Now store the XMM (fp + vector) parameter registers.
2094         SmallVector<SDValue, 11> SaveXMMOps;
2095         SaveXMMOps.push_back(Chain);
2096
2097         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2098         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2099         SaveXMMOps.push_back(ALVal);
2100
2101         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2102                                FuncInfo->getRegSaveFrameIndex()));
2103         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2104                                FuncInfo->getVarArgsFPOffset()));
2105
2106         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2107           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2108                                        &X86::VR128RegClass);
2109           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2110           SaveXMMOps.push_back(Val);
2111         }
2112         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2113                                      MVT::Other,
2114                                      &SaveXMMOps[0], SaveXMMOps.size()));
2115       }
2116
2117       if (!MemOps.empty())
2118         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2119                             &MemOps[0], MemOps.size());
2120     }
2121   }
2122
2123   // Some CCs need callee pop.
2124   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2125                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2126     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2127   } else {
2128     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2129     // If this is an sret function, the return should pop the hidden pointer.
2130     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2131         argsAreStructReturn(Ins) == StackStructReturn)
2132       FuncInfo->setBytesToPopOnReturn(4);
2133   }
2134
2135   if (!Is64Bit) {
2136     // RegSaveFrameIndex is X86-64 only.
2137     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2138     if (CallConv == CallingConv::X86_FastCall ||
2139         CallConv == CallingConv::X86_ThisCall)
2140       // fastcc functions can't have varargs.
2141       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2142   }
2143
2144   FuncInfo->setArgumentStackSize(StackSize);
2145
2146   return Chain;
2147 }
2148
2149 SDValue
2150 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2151                                     SDValue StackPtr, SDValue Arg,
2152                                     DebugLoc dl, SelectionDAG &DAG,
2153                                     const CCValAssign &VA,
2154                                     ISD::ArgFlagsTy Flags) const {
2155   unsigned LocMemOffset = VA.getLocMemOffset();
2156   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2157   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2158   if (Flags.isByVal())
2159     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2160
2161   return DAG.getStore(Chain, dl, Arg, PtrOff,
2162                       MachinePointerInfo::getStack(LocMemOffset),
2163                       false, false, 0);
2164 }
2165
2166 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2167 /// optimization is performed and it is required.
2168 SDValue
2169 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2170                                            SDValue &OutRetAddr, SDValue Chain,
2171                                            bool IsTailCall, bool Is64Bit,
2172                                            int FPDiff, DebugLoc dl) const {
2173   // Adjust the Return address stack slot.
2174   EVT VT = getPointerTy();
2175   OutRetAddr = getReturnAddressFrameIndex(DAG);
2176
2177   // Load the "old" Return address.
2178   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2179                            false, false, false, 0);
2180   return SDValue(OutRetAddr.getNode(), 1);
2181 }
2182
2183 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2184 /// optimization is performed and it is required (FPDiff!=0).
2185 static SDValue
2186 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2187                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2188                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
2189   // Store the return address to the appropriate stack slot.
2190   if (!FPDiff) return Chain;
2191   // Calculate the new stack slot for the return address.
2192   int NewReturnAddrFI =
2193     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2194   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2195   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2196                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2197                        false, false, 0);
2198   return Chain;
2199 }
2200
2201 SDValue
2202 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2203                              SmallVectorImpl<SDValue> &InVals) const {
2204   SelectionDAG &DAG                     = CLI.DAG;
2205   DebugLoc &dl                          = CLI.DL;
2206   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2207   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2208   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2209   SDValue Chain                         = CLI.Chain;
2210   SDValue Callee                        = CLI.Callee;
2211   CallingConv::ID CallConv              = CLI.CallConv;
2212   bool &isTailCall                      = CLI.IsTailCall;
2213   bool isVarArg                         = CLI.IsVarArg;
2214
2215   MachineFunction &MF = DAG.getMachineFunction();
2216   bool Is64Bit        = Subtarget->is64Bit();
2217   bool IsWin64        = Subtarget->isTargetWin64();
2218   bool IsWindows      = Subtarget->isTargetWindows();
2219   StructReturnType SR = callIsStructReturn(Outs);
2220   bool IsSibcall      = false;
2221
2222   if (MF.getTarget().Options.DisableTailCalls)
2223     isTailCall = false;
2224
2225   if (isTailCall) {
2226     // Check if it's really possible to do a tail call.
2227     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2228                     isVarArg, SR != NotStructReturn,
2229                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2230                     Outs, OutVals, Ins, DAG);
2231
2232     // Sibcalls are automatically detected tailcalls which do not require
2233     // ABI changes.
2234     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2235       IsSibcall = true;
2236
2237     if (isTailCall)
2238       ++NumTailCalls;
2239   }
2240
2241   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2242          "Var args not supported with calling convention fastcc or ghc");
2243
2244   // Analyze operands of the call, assigning locations to each operand.
2245   SmallVector<CCValAssign, 16> ArgLocs;
2246   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2247                  ArgLocs, *DAG.getContext());
2248
2249   // Allocate shadow area for Win64
2250   if (IsWin64) {
2251     CCInfo.AllocateStack(32, 8);
2252   }
2253
2254   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2255
2256   // Get a count of how many bytes are to be pushed on the stack.
2257   unsigned NumBytes = CCInfo.getNextStackOffset();
2258   if (IsSibcall)
2259     // This is a sibcall. The memory operands are available in caller's
2260     // own caller's stack.
2261     NumBytes = 0;
2262   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2263            IsTailCallConvention(CallConv))
2264     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2265
2266   int FPDiff = 0;
2267   if (isTailCall && !IsSibcall) {
2268     // Lower arguments at fp - stackoffset + fpdiff.
2269     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2270     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2271
2272     FPDiff = NumBytesCallerPushed - NumBytes;
2273
2274     // Set the delta of movement of the returnaddr stackslot.
2275     // But only set if delta is greater than previous delta.
2276     if (FPDiff < X86Info->getTCReturnAddrDelta())
2277       X86Info->setTCReturnAddrDelta(FPDiff);
2278   }
2279
2280   if (!IsSibcall)
2281     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2282
2283   SDValue RetAddrFrIdx;
2284   // Load return address for tail calls.
2285   if (isTailCall && FPDiff)
2286     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2287                                     Is64Bit, FPDiff, dl);
2288
2289   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2290   SmallVector<SDValue, 8> MemOpChains;
2291   SDValue StackPtr;
2292
2293   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2294   // of tail call optimization arguments are handle later.
2295   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2296     CCValAssign &VA = ArgLocs[i];
2297     EVT RegVT = VA.getLocVT();
2298     SDValue Arg = OutVals[i];
2299     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2300     bool isByVal = Flags.isByVal();
2301
2302     // Promote the value if needed.
2303     switch (VA.getLocInfo()) {
2304     default: llvm_unreachable("Unknown loc info!");
2305     case CCValAssign::Full: break;
2306     case CCValAssign::SExt:
2307       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2308       break;
2309     case CCValAssign::ZExt:
2310       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2311       break;
2312     case CCValAssign::AExt:
2313       if (RegVT.is128BitVector()) {
2314         // Special case: passing MMX values in XMM registers.
2315         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2316         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2317         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2318       } else
2319         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2320       break;
2321     case CCValAssign::BCvt:
2322       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2323       break;
2324     case CCValAssign::Indirect: {
2325       // Store the argument.
2326       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2327       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2328       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2329                            MachinePointerInfo::getFixedStack(FI),
2330                            false, false, 0);
2331       Arg = SpillSlot;
2332       break;
2333     }
2334     }
2335
2336     if (VA.isRegLoc()) {
2337       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2338       if (isVarArg && IsWin64) {
2339         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2340         // shadow reg if callee is a varargs function.
2341         unsigned ShadowReg = 0;
2342         switch (VA.getLocReg()) {
2343         case X86::XMM0: ShadowReg = X86::RCX; break;
2344         case X86::XMM1: ShadowReg = X86::RDX; break;
2345         case X86::XMM2: ShadowReg = X86::R8; break;
2346         case X86::XMM3: ShadowReg = X86::R9; break;
2347         }
2348         if (ShadowReg)
2349           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2350       }
2351     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2352       assert(VA.isMemLoc());
2353       if (StackPtr.getNode() == 0)
2354         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2355       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2356                                              dl, DAG, VA, Flags));
2357     }
2358   }
2359
2360   if (!MemOpChains.empty())
2361     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2362                         &MemOpChains[0], MemOpChains.size());
2363
2364   if (Subtarget->isPICStyleGOT()) {
2365     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2366     // GOT pointer.
2367     if (!isTailCall) {
2368       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2369                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2370     } else {
2371       // If we are tail calling and generating PIC/GOT style code load the
2372       // address of the callee into ECX. The value in ecx is used as target of
2373       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2374       // for tail calls on PIC/GOT architectures. Normally we would just put the
2375       // address of GOT into ebx and then call target@PLT. But for tail calls
2376       // ebx would be restored (since ebx is callee saved) before jumping to the
2377       // target@PLT.
2378
2379       // Note: The actual moving to ECX is done further down.
2380       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2381       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2382           !G->getGlobal()->hasProtectedVisibility())
2383         Callee = LowerGlobalAddress(Callee, DAG);
2384       else if (isa<ExternalSymbolSDNode>(Callee))
2385         Callee = LowerExternalSymbol(Callee, DAG);
2386     }
2387   }
2388
2389   if (Is64Bit && isVarArg && !IsWin64) {
2390     // From AMD64 ABI document:
2391     // For calls that may call functions that use varargs or stdargs
2392     // (prototype-less calls or calls to functions containing ellipsis (...) in
2393     // the declaration) %al is used as hidden argument to specify the number
2394     // of SSE registers used. The contents of %al do not need to match exactly
2395     // the number of registers, but must be an ubound on the number of SSE
2396     // registers used and is in the range 0 - 8 inclusive.
2397
2398     // Count the number of XMM registers allocated.
2399     static const uint16_t XMMArgRegs[] = {
2400       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2401       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2402     };
2403     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2404     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2405            && "SSE registers cannot be used when SSE is disabled");
2406
2407     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2408                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2409   }
2410
2411   // For tail calls lower the arguments to the 'real' stack slot.
2412   if (isTailCall) {
2413     // Force all the incoming stack arguments to be loaded from the stack
2414     // before any new outgoing arguments are stored to the stack, because the
2415     // outgoing stack slots may alias the incoming argument stack slots, and
2416     // the alias isn't otherwise explicit. This is slightly more conservative
2417     // than necessary, because it means that each store effectively depends
2418     // on every argument instead of just those arguments it would clobber.
2419     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2420
2421     SmallVector<SDValue, 8> MemOpChains2;
2422     SDValue FIN;
2423     int FI = 0;
2424     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2425       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2426         CCValAssign &VA = ArgLocs[i];
2427         if (VA.isRegLoc())
2428           continue;
2429         assert(VA.isMemLoc());
2430         SDValue Arg = OutVals[i];
2431         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2432         // Create frame index.
2433         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2434         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2435         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2436         FIN = DAG.getFrameIndex(FI, getPointerTy());
2437
2438         if (Flags.isByVal()) {
2439           // Copy relative to framepointer.
2440           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2441           if (StackPtr.getNode() == 0)
2442             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2443                                           getPointerTy());
2444           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2445
2446           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2447                                                            ArgChain,
2448                                                            Flags, DAG, dl));
2449         } else {
2450           // Store relative to framepointer.
2451           MemOpChains2.push_back(
2452             DAG.getStore(ArgChain, dl, Arg, FIN,
2453                          MachinePointerInfo::getFixedStack(FI),
2454                          false, false, 0));
2455         }
2456       }
2457     }
2458
2459     if (!MemOpChains2.empty())
2460       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2461                           &MemOpChains2[0], MemOpChains2.size());
2462
2463     // Store the return address to the appropriate stack slot.
2464     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2465                                      getPointerTy(), RegInfo->getSlotSize(),
2466                                      FPDiff, dl);
2467   }
2468
2469   // Build a sequence of copy-to-reg nodes chained together with token chain
2470   // and flag operands which copy the outgoing args into registers.
2471   SDValue InFlag;
2472   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2473     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2474                              RegsToPass[i].second, InFlag);
2475     InFlag = Chain.getValue(1);
2476   }
2477
2478   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2479     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2480     // In the 64-bit large code model, we have to make all calls
2481     // through a register, since the call instruction's 32-bit
2482     // pc-relative offset may not be large enough to hold the whole
2483     // address.
2484   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2485     // If the callee is a GlobalAddress node (quite common, every direct call
2486     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2487     // it.
2488
2489     // We should use extra load for direct calls to dllimported functions in
2490     // non-JIT mode.
2491     const GlobalValue *GV = G->getGlobal();
2492     if (!GV->hasDLLImportLinkage()) {
2493       unsigned char OpFlags = 0;
2494       bool ExtraLoad = false;
2495       unsigned WrapperKind = ISD::DELETED_NODE;
2496
2497       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2498       // external symbols most go through the PLT in PIC mode.  If the symbol
2499       // has hidden or protected visibility, or if it is static or local, then
2500       // we don't need to use the PLT - we can directly call it.
2501       if (Subtarget->isTargetELF() &&
2502           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2503           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2504         OpFlags = X86II::MO_PLT;
2505       } else if (Subtarget->isPICStyleStubAny() &&
2506                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2507                  (!Subtarget->getTargetTriple().isMacOSX() ||
2508                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2509         // PC-relative references to external symbols should go through $stub,
2510         // unless we're building with the leopard linker or later, which
2511         // automatically synthesizes these stubs.
2512         OpFlags = X86II::MO_DARWIN_STUB;
2513       } else if (Subtarget->isPICStyleRIPRel() &&
2514                  isa<Function>(GV) &&
2515                  cast<Function>(GV)->getFnAttributes().
2516                    hasAttribute(Attributes::NonLazyBind)) {
2517         // If the function is marked as non-lazy, generate an indirect call
2518         // which loads from the GOT directly. This avoids runtime overhead
2519         // at the cost of eager binding (and one extra byte of encoding).
2520         OpFlags = X86II::MO_GOTPCREL;
2521         WrapperKind = X86ISD::WrapperRIP;
2522         ExtraLoad = true;
2523       }
2524
2525       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2526                                           G->getOffset(), OpFlags);
2527
2528       // Add a wrapper if needed.
2529       if (WrapperKind != ISD::DELETED_NODE)
2530         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2531       // Add extra indirection if needed.
2532       if (ExtraLoad)
2533         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2534                              MachinePointerInfo::getGOT(),
2535                              false, false, false, 0);
2536     }
2537   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2538     unsigned char OpFlags = 0;
2539
2540     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2541     // external symbols should go through the PLT.
2542     if (Subtarget->isTargetELF() &&
2543         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2544       OpFlags = X86II::MO_PLT;
2545     } else if (Subtarget->isPICStyleStubAny() &&
2546                (!Subtarget->getTargetTriple().isMacOSX() ||
2547                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2548       // PC-relative references to external symbols should go through $stub,
2549       // unless we're building with the leopard linker or later, which
2550       // automatically synthesizes these stubs.
2551       OpFlags = X86II::MO_DARWIN_STUB;
2552     }
2553
2554     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2555                                          OpFlags);
2556   }
2557
2558   // Returns a chain & a flag for retval copy to use.
2559   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2560   SmallVector<SDValue, 8> Ops;
2561
2562   if (!IsSibcall && isTailCall) {
2563     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2564                            DAG.getIntPtrConstant(0, true), InFlag);
2565     InFlag = Chain.getValue(1);
2566   }
2567
2568   Ops.push_back(Chain);
2569   Ops.push_back(Callee);
2570
2571   if (isTailCall)
2572     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2573
2574   // Add argument registers to the end of the list so that they are known live
2575   // into the call.
2576   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2577     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2578                                   RegsToPass[i].second.getValueType()));
2579
2580   // Add a register mask operand representing the call-preserved registers.
2581   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2582   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2583   assert(Mask && "Missing call preserved mask for calling convention");
2584   Ops.push_back(DAG.getRegisterMask(Mask));
2585
2586   if (InFlag.getNode())
2587     Ops.push_back(InFlag);
2588
2589   if (isTailCall) {
2590     // We used to do:
2591     //// If this is the first return lowered for this function, add the regs
2592     //// to the liveout set for the function.
2593     // This isn't right, although it's probably harmless on x86; liveouts
2594     // should be computed from returns not tail calls.  Consider a void
2595     // function making a tail call to a function returning int.
2596     return DAG.getNode(X86ISD::TC_RETURN, dl,
2597                        NodeTys, &Ops[0], Ops.size());
2598   }
2599
2600   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2601   InFlag = Chain.getValue(1);
2602
2603   // Create the CALLSEQ_END node.
2604   unsigned NumBytesForCalleeToPush;
2605   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2606                        getTargetMachine().Options.GuaranteedTailCallOpt))
2607     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2608   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2609            SR == StackStructReturn)
2610     // If this is a call to a struct-return function, the callee
2611     // pops the hidden struct pointer, so we have to push it back.
2612     // This is common for Darwin/X86, Linux & Mingw32 targets.
2613     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2614     NumBytesForCalleeToPush = 4;
2615   else
2616     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2617
2618   // Returns a flag for retval copy to use.
2619   if (!IsSibcall) {
2620     Chain = DAG.getCALLSEQ_END(Chain,
2621                                DAG.getIntPtrConstant(NumBytes, true),
2622                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2623                                                      true),
2624                                InFlag);
2625     InFlag = Chain.getValue(1);
2626   }
2627
2628   // Handle result values, copying them out of physregs into vregs that we
2629   // return.
2630   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2631                          Ins, dl, DAG, InVals);
2632 }
2633
2634
2635 //===----------------------------------------------------------------------===//
2636 //                Fast Calling Convention (tail call) implementation
2637 //===----------------------------------------------------------------------===//
2638
2639 //  Like std call, callee cleans arguments, convention except that ECX is
2640 //  reserved for storing the tail called function address. Only 2 registers are
2641 //  free for argument passing (inreg). Tail call optimization is performed
2642 //  provided:
2643 //                * tailcallopt is enabled
2644 //                * caller/callee are fastcc
2645 //  On X86_64 architecture with GOT-style position independent code only local
2646 //  (within module) calls are supported at the moment.
2647 //  To keep the stack aligned according to platform abi the function
2648 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2649 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2650 //  If a tail called function callee has more arguments than the caller the
2651 //  caller needs to make sure that there is room to move the RETADDR to. This is
2652 //  achieved by reserving an area the size of the argument delta right after the
2653 //  original REtADDR, but before the saved framepointer or the spilled registers
2654 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2655 //  stack layout:
2656 //    arg1
2657 //    arg2
2658 //    RETADDR
2659 //    [ new RETADDR
2660 //      move area ]
2661 //    (possible EBP)
2662 //    ESI
2663 //    EDI
2664 //    local1 ..
2665
2666 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2667 /// for a 16 byte align requirement.
2668 unsigned
2669 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2670                                                SelectionDAG& DAG) const {
2671   MachineFunction &MF = DAG.getMachineFunction();
2672   const TargetMachine &TM = MF.getTarget();
2673   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2674   unsigned StackAlignment = TFI.getStackAlignment();
2675   uint64_t AlignMask = StackAlignment - 1;
2676   int64_t Offset = StackSize;
2677   unsigned SlotSize = RegInfo->getSlotSize();
2678   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2679     // Number smaller than 12 so just add the difference.
2680     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2681   } else {
2682     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2683     Offset = ((~AlignMask) & Offset) + StackAlignment +
2684       (StackAlignment-SlotSize);
2685   }
2686   return Offset;
2687 }
2688
2689 /// MatchingStackOffset - Return true if the given stack call argument is
2690 /// already available in the same position (relatively) of the caller's
2691 /// incoming argument stack.
2692 static
2693 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2694                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2695                          const X86InstrInfo *TII) {
2696   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2697   int FI = INT_MAX;
2698   if (Arg.getOpcode() == ISD::CopyFromReg) {
2699     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2700     if (!TargetRegisterInfo::isVirtualRegister(VR))
2701       return false;
2702     MachineInstr *Def = MRI->getVRegDef(VR);
2703     if (!Def)
2704       return false;
2705     if (!Flags.isByVal()) {
2706       if (!TII->isLoadFromStackSlot(Def, FI))
2707         return false;
2708     } else {
2709       unsigned Opcode = Def->getOpcode();
2710       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2711           Def->getOperand(1).isFI()) {
2712         FI = Def->getOperand(1).getIndex();
2713         Bytes = Flags.getByValSize();
2714       } else
2715         return false;
2716     }
2717   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2718     if (Flags.isByVal())
2719       // ByVal argument is passed in as a pointer but it's now being
2720       // dereferenced. e.g.
2721       // define @foo(%struct.X* %A) {
2722       //   tail call @bar(%struct.X* byval %A)
2723       // }
2724       return false;
2725     SDValue Ptr = Ld->getBasePtr();
2726     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2727     if (!FINode)
2728       return false;
2729     FI = FINode->getIndex();
2730   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2731     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2732     FI = FINode->getIndex();
2733     Bytes = Flags.getByValSize();
2734   } else
2735     return false;
2736
2737   assert(FI != INT_MAX);
2738   if (!MFI->isFixedObjectIndex(FI))
2739     return false;
2740   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2741 }
2742
2743 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2744 /// for tail call optimization. Targets which want to do tail call
2745 /// optimization should implement this function.
2746 bool
2747 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2748                                                      CallingConv::ID CalleeCC,
2749                                                      bool isVarArg,
2750                                                      bool isCalleeStructRet,
2751                                                      bool isCallerStructRet,
2752                                                      Type *RetTy,
2753                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2754                                     const SmallVectorImpl<SDValue> &OutVals,
2755                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2756                                                      SelectionDAG& DAG) const {
2757   if (!IsTailCallConvention(CalleeCC) &&
2758       CalleeCC != CallingConv::C)
2759     return false;
2760
2761   // If -tailcallopt is specified, make fastcc functions tail-callable.
2762   const MachineFunction &MF = DAG.getMachineFunction();
2763   const Function *CallerF = DAG.getMachineFunction().getFunction();
2764
2765   // If the function return type is x86_fp80 and the callee return type is not,
2766   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2767   // perform a tailcall optimization here.
2768   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2769     return false;
2770
2771   CallingConv::ID CallerCC = CallerF->getCallingConv();
2772   bool CCMatch = CallerCC == CalleeCC;
2773
2774   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2775     if (IsTailCallConvention(CalleeCC) && CCMatch)
2776       return true;
2777     return false;
2778   }
2779
2780   // Look for obvious safe cases to perform tail call optimization that do not
2781   // require ABI changes. This is what gcc calls sibcall.
2782
2783   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2784   // emit a special epilogue.
2785   if (RegInfo->needsStackRealignment(MF))
2786     return false;
2787
2788   // Also avoid sibcall optimization if either caller or callee uses struct
2789   // return semantics.
2790   if (isCalleeStructRet || isCallerStructRet)
2791     return false;
2792
2793   // An stdcall caller is expected to clean up its arguments; the callee
2794   // isn't going to do that.
2795   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2796     return false;
2797
2798   // Do not sibcall optimize vararg calls unless all arguments are passed via
2799   // registers.
2800   if (isVarArg && !Outs.empty()) {
2801
2802     // Optimizing for varargs on Win64 is unlikely to be safe without
2803     // additional testing.
2804     if (Subtarget->isTargetWin64())
2805       return false;
2806
2807     SmallVector<CCValAssign, 16> ArgLocs;
2808     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2809                    getTargetMachine(), ArgLocs, *DAG.getContext());
2810
2811     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2812     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2813       if (!ArgLocs[i].isRegLoc())
2814         return false;
2815   }
2816
2817   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2818   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2819   // this into a sibcall.
2820   bool Unused = false;
2821   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2822     if (!Ins[i].Used) {
2823       Unused = true;
2824       break;
2825     }
2826   }
2827   if (Unused) {
2828     SmallVector<CCValAssign, 16> RVLocs;
2829     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2830                    getTargetMachine(), RVLocs, *DAG.getContext());
2831     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2832     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2833       CCValAssign &VA = RVLocs[i];
2834       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2835         return false;
2836     }
2837   }
2838
2839   // If the calling conventions do not match, then we'd better make sure the
2840   // results are returned in the same way as what the caller expects.
2841   if (!CCMatch) {
2842     SmallVector<CCValAssign, 16> RVLocs1;
2843     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2844                     getTargetMachine(), RVLocs1, *DAG.getContext());
2845     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2846
2847     SmallVector<CCValAssign, 16> RVLocs2;
2848     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2849                     getTargetMachine(), RVLocs2, *DAG.getContext());
2850     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2851
2852     if (RVLocs1.size() != RVLocs2.size())
2853       return false;
2854     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2855       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2856         return false;
2857       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2858         return false;
2859       if (RVLocs1[i].isRegLoc()) {
2860         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2861           return false;
2862       } else {
2863         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2864           return false;
2865       }
2866     }
2867   }
2868
2869   // If the callee takes no arguments then go on to check the results of the
2870   // call.
2871   if (!Outs.empty()) {
2872     // Check if stack adjustment is needed. For now, do not do this if any
2873     // argument is passed on the stack.
2874     SmallVector<CCValAssign, 16> ArgLocs;
2875     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2876                    getTargetMachine(), ArgLocs, *DAG.getContext());
2877
2878     // Allocate shadow area for Win64
2879     if (Subtarget->isTargetWin64()) {
2880       CCInfo.AllocateStack(32, 8);
2881     }
2882
2883     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2884     if (CCInfo.getNextStackOffset()) {
2885       MachineFunction &MF = DAG.getMachineFunction();
2886       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2887         return false;
2888
2889       // Check if the arguments are already laid out in the right way as
2890       // the caller's fixed stack objects.
2891       MachineFrameInfo *MFI = MF.getFrameInfo();
2892       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2893       const X86InstrInfo *TII =
2894         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2895       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2896         CCValAssign &VA = ArgLocs[i];
2897         SDValue Arg = OutVals[i];
2898         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2899         if (VA.getLocInfo() == CCValAssign::Indirect)
2900           return false;
2901         if (!VA.isRegLoc()) {
2902           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2903                                    MFI, MRI, TII))
2904             return false;
2905         }
2906       }
2907     }
2908
2909     // If the tailcall address may be in a register, then make sure it's
2910     // possible to register allocate for it. In 32-bit, the call address can
2911     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2912     // callee-saved registers are restored. These happen to be the same
2913     // registers used to pass 'inreg' arguments so watch out for those.
2914     if (!Subtarget->is64Bit() &&
2915         !isa<GlobalAddressSDNode>(Callee) &&
2916         !isa<ExternalSymbolSDNode>(Callee)) {
2917       unsigned NumInRegs = 0;
2918       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2919         CCValAssign &VA = ArgLocs[i];
2920         if (!VA.isRegLoc())
2921           continue;
2922         unsigned Reg = VA.getLocReg();
2923         switch (Reg) {
2924         default: break;
2925         case X86::EAX: case X86::EDX: case X86::ECX:
2926           if (++NumInRegs == 3)
2927             return false;
2928           break;
2929         }
2930       }
2931     }
2932   }
2933
2934   return true;
2935 }
2936
2937 FastISel *
2938 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2939                                   const TargetLibraryInfo *libInfo) const {
2940   return X86::createFastISel(funcInfo, libInfo);
2941 }
2942
2943
2944 //===----------------------------------------------------------------------===//
2945 //                           Other Lowering Hooks
2946 //===----------------------------------------------------------------------===//
2947
2948 static bool MayFoldLoad(SDValue Op) {
2949   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2950 }
2951
2952 static bool MayFoldIntoStore(SDValue Op) {
2953   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2954 }
2955
2956 static bool isTargetShuffle(unsigned Opcode) {
2957   switch(Opcode) {
2958   default: return false;
2959   case X86ISD::PSHUFD:
2960   case X86ISD::PSHUFHW:
2961   case X86ISD::PSHUFLW:
2962   case X86ISD::SHUFP:
2963   case X86ISD::PALIGN:
2964   case X86ISD::MOVLHPS:
2965   case X86ISD::MOVLHPD:
2966   case X86ISD::MOVHLPS:
2967   case X86ISD::MOVLPS:
2968   case X86ISD::MOVLPD:
2969   case X86ISD::MOVSHDUP:
2970   case X86ISD::MOVSLDUP:
2971   case X86ISD::MOVDDUP:
2972   case X86ISD::MOVSS:
2973   case X86ISD::MOVSD:
2974   case X86ISD::UNPCKL:
2975   case X86ISD::UNPCKH:
2976   case X86ISD::VPERMILP:
2977   case X86ISD::VPERM2X128:
2978   case X86ISD::VPERMI:
2979     return true;
2980   }
2981 }
2982
2983 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2984                                     SDValue V1, SelectionDAG &DAG) {
2985   switch(Opc) {
2986   default: llvm_unreachable("Unknown x86 shuffle node");
2987   case X86ISD::MOVSHDUP:
2988   case X86ISD::MOVSLDUP:
2989   case X86ISD::MOVDDUP:
2990     return DAG.getNode(Opc, dl, VT, V1);
2991   }
2992 }
2993
2994 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2995                                     SDValue V1, unsigned TargetMask,
2996                                     SelectionDAG &DAG) {
2997   switch(Opc) {
2998   default: llvm_unreachable("Unknown x86 shuffle node");
2999   case X86ISD::PSHUFD:
3000   case X86ISD::PSHUFHW:
3001   case X86ISD::PSHUFLW:
3002   case X86ISD::VPERMILP:
3003   case X86ISD::VPERMI:
3004     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3005   }
3006 }
3007
3008 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3009                                     SDValue V1, SDValue V2, unsigned TargetMask,
3010                                     SelectionDAG &DAG) {
3011   switch(Opc) {
3012   default: llvm_unreachable("Unknown x86 shuffle node");
3013   case X86ISD::PALIGN:
3014   case X86ISD::SHUFP:
3015   case X86ISD::VPERM2X128:
3016     return DAG.getNode(Opc, dl, VT, V1, V2,
3017                        DAG.getConstant(TargetMask, MVT::i8));
3018   }
3019 }
3020
3021 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3022                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3023   switch(Opc) {
3024   default: llvm_unreachable("Unknown x86 shuffle node");
3025   case X86ISD::MOVLHPS:
3026   case X86ISD::MOVLHPD:
3027   case X86ISD::MOVHLPS:
3028   case X86ISD::MOVLPS:
3029   case X86ISD::MOVLPD:
3030   case X86ISD::MOVSS:
3031   case X86ISD::MOVSD:
3032   case X86ISD::UNPCKL:
3033   case X86ISD::UNPCKH:
3034     return DAG.getNode(Opc, dl, VT, V1, V2);
3035   }
3036 }
3037
3038 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3039   MachineFunction &MF = DAG.getMachineFunction();
3040   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3041   int ReturnAddrIndex = FuncInfo->getRAIndex();
3042
3043   if (ReturnAddrIndex == 0) {
3044     // Set up a frame object for the return address.
3045     unsigned SlotSize = RegInfo->getSlotSize();
3046     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3047                                                            false);
3048     FuncInfo->setRAIndex(ReturnAddrIndex);
3049   }
3050
3051   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3052 }
3053
3054
3055 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3056                                        bool hasSymbolicDisplacement) {
3057   // Offset should fit into 32 bit immediate field.
3058   if (!isInt<32>(Offset))
3059     return false;
3060
3061   // If we don't have a symbolic displacement - we don't have any extra
3062   // restrictions.
3063   if (!hasSymbolicDisplacement)
3064     return true;
3065
3066   // FIXME: Some tweaks might be needed for medium code model.
3067   if (M != CodeModel::Small && M != CodeModel::Kernel)
3068     return false;
3069
3070   // For small code model we assume that latest object is 16MB before end of 31
3071   // bits boundary. We may also accept pretty large negative constants knowing
3072   // that all objects are in the positive half of address space.
3073   if (M == CodeModel::Small && Offset < 16*1024*1024)
3074     return true;
3075
3076   // For kernel code model we know that all object resist in the negative half
3077   // of 32bits address space. We may not accept negative offsets, since they may
3078   // be just off and we may accept pretty large positive ones.
3079   if (M == CodeModel::Kernel && Offset > 0)
3080     return true;
3081
3082   return false;
3083 }
3084
3085 /// isCalleePop - Determines whether the callee is required to pop its
3086 /// own arguments. Callee pop is necessary to support tail calls.
3087 bool X86::isCalleePop(CallingConv::ID CallingConv,
3088                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3089   if (IsVarArg)
3090     return false;
3091
3092   switch (CallingConv) {
3093   default:
3094     return false;
3095   case CallingConv::X86_StdCall:
3096     return !is64Bit;
3097   case CallingConv::X86_FastCall:
3098     return !is64Bit;
3099   case CallingConv::X86_ThisCall:
3100     return !is64Bit;
3101   case CallingConv::Fast:
3102     return TailCallOpt;
3103   case CallingConv::GHC:
3104     return TailCallOpt;
3105   }
3106 }
3107
3108 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3109 /// specific condition code, returning the condition code and the LHS/RHS of the
3110 /// comparison to make.
3111 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3112                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3113   if (!isFP) {
3114     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3115       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3116         // X > -1   -> X == 0, jump !sign.
3117         RHS = DAG.getConstant(0, RHS.getValueType());
3118         return X86::COND_NS;
3119       }
3120       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3121         // X < 0   -> X == 0, jump on sign.
3122         return X86::COND_S;
3123       }
3124       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3125         // X < 1   -> X <= 0
3126         RHS = DAG.getConstant(0, RHS.getValueType());
3127         return X86::COND_LE;
3128       }
3129     }
3130
3131     switch (SetCCOpcode) {
3132     default: llvm_unreachable("Invalid integer condition!");
3133     case ISD::SETEQ:  return X86::COND_E;
3134     case ISD::SETGT:  return X86::COND_G;
3135     case ISD::SETGE:  return X86::COND_GE;
3136     case ISD::SETLT:  return X86::COND_L;
3137     case ISD::SETLE:  return X86::COND_LE;
3138     case ISD::SETNE:  return X86::COND_NE;
3139     case ISD::SETULT: return X86::COND_B;
3140     case ISD::SETUGT: return X86::COND_A;
3141     case ISD::SETULE: return X86::COND_BE;
3142     case ISD::SETUGE: return X86::COND_AE;
3143     }
3144   }
3145
3146   // First determine if it is required or is profitable to flip the operands.
3147
3148   // If LHS is a foldable load, but RHS is not, flip the condition.
3149   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3150       !ISD::isNON_EXTLoad(RHS.getNode())) {
3151     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3152     std::swap(LHS, RHS);
3153   }
3154
3155   switch (SetCCOpcode) {
3156   default: break;
3157   case ISD::SETOLT:
3158   case ISD::SETOLE:
3159   case ISD::SETUGT:
3160   case ISD::SETUGE:
3161     std::swap(LHS, RHS);
3162     break;
3163   }
3164
3165   // On a floating point condition, the flags are set as follows:
3166   // ZF  PF  CF   op
3167   //  0 | 0 | 0 | X > Y
3168   //  0 | 0 | 1 | X < Y
3169   //  1 | 0 | 0 | X == Y
3170   //  1 | 1 | 1 | unordered
3171   switch (SetCCOpcode) {
3172   default: llvm_unreachable("Condcode should be pre-legalized away");
3173   case ISD::SETUEQ:
3174   case ISD::SETEQ:   return X86::COND_E;
3175   case ISD::SETOLT:              // flipped
3176   case ISD::SETOGT:
3177   case ISD::SETGT:   return X86::COND_A;
3178   case ISD::SETOLE:              // flipped
3179   case ISD::SETOGE:
3180   case ISD::SETGE:   return X86::COND_AE;
3181   case ISD::SETUGT:              // flipped
3182   case ISD::SETULT:
3183   case ISD::SETLT:   return X86::COND_B;
3184   case ISD::SETUGE:              // flipped
3185   case ISD::SETULE:
3186   case ISD::SETLE:   return X86::COND_BE;
3187   case ISD::SETONE:
3188   case ISD::SETNE:   return X86::COND_NE;
3189   case ISD::SETUO:   return X86::COND_P;
3190   case ISD::SETO:    return X86::COND_NP;
3191   case ISD::SETOEQ:
3192   case ISD::SETUNE:  return X86::COND_INVALID;
3193   }
3194 }
3195
3196 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3197 /// code. Current x86 isa includes the following FP cmov instructions:
3198 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3199 static bool hasFPCMov(unsigned X86CC) {
3200   switch (X86CC) {
3201   default:
3202     return false;
3203   case X86::COND_B:
3204   case X86::COND_BE:
3205   case X86::COND_E:
3206   case X86::COND_P:
3207   case X86::COND_A:
3208   case X86::COND_AE:
3209   case X86::COND_NE:
3210   case X86::COND_NP:
3211     return true;
3212   }
3213 }
3214
3215 /// isFPImmLegal - Returns true if the target can instruction select the
3216 /// specified FP immediate natively. If false, the legalizer will
3217 /// materialize the FP immediate as a load from a constant pool.
3218 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3219   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3220     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3221       return true;
3222   }
3223   return false;
3224 }
3225
3226 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3227 /// the specified range (L, H].
3228 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3229   return (Val < 0) || (Val >= Low && Val < Hi);
3230 }
3231
3232 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3233 /// specified value.
3234 static bool isUndefOrEqual(int Val, int CmpVal) {
3235   if (Val < 0 || Val == CmpVal)
3236     return true;
3237   return false;
3238 }
3239
3240 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3241 /// from position Pos and ending in Pos+Size, falls within the specified
3242 /// sequential range (L, L+Pos]. or is undef.
3243 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3244                                        unsigned Pos, unsigned Size, int Low) {
3245   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3246     if (!isUndefOrEqual(Mask[i], Low))
3247       return false;
3248   return true;
3249 }
3250
3251 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3252 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3253 /// the second operand.
3254 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3255   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3256     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3257   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3258     return (Mask[0] < 2 && Mask[1] < 2);
3259   return false;
3260 }
3261
3262 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3263 /// is suitable for input to PSHUFHW.
3264 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3265   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3266     return false;
3267
3268   // Lower quadword copied in order or undef.
3269   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3270     return false;
3271
3272   // Upper quadword shuffled.
3273   for (unsigned i = 4; i != 8; ++i)
3274     if (!isUndefOrInRange(Mask[i], 4, 8))
3275       return false;
3276
3277   if (VT == MVT::v16i16) {
3278     // Lower quadword copied in order or undef.
3279     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3280       return false;
3281
3282     // Upper quadword shuffled.
3283     for (unsigned i = 12; i != 16; ++i)
3284       if (!isUndefOrInRange(Mask[i], 12, 16))
3285         return false;
3286   }
3287
3288   return true;
3289 }
3290
3291 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3292 /// is suitable for input to PSHUFLW.
3293 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3294   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3295     return false;
3296
3297   // Upper quadword copied in order.
3298   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3299     return false;
3300
3301   // Lower quadword shuffled.
3302   for (unsigned i = 0; i != 4; ++i)
3303     if (!isUndefOrInRange(Mask[i], 0, 4))
3304       return false;
3305
3306   if (VT == MVT::v16i16) {
3307     // Upper quadword copied in order.
3308     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3309       return false;
3310
3311     // Lower quadword shuffled.
3312     for (unsigned i = 8; i != 12; ++i)
3313       if (!isUndefOrInRange(Mask[i], 8, 12))
3314         return false;
3315   }
3316
3317   return true;
3318 }
3319
3320 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3321 /// is suitable for input to PALIGNR.
3322 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3323                           const X86Subtarget *Subtarget) {
3324   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3325       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3326     return false;
3327
3328   unsigned NumElts = VT.getVectorNumElements();
3329   unsigned NumLanes = VT.getSizeInBits()/128;
3330   unsigned NumLaneElts = NumElts/NumLanes;
3331
3332   // Do not handle 64-bit element shuffles with palignr.
3333   if (NumLaneElts == 2)
3334     return false;
3335
3336   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3337     unsigned i;
3338     for (i = 0; i != NumLaneElts; ++i) {
3339       if (Mask[i+l] >= 0)
3340         break;
3341     }
3342
3343     // Lane is all undef, go to next lane
3344     if (i == NumLaneElts)
3345       continue;
3346
3347     int Start = Mask[i+l];
3348
3349     // Make sure its in this lane in one of the sources
3350     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3351         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3352       return false;
3353
3354     // If not lane 0, then we must match lane 0
3355     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3356       return false;
3357
3358     // Correct second source to be contiguous with first source
3359     if (Start >= (int)NumElts)
3360       Start -= NumElts - NumLaneElts;
3361
3362     // Make sure we're shifting in the right direction.
3363     if (Start <= (int)(i+l))
3364       return false;
3365
3366     Start -= i;
3367
3368     // Check the rest of the elements to see if they are consecutive.
3369     for (++i; i != NumLaneElts; ++i) {
3370       int Idx = Mask[i+l];
3371
3372       // Make sure its in this lane
3373       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3374           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3375         return false;
3376
3377       // If not lane 0, then we must match lane 0
3378       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3379         return false;
3380
3381       if (Idx >= (int)NumElts)
3382         Idx -= NumElts - NumLaneElts;
3383
3384       if (!isUndefOrEqual(Idx, Start+i))
3385         return false;
3386
3387     }
3388   }
3389
3390   return true;
3391 }
3392
3393 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3394 /// the two vector operands have swapped position.
3395 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3396                                      unsigned NumElems) {
3397   for (unsigned i = 0; i != NumElems; ++i) {
3398     int idx = Mask[i];
3399     if (idx < 0)
3400       continue;
3401     else if (idx < (int)NumElems)
3402       Mask[i] = idx + NumElems;
3403     else
3404       Mask[i] = idx - NumElems;
3405   }
3406 }
3407
3408 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3409 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3410 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3411 /// reverse of what x86 shuffles want.
3412 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3413                         bool Commuted = false) {
3414   if (!HasAVX && VT.getSizeInBits() == 256)
3415     return false;
3416
3417   unsigned NumElems = VT.getVectorNumElements();
3418   unsigned NumLanes = VT.getSizeInBits()/128;
3419   unsigned NumLaneElems = NumElems/NumLanes;
3420
3421   if (NumLaneElems != 2 && NumLaneElems != 4)
3422     return false;
3423
3424   // VSHUFPSY divides the resulting vector into 4 chunks.
3425   // The sources are also splitted into 4 chunks, and each destination
3426   // chunk must come from a different source chunk.
3427   //
3428   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3429   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3430   //
3431   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3432   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3433   //
3434   // VSHUFPDY divides the resulting vector into 4 chunks.
3435   // The sources are also splitted into 4 chunks, and each destination
3436   // chunk must come from a different source chunk.
3437   //
3438   //  SRC1 =>      X3       X2       X1       X0
3439   //  SRC2 =>      Y3       Y2       Y1       Y0
3440   //
3441   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3442   //
3443   unsigned HalfLaneElems = NumLaneElems/2;
3444   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3445     for (unsigned i = 0; i != NumLaneElems; ++i) {
3446       int Idx = Mask[i+l];
3447       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3448       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3449         return false;
3450       // For VSHUFPSY, the mask of the second half must be the same as the
3451       // first but with the appropriate offsets. This works in the same way as
3452       // VPERMILPS works with masks.
3453       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3454         continue;
3455       if (!isUndefOrEqual(Idx, Mask[i]+l))
3456         return false;
3457     }
3458   }
3459
3460   return true;
3461 }
3462
3463 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3464 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3465 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3466   if (!VT.is128BitVector())
3467     return false;
3468
3469   unsigned NumElems = VT.getVectorNumElements();
3470
3471   if (NumElems != 4)
3472     return false;
3473
3474   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3475   return isUndefOrEqual(Mask[0], 6) &&
3476          isUndefOrEqual(Mask[1], 7) &&
3477          isUndefOrEqual(Mask[2], 2) &&
3478          isUndefOrEqual(Mask[3], 3);
3479 }
3480
3481 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3482 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3483 /// <2, 3, 2, 3>
3484 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3485   if (!VT.is128BitVector())
3486     return false;
3487
3488   unsigned NumElems = VT.getVectorNumElements();
3489
3490   if (NumElems != 4)
3491     return false;
3492
3493   return isUndefOrEqual(Mask[0], 2) &&
3494          isUndefOrEqual(Mask[1], 3) &&
3495          isUndefOrEqual(Mask[2], 2) &&
3496          isUndefOrEqual(Mask[3], 3);
3497 }
3498
3499 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3500 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3501 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3502   if (!VT.is128BitVector())
3503     return false;
3504
3505   unsigned NumElems = VT.getVectorNumElements();
3506
3507   if (NumElems != 2 && NumElems != 4)
3508     return false;
3509
3510   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3511     if (!isUndefOrEqual(Mask[i], i + NumElems))
3512       return false;
3513
3514   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3515     if (!isUndefOrEqual(Mask[i], i))
3516       return false;
3517
3518   return true;
3519 }
3520
3521 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3522 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3523 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3524   if (!VT.is128BitVector())
3525     return false;
3526
3527   unsigned NumElems = VT.getVectorNumElements();
3528
3529   if (NumElems != 2 && NumElems != 4)
3530     return false;
3531
3532   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3533     if (!isUndefOrEqual(Mask[i], i))
3534       return false;
3535
3536   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3537     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3538       return false;
3539
3540   return true;
3541 }
3542
3543 //
3544 // Some special combinations that can be optimized.
3545 //
3546 static
3547 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3548                                SelectionDAG &DAG) {
3549   EVT VT = SVOp->getValueType(0);
3550   DebugLoc dl = SVOp->getDebugLoc();
3551
3552   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3553     return SDValue();
3554
3555   ArrayRef<int> Mask = SVOp->getMask();
3556
3557   // These are the special masks that may be optimized.
3558   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3559   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3560   bool MatchEvenMask = true;
3561   bool MatchOddMask  = true;
3562   for (int i=0; i<8; ++i) {
3563     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3564       MatchEvenMask = false;
3565     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3566       MatchOddMask = false;
3567   }
3568
3569   if (!MatchEvenMask && !MatchOddMask)
3570     return SDValue();
3571
3572   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3573
3574   SDValue Op0 = SVOp->getOperand(0);
3575   SDValue Op1 = SVOp->getOperand(1);
3576
3577   if (MatchEvenMask) {
3578     // Shift the second operand right to 32 bits.
3579     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3580     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3581   } else {
3582     // Shift the first operand left to 32 bits.
3583     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3584     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3585   }
3586   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3587   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3588 }
3589
3590 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3591 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3592 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3593                          bool HasAVX2, bool V2IsSplat = false) {
3594   unsigned NumElts = VT.getVectorNumElements();
3595
3596   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3597          "Unsupported vector type for unpckh");
3598
3599   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3600       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3601     return false;
3602
3603   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3604   // independently on 128-bit lanes.
3605   unsigned NumLanes = VT.getSizeInBits()/128;
3606   unsigned NumLaneElts = NumElts/NumLanes;
3607
3608   for (unsigned l = 0; l != NumLanes; ++l) {
3609     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3610          i != (l+1)*NumLaneElts;
3611          i += 2, ++j) {
3612       int BitI  = Mask[i];
3613       int BitI1 = Mask[i+1];
3614       if (!isUndefOrEqual(BitI, j))
3615         return false;
3616       if (V2IsSplat) {
3617         if (!isUndefOrEqual(BitI1, NumElts))
3618           return false;
3619       } else {
3620         if (!isUndefOrEqual(BitI1, j + NumElts))
3621           return false;
3622       }
3623     }
3624   }
3625
3626   return true;
3627 }
3628
3629 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3630 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3631 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3632                          bool HasAVX2, bool V2IsSplat = false) {
3633   unsigned NumElts = VT.getVectorNumElements();
3634
3635   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3636          "Unsupported vector type for unpckh");
3637
3638   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3639       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3640     return false;
3641
3642   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3643   // independently on 128-bit lanes.
3644   unsigned NumLanes = VT.getSizeInBits()/128;
3645   unsigned NumLaneElts = NumElts/NumLanes;
3646
3647   for (unsigned l = 0; l != NumLanes; ++l) {
3648     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3649          i != (l+1)*NumLaneElts; i += 2, ++j) {
3650       int BitI  = Mask[i];
3651       int BitI1 = Mask[i+1];
3652       if (!isUndefOrEqual(BitI, j))
3653         return false;
3654       if (V2IsSplat) {
3655         if (isUndefOrEqual(BitI1, NumElts))
3656           return false;
3657       } else {
3658         if (!isUndefOrEqual(BitI1, j+NumElts))
3659           return false;
3660       }
3661     }
3662   }
3663   return true;
3664 }
3665
3666 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3667 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3668 /// <0, 0, 1, 1>
3669 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3670                                   bool HasAVX2) {
3671   unsigned NumElts = VT.getVectorNumElements();
3672
3673   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3674          "Unsupported vector type for unpckh");
3675
3676   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3677       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3678     return false;
3679
3680   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3681   // FIXME: Need a better way to get rid of this, there's no latency difference
3682   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3683   // the former later. We should also remove the "_undef" special mask.
3684   if (NumElts == 4 && VT.getSizeInBits() == 256)
3685     return false;
3686
3687   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3688   // independently on 128-bit lanes.
3689   unsigned NumLanes = VT.getSizeInBits()/128;
3690   unsigned NumLaneElts = NumElts/NumLanes;
3691
3692   for (unsigned l = 0; l != NumLanes; ++l) {
3693     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3694          i != (l+1)*NumLaneElts;
3695          i += 2, ++j) {
3696       int BitI  = Mask[i];
3697       int BitI1 = Mask[i+1];
3698
3699       if (!isUndefOrEqual(BitI, j))
3700         return false;
3701       if (!isUndefOrEqual(BitI1, j))
3702         return false;
3703     }
3704   }
3705
3706   return true;
3707 }
3708
3709 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3710 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3711 /// <2, 2, 3, 3>
3712 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3713   unsigned NumElts = VT.getVectorNumElements();
3714
3715   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3716          "Unsupported vector type for unpckh");
3717
3718   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3719       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3720     return false;
3721
3722   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3723   // independently on 128-bit lanes.
3724   unsigned NumLanes = VT.getSizeInBits()/128;
3725   unsigned NumLaneElts = NumElts/NumLanes;
3726
3727   for (unsigned l = 0; l != NumLanes; ++l) {
3728     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3729          i != (l+1)*NumLaneElts; i += 2, ++j) {
3730       int BitI  = Mask[i];
3731       int BitI1 = Mask[i+1];
3732       if (!isUndefOrEqual(BitI, j))
3733         return false;
3734       if (!isUndefOrEqual(BitI1, j))
3735         return false;
3736     }
3737   }
3738   return true;
3739 }
3740
3741 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3742 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3743 /// MOVSD, and MOVD, i.e. setting the lowest element.
3744 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3745   if (VT.getVectorElementType().getSizeInBits() < 32)
3746     return false;
3747   if (!VT.is128BitVector())
3748     return false;
3749
3750   unsigned NumElts = VT.getVectorNumElements();
3751
3752   if (!isUndefOrEqual(Mask[0], NumElts))
3753     return false;
3754
3755   for (unsigned i = 1; i != NumElts; ++i)
3756     if (!isUndefOrEqual(Mask[i], i))
3757       return false;
3758
3759   return true;
3760 }
3761
3762 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3763 /// as permutations between 128-bit chunks or halves. As an example: this
3764 /// shuffle bellow:
3765 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3766 /// The first half comes from the second half of V1 and the second half from the
3767 /// the second half of V2.
3768 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3769   if (!HasAVX || !VT.is256BitVector())
3770     return false;
3771
3772   // The shuffle result is divided into half A and half B. In total the two
3773   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3774   // B must come from C, D, E or F.
3775   unsigned HalfSize = VT.getVectorNumElements()/2;
3776   bool MatchA = false, MatchB = false;
3777
3778   // Check if A comes from one of C, D, E, F.
3779   for (unsigned Half = 0; Half != 4; ++Half) {
3780     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3781       MatchA = true;
3782       break;
3783     }
3784   }
3785
3786   // Check if B comes from one of C, D, E, F.
3787   for (unsigned Half = 0; Half != 4; ++Half) {
3788     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3789       MatchB = true;
3790       break;
3791     }
3792   }
3793
3794   return MatchA && MatchB;
3795 }
3796
3797 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3798 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3799 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3800   EVT VT = SVOp->getValueType(0);
3801
3802   unsigned HalfSize = VT.getVectorNumElements()/2;
3803
3804   unsigned FstHalf = 0, SndHalf = 0;
3805   for (unsigned i = 0; i < HalfSize; ++i) {
3806     if (SVOp->getMaskElt(i) > 0) {
3807       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3808       break;
3809     }
3810   }
3811   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3812     if (SVOp->getMaskElt(i) > 0) {
3813       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3814       break;
3815     }
3816   }
3817
3818   return (FstHalf | (SndHalf << 4));
3819 }
3820
3821 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3822 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3823 /// Note that VPERMIL mask matching is different depending whether theunderlying
3824 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3825 /// to the same elements of the low, but to the higher half of the source.
3826 /// In VPERMILPD the two lanes could be shuffled independently of each other
3827 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3828 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3829   if (!HasAVX)
3830     return false;
3831
3832   unsigned NumElts = VT.getVectorNumElements();
3833   // Only match 256-bit with 32/64-bit types
3834   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3835     return false;
3836
3837   unsigned NumLanes = VT.getSizeInBits()/128;
3838   unsigned LaneSize = NumElts/NumLanes;
3839   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3840     for (unsigned i = 0; i != LaneSize; ++i) {
3841       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3842         return false;
3843       if (NumElts != 8 || l == 0)
3844         continue;
3845       // VPERMILPS handling
3846       if (Mask[i] < 0)
3847         continue;
3848       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3849         return false;
3850     }
3851   }
3852
3853   return true;
3854 }
3855
3856 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3857 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3858 /// element of vector 2 and the other elements to come from vector 1 in order.
3859 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3860                                bool V2IsSplat = false, bool V2IsUndef = false) {
3861   if (!VT.is128BitVector())
3862     return false;
3863
3864   unsigned NumOps = VT.getVectorNumElements();
3865   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3866     return false;
3867
3868   if (!isUndefOrEqual(Mask[0], 0))
3869     return false;
3870
3871   for (unsigned i = 1; i != NumOps; ++i)
3872     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3873           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3874           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3875       return false;
3876
3877   return true;
3878 }
3879
3880 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3881 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3882 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3883 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3884                            const X86Subtarget *Subtarget) {
3885   if (!Subtarget->hasSSE3())
3886     return false;
3887
3888   unsigned NumElems = VT.getVectorNumElements();
3889
3890   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3891       (VT.getSizeInBits() == 256 && NumElems != 8))
3892     return false;
3893
3894   // "i+1" is the value the indexed mask element must have
3895   for (unsigned i = 0; i != NumElems; i += 2)
3896     if (!isUndefOrEqual(Mask[i], i+1) ||
3897         !isUndefOrEqual(Mask[i+1], i+1))
3898       return false;
3899
3900   return true;
3901 }
3902
3903 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3904 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3905 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3906 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3907                            const X86Subtarget *Subtarget) {
3908   if (!Subtarget->hasSSE3())
3909     return false;
3910
3911   unsigned NumElems = VT.getVectorNumElements();
3912
3913   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3914       (VT.getSizeInBits() == 256 && NumElems != 8))
3915     return false;
3916
3917   // "i" is the value the indexed mask element must have
3918   for (unsigned i = 0; i != NumElems; i += 2)
3919     if (!isUndefOrEqual(Mask[i], i) ||
3920         !isUndefOrEqual(Mask[i+1], i))
3921       return false;
3922
3923   return true;
3924 }
3925
3926 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3927 /// specifies a shuffle of elements that is suitable for input to 256-bit
3928 /// version of MOVDDUP.
3929 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3930   if (!HasAVX || !VT.is256BitVector())
3931     return false;
3932
3933   unsigned NumElts = VT.getVectorNumElements();
3934   if (NumElts != 4)
3935     return false;
3936
3937   for (unsigned i = 0; i != NumElts/2; ++i)
3938     if (!isUndefOrEqual(Mask[i], 0))
3939       return false;
3940   for (unsigned i = NumElts/2; i != NumElts; ++i)
3941     if (!isUndefOrEqual(Mask[i], NumElts/2))
3942       return false;
3943   return true;
3944 }
3945
3946 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3947 /// specifies a shuffle of elements that is suitable for input to 128-bit
3948 /// version of MOVDDUP.
3949 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3950   if (!VT.is128BitVector())
3951     return false;
3952
3953   unsigned e = VT.getVectorNumElements() / 2;
3954   for (unsigned i = 0; i != e; ++i)
3955     if (!isUndefOrEqual(Mask[i], i))
3956       return false;
3957   for (unsigned i = 0; i != e; ++i)
3958     if (!isUndefOrEqual(Mask[e+i], i))
3959       return false;
3960   return true;
3961 }
3962
3963 /// isVEXTRACTF128Index - Return true if the specified
3964 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3965 /// suitable for input to VEXTRACTF128.
3966 bool X86::isVEXTRACTF128Index(SDNode *N) {
3967   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3968     return false;
3969
3970   // The index should be aligned on a 128-bit boundary.
3971   uint64_t Index =
3972     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3973
3974   unsigned VL = N->getValueType(0).getVectorNumElements();
3975   unsigned VBits = N->getValueType(0).getSizeInBits();
3976   unsigned ElSize = VBits / VL;
3977   bool Result = (Index * ElSize) % 128 == 0;
3978
3979   return Result;
3980 }
3981
3982 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3983 /// operand specifies a subvector insert that is suitable for input to
3984 /// VINSERTF128.
3985 bool X86::isVINSERTF128Index(SDNode *N) {
3986   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3987     return false;
3988
3989   // The index should be aligned on a 128-bit boundary.
3990   uint64_t Index =
3991     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3992
3993   unsigned VL = N->getValueType(0).getVectorNumElements();
3994   unsigned VBits = N->getValueType(0).getSizeInBits();
3995   unsigned ElSize = VBits / VL;
3996   bool Result = (Index * ElSize) % 128 == 0;
3997
3998   return Result;
3999 }
4000
4001 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4002 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4003 /// Handles 128-bit and 256-bit.
4004 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4005   EVT VT = N->getValueType(0);
4006
4007   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4008          "Unsupported vector type for PSHUF/SHUFP");
4009
4010   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4011   // independently on 128-bit lanes.
4012   unsigned NumElts = VT.getVectorNumElements();
4013   unsigned NumLanes = VT.getSizeInBits()/128;
4014   unsigned NumLaneElts = NumElts/NumLanes;
4015
4016   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4017          "Only supports 2 or 4 elements per lane");
4018
4019   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4020   unsigned Mask = 0;
4021   for (unsigned i = 0; i != NumElts; ++i) {
4022     int Elt = N->getMaskElt(i);
4023     if (Elt < 0) continue;
4024     Elt &= NumLaneElts - 1;
4025     unsigned ShAmt = (i << Shift) % 8;
4026     Mask |= Elt << ShAmt;
4027   }
4028
4029   return Mask;
4030 }
4031
4032 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4033 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4034 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4035   EVT VT = N->getValueType(0);
4036
4037   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4038          "Unsupported vector type for PSHUFHW");
4039
4040   unsigned NumElts = VT.getVectorNumElements();
4041
4042   unsigned Mask = 0;
4043   for (unsigned l = 0; l != NumElts; l += 8) {
4044     // 8 nodes per lane, but we only care about the last 4.
4045     for (unsigned i = 0; i < 4; ++i) {
4046       int Elt = N->getMaskElt(l+i+4);
4047       if (Elt < 0) continue;
4048       Elt &= 0x3; // only 2-bits.
4049       Mask |= Elt << (i * 2);
4050     }
4051   }
4052
4053   return Mask;
4054 }
4055
4056 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4057 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4058 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4059   EVT VT = N->getValueType(0);
4060
4061   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4062          "Unsupported vector type for PSHUFHW");
4063
4064   unsigned NumElts = VT.getVectorNumElements();
4065
4066   unsigned Mask = 0;
4067   for (unsigned l = 0; l != NumElts; l += 8) {
4068     // 8 nodes per lane, but we only care about the first 4.
4069     for (unsigned i = 0; i < 4; ++i) {
4070       int Elt = N->getMaskElt(l+i);
4071       if (Elt < 0) continue;
4072       Elt &= 0x3; // only 2-bits
4073       Mask |= Elt << (i * 2);
4074     }
4075   }
4076
4077   return Mask;
4078 }
4079
4080 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4081 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4082 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4083   EVT VT = SVOp->getValueType(0);
4084   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4085
4086   unsigned NumElts = VT.getVectorNumElements();
4087   unsigned NumLanes = VT.getSizeInBits()/128;
4088   unsigned NumLaneElts = NumElts/NumLanes;
4089
4090   int Val = 0;
4091   unsigned i;
4092   for (i = 0; i != NumElts; ++i) {
4093     Val = SVOp->getMaskElt(i);
4094     if (Val >= 0)
4095       break;
4096   }
4097   if (Val >= (int)NumElts)
4098     Val -= NumElts - NumLaneElts;
4099
4100   assert(Val - i > 0 && "PALIGNR imm should be positive");
4101   return (Val - i) * EltSize;
4102 }
4103
4104 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4105 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4106 /// instructions.
4107 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4108   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4109     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4110
4111   uint64_t Index =
4112     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4113
4114   EVT VecVT = N->getOperand(0).getValueType();
4115   EVT ElVT = VecVT.getVectorElementType();
4116
4117   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4118   return Index / NumElemsPerChunk;
4119 }
4120
4121 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4122 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4123 /// instructions.
4124 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4125   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4126     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4127
4128   uint64_t Index =
4129     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4130
4131   EVT VecVT = N->getValueType(0);
4132   EVT ElVT = VecVT.getVectorElementType();
4133
4134   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4135   return Index / NumElemsPerChunk;
4136 }
4137
4138 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4139 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4140 /// Handles 256-bit.
4141 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4142   EVT VT = N->getValueType(0);
4143
4144   unsigned NumElts = VT.getVectorNumElements();
4145
4146   assert((VT.is256BitVector() && NumElts == 4) &&
4147          "Unsupported vector type for VPERMQ/VPERMPD");
4148
4149   unsigned Mask = 0;
4150   for (unsigned i = 0; i != NumElts; ++i) {
4151     int Elt = N->getMaskElt(i);
4152     if (Elt < 0)
4153       continue;
4154     Mask |= Elt << (i*2);
4155   }
4156
4157   return Mask;
4158 }
4159 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4160 /// constant +0.0.
4161 bool X86::isZeroNode(SDValue Elt) {
4162   return ((isa<ConstantSDNode>(Elt) &&
4163            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4164           (isa<ConstantFPSDNode>(Elt) &&
4165            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4166 }
4167
4168 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4169 /// their permute mask.
4170 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4171                                     SelectionDAG &DAG) {
4172   EVT VT = SVOp->getValueType(0);
4173   unsigned NumElems = VT.getVectorNumElements();
4174   SmallVector<int, 8> MaskVec;
4175
4176   for (unsigned i = 0; i != NumElems; ++i) {
4177     int Idx = SVOp->getMaskElt(i);
4178     if (Idx >= 0) {
4179       if (Idx < (int)NumElems)
4180         Idx += NumElems;
4181       else
4182         Idx -= NumElems;
4183     }
4184     MaskVec.push_back(Idx);
4185   }
4186   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4187                               SVOp->getOperand(0), &MaskVec[0]);
4188 }
4189
4190 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4191 /// match movhlps. The lower half elements should come from upper half of
4192 /// V1 (and in order), and the upper half elements should come from the upper
4193 /// half of V2 (and in order).
4194 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4195   if (!VT.is128BitVector())
4196     return false;
4197   if (VT.getVectorNumElements() != 4)
4198     return false;
4199   for (unsigned i = 0, e = 2; i != e; ++i)
4200     if (!isUndefOrEqual(Mask[i], i+2))
4201       return false;
4202   for (unsigned i = 2; i != 4; ++i)
4203     if (!isUndefOrEqual(Mask[i], i+4))
4204       return false;
4205   return true;
4206 }
4207
4208 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4209 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4210 /// required.
4211 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4212   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4213     return false;
4214   N = N->getOperand(0).getNode();
4215   if (!ISD::isNON_EXTLoad(N))
4216     return false;
4217   if (LD)
4218     *LD = cast<LoadSDNode>(N);
4219   return true;
4220 }
4221
4222 // Test whether the given value is a vector value which will be legalized
4223 // into a load.
4224 static bool WillBeConstantPoolLoad(SDNode *N) {
4225   if (N->getOpcode() != ISD::BUILD_VECTOR)
4226     return false;
4227
4228   // Check for any non-constant elements.
4229   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4230     switch (N->getOperand(i).getNode()->getOpcode()) {
4231     case ISD::UNDEF:
4232     case ISD::ConstantFP:
4233     case ISD::Constant:
4234       break;
4235     default:
4236       return false;
4237     }
4238
4239   // Vectors of all-zeros and all-ones are materialized with special
4240   // instructions rather than being loaded.
4241   return !ISD::isBuildVectorAllZeros(N) &&
4242          !ISD::isBuildVectorAllOnes(N);
4243 }
4244
4245 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4246 /// match movlp{s|d}. The lower half elements should come from lower half of
4247 /// V1 (and in order), and the upper half elements should come from the upper
4248 /// half of V2 (and in order). And since V1 will become the source of the
4249 /// MOVLP, it must be either a vector load or a scalar load to vector.
4250 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4251                                ArrayRef<int> Mask, EVT VT) {
4252   if (!VT.is128BitVector())
4253     return false;
4254
4255   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4256     return false;
4257   // Is V2 is a vector load, don't do this transformation. We will try to use
4258   // load folding shufps op.
4259   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4260     return false;
4261
4262   unsigned NumElems = VT.getVectorNumElements();
4263
4264   if (NumElems != 2 && NumElems != 4)
4265     return false;
4266   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4267     if (!isUndefOrEqual(Mask[i], i))
4268       return false;
4269   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4270     if (!isUndefOrEqual(Mask[i], i+NumElems))
4271       return false;
4272   return true;
4273 }
4274
4275 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4276 /// all the same.
4277 static bool isSplatVector(SDNode *N) {
4278   if (N->getOpcode() != ISD::BUILD_VECTOR)
4279     return false;
4280
4281   SDValue SplatValue = N->getOperand(0);
4282   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4283     if (N->getOperand(i) != SplatValue)
4284       return false;
4285   return true;
4286 }
4287
4288 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4289 /// to an zero vector.
4290 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4291 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4292   SDValue V1 = N->getOperand(0);
4293   SDValue V2 = N->getOperand(1);
4294   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4295   for (unsigned i = 0; i != NumElems; ++i) {
4296     int Idx = N->getMaskElt(i);
4297     if (Idx >= (int)NumElems) {
4298       unsigned Opc = V2.getOpcode();
4299       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4300         continue;
4301       if (Opc != ISD::BUILD_VECTOR ||
4302           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4303         return false;
4304     } else if (Idx >= 0) {
4305       unsigned Opc = V1.getOpcode();
4306       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4307         continue;
4308       if (Opc != ISD::BUILD_VECTOR ||
4309           !X86::isZeroNode(V1.getOperand(Idx)))
4310         return false;
4311     }
4312   }
4313   return true;
4314 }
4315
4316 /// getZeroVector - Returns a vector of specified type with all zero elements.
4317 ///
4318 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4319                              SelectionDAG &DAG, DebugLoc dl) {
4320   assert(VT.isVector() && "Expected a vector type");
4321   unsigned Size = VT.getSizeInBits();
4322
4323   // Always build SSE zero vectors as <4 x i32> bitcasted
4324   // to their dest type. This ensures they get CSE'd.
4325   SDValue Vec;
4326   if (Size == 128) {  // SSE
4327     if (Subtarget->hasSSE2()) {  // SSE2
4328       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4329       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4330     } else { // SSE1
4331       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4332       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4333     }
4334   } else if (Size == 256) { // AVX
4335     if (Subtarget->hasAVX2()) { // AVX2
4336       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4337       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4338       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4339     } else {
4340       // 256-bit logic and arithmetic instructions in AVX are all
4341       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4342       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4343       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4344       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4345     }
4346   } else
4347     llvm_unreachable("Unexpected vector type");
4348
4349   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4350 }
4351
4352 /// getOnesVector - Returns a vector of specified type with all bits set.
4353 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4354 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4355 /// Then bitcast to their original type, ensuring they get CSE'd.
4356 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4357                              DebugLoc dl) {
4358   assert(VT.isVector() && "Expected a vector type");
4359   unsigned Size = VT.getSizeInBits();
4360
4361   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4362   SDValue Vec;
4363   if (Size == 256) {
4364     if (HasAVX2) { // AVX2
4365       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4366       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4367     } else { // AVX
4368       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4369       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4370     }
4371   } else if (Size == 128) {
4372     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4373   } else
4374     llvm_unreachable("Unexpected vector type");
4375
4376   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4377 }
4378
4379 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4380 /// that point to V2 points to its first element.
4381 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4382   for (unsigned i = 0; i != NumElems; ++i) {
4383     if (Mask[i] > (int)NumElems) {
4384       Mask[i] = NumElems;
4385     }
4386   }
4387 }
4388
4389 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4390 /// operation of specified width.
4391 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4392                        SDValue V2) {
4393   unsigned NumElems = VT.getVectorNumElements();
4394   SmallVector<int, 8> Mask;
4395   Mask.push_back(NumElems);
4396   for (unsigned i = 1; i != NumElems; ++i)
4397     Mask.push_back(i);
4398   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4399 }
4400
4401 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4402 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4403                           SDValue V2) {
4404   unsigned NumElems = VT.getVectorNumElements();
4405   SmallVector<int, 8> Mask;
4406   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4407     Mask.push_back(i);
4408     Mask.push_back(i + NumElems);
4409   }
4410   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4411 }
4412
4413 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4414 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4415                           SDValue V2) {
4416   unsigned NumElems = VT.getVectorNumElements();
4417   SmallVector<int, 8> Mask;
4418   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4419     Mask.push_back(i + Half);
4420     Mask.push_back(i + NumElems + Half);
4421   }
4422   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4423 }
4424
4425 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4426 // a generic shuffle instruction because the target has no such instructions.
4427 // Generate shuffles which repeat i16 and i8 several times until they can be
4428 // represented by v4f32 and then be manipulated by target suported shuffles.
4429 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4430   EVT VT = V.getValueType();
4431   int NumElems = VT.getVectorNumElements();
4432   DebugLoc dl = V.getDebugLoc();
4433
4434   while (NumElems > 4) {
4435     if (EltNo < NumElems/2) {
4436       V = getUnpackl(DAG, dl, VT, V, V);
4437     } else {
4438       V = getUnpackh(DAG, dl, VT, V, V);
4439       EltNo -= NumElems/2;
4440     }
4441     NumElems >>= 1;
4442   }
4443   return V;
4444 }
4445
4446 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4447 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4448   EVT VT = V.getValueType();
4449   DebugLoc dl = V.getDebugLoc();
4450   unsigned Size = VT.getSizeInBits();
4451
4452   if (Size == 128) {
4453     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4454     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4455     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4456                              &SplatMask[0]);
4457   } else if (Size == 256) {
4458     // To use VPERMILPS to splat scalars, the second half of indicies must
4459     // refer to the higher part, which is a duplication of the lower one,
4460     // because VPERMILPS can only handle in-lane permutations.
4461     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4462                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4463
4464     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4465     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4466                              &SplatMask[0]);
4467   } else
4468     llvm_unreachable("Vector size not supported");
4469
4470   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4471 }
4472
4473 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4474 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4475   EVT SrcVT = SV->getValueType(0);
4476   SDValue V1 = SV->getOperand(0);
4477   DebugLoc dl = SV->getDebugLoc();
4478
4479   int EltNo = SV->getSplatIndex();
4480   int NumElems = SrcVT.getVectorNumElements();
4481   unsigned Size = SrcVT.getSizeInBits();
4482
4483   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4484           "Unknown how to promote splat for type");
4485
4486   // Extract the 128-bit part containing the splat element and update
4487   // the splat element index when it refers to the higher register.
4488   if (Size == 256) {
4489     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4490     if (EltNo >= NumElems/2)
4491       EltNo -= NumElems/2;
4492   }
4493
4494   // All i16 and i8 vector types can't be used directly by a generic shuffle
4495   // instruction because the target has no such instruction. Generate shuffles
4496   // which repeat i16 and i8 several times until they fit in i32, and then can
4497   // be manipulated by target suported shuffles.
4498   EVT EltVT = SrcVT.getVectorElementType();
4499   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4500     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4501
4502   // Recreate the 256-bit vector and place the same 128-bit vector
4503   // into the low and high part. This is necessary because we want
4504   // to use VPERM* to shuffle the vectors
4505   if (Size == 256) {
4506     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4507   }
4508
4509   return getLegalSplat(DAG, V1, EltNo);
4510 }
4511
4512 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4513 /// vector of zero or undef vector.  This produces a shuffle where the low
4514 /// element of V2 is swizzled into the zero/undef vector, landing at element
4515 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4516 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4517                                            bool IsZero,
4518                                            const X86Subtarget *Subtarget,
4519                                            SelectionDAG &DAG) {
4520   EVT VT = V2.getValueType();
4521   SDValue V1 = IsZero
4522     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4523   unsigned NumElems = VT.getVectorNumElements();
4524   SmallVector<int, 16> MaskVec;
4525   for (unsigned i = 0; i != NumElems; ++i)
4526     // If this is the insertion idx, put the low elt of V2 here.
4527     MaskVec.push_back(i == Idx ? NumElems : i);
4528   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4529 }
4530
4531 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4532 /// target specific opcode. Returns true if the Mask could be calculated.
4533 /// Sets IsUnary to true if only uses one source.
4534 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4535                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4536   unsigned NumElems = VT.getVectorNumElements();
4537   SDValue ImmN;
4538
4539   IsUnary = false;
4540   switch(N->getOpcode()) {
4541   case X86ISD::SHUFP:
4542     ImmN = N->getOperand(N->getNumOperands()-1);
4543     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4544     break;
4545   case X86ISD::UNPCKH:
4546     DecodeUNPCKHMask(VT, Mask);
4547     break;
4548   case X86ISD::UNPCKL:
4549     DecodeUNPCKLMask(VT, Mask);
4550     break;
4551   case X86ISD::MOVHLPS:
4552     DecodeMOVHLPSMask(NumElems, Mask);
4553     break;
4554   case X86ISD::MOVLHPS:
4555     DecodeMOVLHPSMask(NumElems, Mask);
4556     break;
4557   case X86ISD::PSHUFD:
4558   case X86ISD::VPERMILP:
4559     ImmN = N->getOperand(N->getNumOperands()-1);
4560     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4561     IsUnary = true;
4562     break;
4563   case X86ISD::PSHUFHW:
4564     ImmN = N->getOperand(N->getNumOperands()-1);
4565     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4566     IsUnary = true;
4567     break;
4568   case X86ISD::PSHUFLW:
4569     ImmN = N->getOperand(N->getNumOperands()-1);
4570     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4571     IsUnary = true;
4572     break;
4573   case X86ISD::VPERMI:
4574     ImmN = N->getOperand(N->getNumOperands()-1);
4575     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4576     IsUnary = true;
4577     break;
4578   case X86ISD::MOVSS:
4579   case X86ISD::MOVSD: {
4580     // The index 0 always comes from the first element of the second source,
4581     // this is why MOVSS and MOVSD are used in the first place. The other
4582     // elements come from the other positions of the first source vector
4583     Mask.push_back(NumElems);
4584     for (unsigned i = 1; i != NumElems; ++i) {
4585       Mask.push_back(i);
4586     }
4587     break;
4588   }
4589   case X86ISD::VPERM2X128:
4590     ImmN = N->getOperand(N->getNumOperands()-1);
4591     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4592     if (Mask.empty()) return false;
4593     break;
4594   case X86ISD::MOVDDUP:
4595   case X86ISD::MOVLHPD:
4596   case X86ISD::MOVLPD:
4597   case X86ISD::MOVLPS:
4598   case X86ISD::MOVSHDUP:
4599   case X86ISD::MOVSLDUP:
4600   case X86ISD::PALIGN:
4601     // Not yet implemented
4602     return false;
4603   default: llvm_unreachable("unknown target shuffle node");
4604   }
4605
4606   return true;
4607 }
4608
4609 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4610 /// element of the result of the vector shuffle.
4611 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4612                                    unsigned Depth) {
4613   if (Depth == 6)
4614     return SDValue();  // Limit search depth.
4615
4616   SDValue V = SDValue(N, 0);
4617   EVT VT = V.getValueType();
4618   unsigned Opcode = V.getOpcode();
4619
4620   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4621   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4622     int Elt = SV->getMaskElt(Index);
4623
4624     if (Elt < 0)
4625       return DAG.getUNDEF(VT.getVectorElementType());
4626
4627     unsigned NumElems = VT.getVectorNumElements();
4628     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4629                                          : SV->getOperand(1);
4630     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4631   }
4632
4633   // Recurse into target specific vector shuffles to find scalars.
4634   if (isTargetShuffle(Opcode)) {
4635     MVT ShufVT = V.getValueType().getSimpleVT();
4636     unsigned NumElems = ShufVT.getVectorNumElements();
4637     SmallVector<int, 16> ShuffleMask;
4638     SDValue ImmN;
4639     bool IsUnary;
4640
4641     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4642       return SDValue();
4643
4644     int Elt = ShuffleMask[Index];
4645     if (Elt < 0)
4646       return DAG.getUNDEF(ShufVT.getVectorElementType());
4647
4648     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4649                                          : N->getOperand(1);
4650     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4651                                Depth+1);
4652   }
4653
4654   // Actual nodes that may contain scalar elements
4655   if (Opcode == ISD::BITCAST) {
4656     V = V.getOperand(0);
4657     EVT SrcVT = V.getValueType();
4658     unsigned NumElems = VT.getVectorNumElements();
4659
4660     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4661       return SDValue();
4662   }
4663
4664   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4665     return (Index == 0) ? V.getOperand(0)
4666                         : DAG.getUNDEF(VT.getVectorElementType());
4667
4668   if (V.getOpcode() == ISD::BUILD_VECTOR)
4669     return V.getOperand(Index);
4670
4671   return SDValue();
4672 }
4673
4674 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4675 /// shuffle operation which come from a consecutively from a zero. The
4676 /// search can start in two different directions, from left or right.
4677 static
4678 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4679                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4680   unsigned i;
4681   for (i = 0; i != NumElems; ++i) {
4682     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4683     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4684     if (!(Elt.getNode() &&
4685          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4686       break;
4687   }
4688
4689   return i;
4690 }
4691
4692 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4693 /// correspond consecutively to elements from one of the vector operands,
4694 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4695 static
4696 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4697                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4698                               unsigned NumElems, unsigned &OpNum) {
4699   bool SeenV1 = false;
4700   bool SeenV2 = false;
4701
4702   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4703     int Idx = SVOp->getMaskElt(i);
4704     // Ignore undef indicies
4705     if (Idx < 0)
4706       continue;
4707
4708     if (Idx < (int)NumElems)
4709       SeenV1 = true;
4710     else
4711       SeenV2 = true;
4712
4713     // Only accept consecutive elements from the same vector
4714     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4715       return false;
4716   }
4717
4718   OpNum = SeenV1 ? 0 : 1;
4719   return true;
4720 }
4721
4722 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4723 /// logical left shift of a vector.
4724 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4725                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4726   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4727   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4728               false /* check zeros from right */, DAG);
4729   unsigned OpSrc;
4730
4731   if (!NumZeros)
4732     return false;
4733
4734   // Considering the elements in the mask that are not consecutive zeros,
4735   // check if they consecutively come from only one of the source vectors.
4736   //
4737   //               V1 = {X, A, B, C}     0
4738   //                         \  \  \    /
4739   //   vector_shuffle V1, V2 <1, 2, 3, X>
4740   //
4741   if (!isShuffleMaskConsecutive(SVOp,
4742             0,                   // Mask Start Index
4743             NumElems-NumZeros,   // Mask End Index(exclusive)
4744             NumZeros,            // Where to start looking in the src vector
4745             NumElems,            // Number of elements in vector
4746             OpSrc))              // Which source operand ?
4747     return false;
4748
4749   isLeft = false;
4750   ShAmt = NumZeros;
4751   ShVal = SVOp->getOperand(OpSrc);
4752   return true;
4753 }
4754
4755 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4756 /// logical left shift of a vector.
4757 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4758                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4759   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4760   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4761               true /* check zeros from left */, DAG);
4762   unsigned OpSrc;
4763
4764   if (!NumZeros)
4765     return false;
4766
4767   // Considering the elements in the mask that are not consecutive zeros,
4768   // check if they consecutively come from only one of the source vectors.
4769   //
4770   //                           0    { A, B, X, X } = V2
4771   //                          / \    /  /
4772   //   vector_shuffle V1, V2 <X, X, 4, 5>
4773   //
4774   if (!isShuffleMaskConsecutive(SVOp,
4775             NumZeros,     // Mask Start Index
4776             NumElems,     // Mask End Index(exclusive)
4777             0,            // Where to start looking in the src vector
4778             NumElems,     // Number of elements in vector
4779             OpSrc))       // Which source operand ?
4780     return false;
4781
4782   isLeft = true;
4783   ShAmt = NumZeros;
4784   ShVal = SVOp->getOperand(OpSrc);
4785   return true;
4786 }
4787
4788 /// isVectorShift - Returns true if the shuffle can be implemented as a
4789 /// logical left or right shift of a vector.
4790 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4791                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4792   // Although the logic below support any bitwidth size, there are no
4793   // shift instructions which handle more than 128-bit vectors.
4794   if (!SVOp->getValueType(0).is128BitVector())
4795     return false;
4796
4797   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4798       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4799     return true;
4800
4801   return false;
4802 }
4803
4804 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4805 ///
4806 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4807                                        unsigned NumNonZero, unsigned NumZero,
4808                                        SelectionDAG &DAG,
4809                                        const X86Subtarget* Subtarget,
4810                                        const TargetLowering &TLI) {
4811   if (NumNonZero > 8)
4812     return SDValue();
4813
4814   DebugLoc dl = Op.getDebugLoc();
4815   SDValue V(0, 0);
4816   bool First = true;
4817   for (unsigned i = 0; i < 16; ++i) {
4818     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4819     if (ThisIsNonZero && First) {
4820       if (NumZero)
4821         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4822       else
4823         V = DAG.getUNDEF(MVT::v8i16);
4824       First = false;
4825     }
4826
4827     if ((i & 1) != 0) {
4828       SDValue ThisElt(0, 0), LastElt(0, 0);
4829       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4830       if (LastIsNonZero) {
4831         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4832                               MVT::i16, Op.getOperand(i-1));
4833       }
4834       if (ThisIsNonZero) {
4835         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4836         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4837                               ThisElt, DAG.getConstant(8, MVT::i8));
4838         if (LastIsNonZero)
4839           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4840       } else
4841         ThisElt = LastElt;
4842
4843       if (ThisElt.getNode())
4844         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4845                         DAG.getIntPtrConstant(i/2));
4846     }
4847   }
4848
4849   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4850 }
4851
4852 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4853 ///
4854 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4855                                      unsigned NumNonZero, unsigned NumZero,
4856                                      SelectionDAG &DAG,
4857                                      const X86Subtarget* Subtarget,
4858                                      const TargetLowering &TLI) {
4859   if (NumNonZero > 4)
4860     return SDValue();
4861
4862   DebugLoc dl = Op.getDebugLoc();
4863   SDValue V(0, 0);
4864   bool First = true;
4865   for (unsigned i = 0; i < 8; ++i) {
4866     bool isNonZero = (NonZeros & (1 << i)) != 0;
4867     if (isNonZero) {
4868       if (First) {
4869         if (NumZero)
4870           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4871         else
4872           V = DAG.getUNDEF(MVT::v8i16);
4873         First = false;
4874       }
4875       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4876                       MVT::v8i16, V, Op.getOperand(i),
4877                       DAG.getIntPtrConstant(i));
4878     }
4879   }
4880
4881   return V;
4882 }
4883
4884 /// getVShift - Return a vector logical shift node.
4885 ///
4886 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4887                          unsigned NumBits, SelectionDAG &DAG,
4888                          const TargetLowering &TLI, DebugLoc dl) {
4889   assert(VT.is128BitVector() && "Unknown type for VShift");
4890   EVT ShVT = MVT::v2i64;
4891   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4892   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4893   return DAG.getNode(ISD::BITCAST, dl, VT,
4894                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4895                              DAG.getConstant(NumBits,
4896                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4897 }
4898
4899 SDValue
4900 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4901                                           SelectionDAG &DAG) const {
4902
4903   // Check if the scalar load can be widened into a vector load. And if
4904   // the address is "base + cst" see if the cst can be "absorbed" into
4905   // the shuffle mask.
4906   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4907     SDValue Ptr = LD->getBasePtr();
4908     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4909       return SDValue();
4910     EVT PVT = LD->getValueType(0);
4911     if (PVT != MVT::i32 && PVT != MVT::f32)
4912       return SDValue();
4913
4914     int FI = -1;
4915     int64_t Offset = 0;
4916     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4917       FI = FINode->getIndex();
4918       Offset = 0;
4919     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4920                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4921       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4922       Offset = Ptr.getConstantOperandVal(1);
4923       Ptr = Ptr.getOperand(0);
4924     } else {
4925       return SDValue();
4926     }
4927
4928     // FIXME: 256-bit vector instructions don't require a strict alignment,
4929     // improve this code to support it better.
4930     unsigned RequiredAlign = VT.getSizeInBits()/8;
4931     SDValue Chain = LD->getChain();
4932     // Make sure the stack object alignment is at least 16 or 32.
4933     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4934     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4935       if (MFI->isFixedObjectIndex(FI)) {
4936         // Can't change the alignment. FIXME: It's possible to compute
4937         // the exact stack offset and reference FI + adjust offset instead.
4938         // If someone *really* cares about this. That's the way to implement it.
4939         return SDValue();
4940       } else {
4941         MFI->setObjectAlignment(FI, RequiredAlign);
4942       }
4943     }
4944
4945     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4946     // Ptr + (Offset & ~15).
4947     if (Offset < 0)
4948       return SDValue();
4949     if ((Offset % RequiredAlign) & 3)
4950       return SDValue();
4951     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4952     if (StartOffset)
4953       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4954                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4955
4956     int EltNo = (Offset - StartOffset) >> 2;
4957     unsigned NumElems = VT.getVectorNumElements();
4958
4959     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4960     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4961                              LD->getPointerInfo().getWithOffset(StartOffset),
4962                              false, false, false, 0);
4963
4964     SmallVector<int, 8> Mask;
4965     for (unsigned i = 0; i != NumElems; ++i)
4966       Mask.push_back(EltNo);
4967
4968     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4969   }
4970
4971   return SDValue();
4972 }
4973
4974 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4975 /// vector of type 'VT', see if the elements can be replaced by a single large
4976 /// load which has the same value as a build_vector whose operands are 'elts'.
4977 ///
4978 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4979 ///
4980 /// FIXME: we'd also like to handle the case where the last elements are zero
4981 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4982 /// There's even a handy isZeroNode for that purpose.
4983 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4984                                         DebugLoc &DL, SelectionDAG &DAG) {
4985   EVT EltVT = VT.getVectorElementType();
4986   unsigned NumElems = Elts.size();
4987
4988   LoadSDNode *LDBase = NULL;
4989   unsigned LastLoadedElt = -1U;
4990
4991   // For each element in the initializer, see if we've found a load or an undef.
4992   // If we don't find an initial load element, or later load elements are
4993   // non-consecutive, bail out.
4994   for (unsigned i = 0; i < NumElems; ++i) {
4995     SDValue Elt = Elts[i];
4996
4997     if (!Elt.getNode() ||
4998         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4999       return SDValue();
5000     if (!LDBase) {
5001       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5002         return SDValue();
5003       LDBase = cast<LoadSDNode>(Elt.getNode());
5004       LastLoadedElt = i;
5005       continue;
5006     }
5007     if (Elt.getOpcode() == ISD::UNDEF)
5008       continue;
5009
5010     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5011     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5012       return SDValue();
5013     LastLoadedElt = i;
5014   }
5015
5016   // If we have found an entire vector of loads and undefs, then return a large
5017   // load of the entire vector width starting at the base pointer.  If we found
5018   // consecutive loads for the low half, generate a vzext_load node.
5019   if (LastLoadedElt == NumElems - 1) {
5020     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5021       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5022                          LDBase->getPointerInfo(),
5023                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5024                          LDBase->isInvariant(), 0);
5025     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5026                        LDBase->getPointerInfo(),
5027                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5028                        LDBase->isInvariant(), LDBase->getAlignment());
5029   }
5030   if (NumElems == 4 && LastLoadedElt == 1 &&
5031       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5032     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5033     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5034     SDValue ResNode =
5035         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5036                                 LDBase->getPointerInfo(),
5037                                 LDBase->getAlignment(),
5038                                 false/*isVolatile*/, true/*ReadMem*/,
5039                                 false/*WriteMem*/);
5040
5041     // Make sure the newly-created LOAD is in the same position as LDBase in
5042     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5043     // update uses of LDBase's output chain to use the TokenFactor.
5044     if (LDBase->hasAnyUseOfValue(1)) {
5045       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5046                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5047       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5048       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5049                              SDValue(ResNode.getNode(), 1));
5050     }
5051
5052     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5053   }
5054   return SDValue();
5055 }
5056
5057 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5058 /// to generate a splat value for the following cases:
5059 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5060 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5061 /// a scalar load, or a constant.
5062 /// The VBROADCAST node is returned when a pattern is found,
5063 /// or SDValue() otherwise.
5064 SDValue
5065 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5066   if (!Subtarget->hasAVX())
5067     return SDValue();
5068
5069   EVT VT = Op.getValueType();
5070   DebugLoc dl = Op.getDebugLoc();
5071
5072   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5073          "Unsupported vector type for broadcast.");
5074
5075   SDValue Ld;
5076   bool ConstSplatVal;
5077
5078   switch (Op.getOpcode()) {
5079     default:
5080       // Unknown pattern found.
5081       return SDValue();
5082
5083     case ISD::BUILD_VECTOR: {
5084       // The BUILD_VECTOR node must be a splat.
5085       if (!isSplatVector(Op.getNode()))
5086         return SDValue();
5087
5088       Ld = Op.getOperand(0);
5089       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5090                      Ld.getOpcode() == ISD::ConstantFP);
5091
5092       // The suspected load node has several users. Make sure that all
5093       // of its users are from the BUILD_VECTOR node.
5094       // Constants may have multiple users.
5095       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5096         return SDValue();
5097       break;
5098     }
5099
5100     case ISD::VECTOR_SHUFFLE: {
5101       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5102
5103       // Shuffles must have a splat mask where the first element is
5104       // broadcasted.
5105       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5106         return SDValue();
5107
5108       SDValue Sc = Op.getOperand(0);
5109       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5110           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5111
5112         if (!Subtarget->hasAVX2())
5113           return SDValue();
5114
5115         // Use the register form of the broadcast instruction available on AVX2.
5116         if (VT.is256BitVector())
5117           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5118         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5119       }
5120
5121       Ld = Sc.getOperand(0);
5122       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5123                        Ld.getOpcode() == ISD::ConstantFP);
5124
5125       // The scalar_to_vector node and the suspected
5126       // load node must have exactly one user.
5127       // Constants may have multiple users.
5128       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5129         return SDValue();
5130       break;
5131     }
5132   }
5133
5134   bool Is256 = VT.is256BitVector();
5135
5136   // Handle the broadcasting a single constant scalar from the constant pool
5137   // into a vector. On Sandybridge it is still better to load a constant vector
5138   // from the constant pool and not to broadcast it from a scalar.
5139   if (ConstSplatVal && Subtarget->hasAVX2()) {
5140     EVT CVT = Ld.getValueType();
5141     assert(!CVT.isVector() && "Must not broadcast a vector type");
5142     unsigned ScalarSize = CVT.getSizeInBits();
5143
5144     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5145       const Constant *C = 0;
5146       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5147         C = CI->getConstantIntValue();
5148       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5149         C = CF->getConstantFPValue();
5150
5151       assert(C && "Invalid constant type");
5152
5153       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5154       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5155       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5156                        MachinePointerInfo::getConstantPool(),
5157                        false, false, false, Alignment);
5158
5159       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5160     }
5161   }
5162
5163   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5164   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5165
5166   // Handle AVX2 in-register broadcasts.
5167   if (!IsLoad && Subtarget->hasAVX2() &&
5168       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5169     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5170
5171   // The scalar source must be a normal load.
5172   if (!IsLoad)
5173     return SDValue();
5174
5175   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5176     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5177
5178   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5179   // double since there is no vbroadcastsd xmm
5180   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5181     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5182       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5183   }
5184
5185   // Unsupported broadcast.
5186   return SDValue();
5187 }
5188
5189 SDValue
5190 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5191   EVT VT = Op.getValueType();
5192
5193   // Skip if insert_vec_elt is not supported.
5194   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5195     return SDValue();
5196
5197   DebugLoc DL = Op.getDebugLoc();
5198   unsigned NumElems = Op.getNumOperands();
5199
5200   SDValue VecIn1;
5201   SDValue VecIn2;
5202   SmallVector<unsigned, 4> InsertIndices;
5203   SmallVector<int, 8> Mask(NumElems, -1);
5204
5205   for (unsigned i = 0; i != NumElems; ++i) {
5206     unsigned Opc = Op.getOperand(i).getOpcode();
5207
5208     if (Opc == ISD::UNDEF)
5209       continue;
5210
5211     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5212       // Quit if more than 1 elements need inserting.
5213       if (InsertIndices.size() > 1)
5214         return SDValue();
5215
5216       InsertIndices.push_back(i);
5217       continue;
5218     }
5219
5220     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5221     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5222
5223     // Quit if extracted from vector of different type.
5224     if (ExtractedFromVec.getValueType() != VT)
5225       return SDValue();
5226
5227     // Quit if non-constant index.
5228     if (!isa<ConstantSDNode>(ExtIdx))
5229       return SDValue();
5230
5231     if (VecIn1.getNode() == 0)
5232       VecIn1 = ExtractedFromVec;
5233     else if (VecIn1 != ExtractedFromVec) {
5234       if (VecIn2.getNode() == 0)
5235         VecIn2 = ExtractedFromVec;
5236       else if (VecIn2 != ExtractedFromVec)
5237         // Quit if more than 2 vectors to shuffle
5238         return SDValue();
5239     }
5240
5241     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5242
5243     if (ExtractedFromVec == VecIn1)
5244       Mask[i] = Idx;
5245     else if (ExtractedFromVec == VecIn2)
5246       Mask[i] = Idx + NumElems;
5247   }
5248
5249   if (VecIn1.getNode() == 0)
5250     return SDValue();
5251
5252   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5253   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5254   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5255     unsigned Idx = InsertIndices[i];
5256     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5257                      DAG.getIntPtrConstant(Idx));
5258   }
5259
5260   return NV;
5261 }
5262
5263 SDValue
5264 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5265   DebugLoc dl = Op.getDebugLoc();
5266
5267   EVT VT = Op.getValueType();
5268   EVT ExtVT = VT.getVectorElementType();
5269   unsigned NumElems = Op.getNumOperands();
5270
5271   // Vectors containing all zeros can be matched by pxor and xorps later
5272   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5273     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5274     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5275     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5276       return Op;
5277
5278     return getZeroVector(VT, Subtarget, DAG, dl);
5279   }
5280
5281   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5282   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5283   // vpcmpeqd on 256-bit vectors.
5284   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5285     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5286       return Op;
5287
5288     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5289   }
5290
5291   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5292   if (Broadcast.getNode())
5293     return Broadcast;
5294
5295   unsigned EVTBits = ExtVT.getSizeInBits();
5296
5297   unsigned NumZero  = 0;
5298   unsigned NumNonZero = 0;
5299   unsigned NonZeros = 0;
5300   bool IsAllConstants = true;
5301   SmallSet<SDValue, 8> Values;
5302   for (unsigned i = 0; i < NumElems; ++i) {
5303     SDValue Elt = Op.getOperand(i);
5304     if (Elt.getOpcode() == ISD::UNDEF)
5305       continue;
5306     Values.insert(Elt);
5307     if (Elt.getOpcode() != ISD::Constant &&
5308         Elt.getOpcode() != ISD::ConstantFP)
5309       IsAllConstants = false;
5310     if (X86::isZeroNode(Elt))
5311       NumZero++;
5312     else {
5313       NonZeros |= (1 << i);
5314       NumNonZero++;
5315     }
5316   }
5317
5318   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5319   if (NumNonZero == 0)
5320     return DAG.getUNDEF(VT);
5321
5322   // Special case for single non-zero, non-undef, element.
5323   if (NumNonZero == 1) {
5324     unsigned Idx = CountTrailingZeros_32(NonZeros);
5325     SDValue Item = Op.getOperand(Idx);
5326
5327     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5328     // the value are obviously zero, truncate the value to i32 and do the
5329     // insertion that way.  Only do this if the value is non-constant or if the
5330     // value is a constant being inserted into element 0.  It is cheaper to do
5331     // a constant pool load than it is to do a movd + shuffle.
5332     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5333         (!IsAllConstants || Idx == 0)) {
5334       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5335         // Handle SSE only.
5336         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5337         EVT VecVT = MVT::v4i32;
5338         unsigned VecElts = 4;
5339
5340         // Truncate the value (which may itself be a constant) to i32, and
5341         // convert it to a vector with movd (S2V+shuffle to zero extend).
5342         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5343         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5344         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5345
5346         // Now we have our 32-bit value zero extended in the low element of
5347         // a vector.  If Idx != 0, swizzle it into place.
5348         if (Idx != 0) {
5349           SmallVector<int, 4> Mask;
5350           Mask.push_back(Idx);
5351           for (unsigned i = 1; i != VecElts; ++i)
5352             Mask.push_back(i);
5353           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5354                                       &Mask[0]);
5355         }
5356         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5357       }
5358     }
5359
5360     // If we have a constant or non-constant insertion into the low element of
5361     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5362     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5363     // depending on what the source datatype is.
5364     if (Idx == 0) {
5365       if (NumZero == 0)
5366         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5367
5368       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5369           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5370         if (VT.is256BitVector()) {
5371           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5372           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5373                              Item, DAG.getIntPtrConstant(0));
5374         }
5375         assert(VT.is128BitVector() && "Expected an SSE value type!");
5376         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5377         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5378         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5379       }
5380
5381       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5382         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5383         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5384         if (VT.is256BitVector()) {
5385           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5386           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5387         } else {
5388           assert(VT.is128BitVector() && "Expected an SSE value type!");
5389           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5390         }
5391         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5392       }
5393     }
5394
5395     // Is it a vector logical left shift?
5396     if (NumElems == 2 && Idx == 1 &&
5397         X86::isZeroNode(Op.getOperand(0)) &&
5398         !X86::isZeroNode(Op.getOperand(1))) {
5399       unsigned NumBits = VT.getSizeInBits();
5400       return getVShift(true, VT,
5401                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5402                                    VT, Op.getOperand(1)),
5403                        NumBits/2, DAG, *this, dl);
5404     }
5405
5406     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5407       return SDValue();
5408
5409     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5410     // is a non-constant being inserted into an element other than the low one,
5411     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5412     // movd/movss) to move this into the low element, then shuffle it into
5413     // place.
5414     if (EVTBits == 32) {
5415       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5416
5417       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5418       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5419       SmallVector<int, 8> MaskVec;
5420       for (unsigned i = 0; i != NumElems; ++i)
5421         MaskVec.push_back(i == Idx ? 0 : 1);
5422       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5423     }
5424   }
5425
5426   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5427   if (Values.size() == 1) {
5428     if (EVTBits == 32) {
5429       // Instead of a shuffle like this:
5430       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5431       // Check if it's possible to issue this instead.
5432       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5433       unsigned Idx = CountTrailingZeros_32(NonZeros);
5434       SDValue Item = Op.getOperand(Idx);
5435       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5436         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5437     }
5438     return SDValue();
5439   }
5440
5441   // A vector full of immediates; various special cases are already
5442   // handled, so this is best done with a single constant-pool load.
5443   if (IsAllConstants)
5444     return SDValue();
5445
5446   // For AVX-length vectors, build the individual 128-bit pieces and use
5447   // shuffles to put them in place.
5448   if (VT.is256BitVector()) {
5449     SmallVector<SDValue, 32> V;
5450     for (unsigned i = 0; i != NumElems; ++i)
5451       V.push_back(Op.getOperand(i));
5452
5453     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5454
5455     // Build both the lower and upper subvector.
5456     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5457     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5458                                 NumElems/2);
5459
5460     // Recreate the wider vector with the lower and upper part.
5461     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5462   }
5463
5464   // Let legalizer expand 2-wide build_vectors.
5465   if (EVTBits == 64) {
5466     if (NumNonZero == 1) {
5467       // One half is zero or undef.
5468       unsigned Idx = CountTrailingZeros_32(NonZeros);
5469       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5470                                  Op.getOperand(Idx));
5471       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5472     }
5473     return SDValue();
5474   }
5475
5476   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5477   if (EVTBits == 8 && NumElems == 16) {
5478     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5479                                         Subtarget, *this);
5480     if (V.getNode()) return V;
5481   }
5482
5483   if (EVTBits == 16 && NumElems == 8) {
5484     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5485                                       Subtarget, *this);
5486     if (V.getNode()) return V;
5487   }
5488
5489   // If element VT is == 32 bits, turn it into a number of shuffles.
5490   SmallVector<SDValue, 8> V(NumElems);
5491   if (NumElems == 4 && NumZero > 0) {
5492     for (unsigned i = 0; i < 4; ++i) {
5493       bool isZero = !(NonZeros & (1 << i));
5494       if (isZero)
5495         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5496       else
5497         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5498     }
5499
5500     for (unsigned i = 0; i < 2; ++i) {
5501       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5502         default: break;
5503         case 0:
5504           V[i] = V[i*2];  // Must be a zero vector.
5505           break;
5506         case 1:
5507           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5508           break;
5509         case 2:
5510           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5511           break;
5512         case 3:
5513           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5514           break;
5515       }
5516     }
5517
5518     bool Reverse1 = (NonZeros & 0x3) == 2;
5519     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5520     int MaskVec[] = {
5521       Reverse1 ? 1 : 0,
5522       Reverse1 ? 0 : 1,
5523       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5524       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5525     };
5526     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5527   }
5528
5529   if (Values.size() > 1 && VT.is128BitVector()) {
5530     // Check for a build vector of consecutive loads.
5531     for (unsigned i = 0; i < NumElems; ++i)
5532       V[i] = Op.getOperand(i);
5533
5534     // Check for elements which are consecutive loads.
5535     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5536     if (LD.getNode())
5537       return LD;
5538
5539     // Check for a build vector from mostly shuffle plus few inserting.
5540     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5541     if (Sh.getNode())
5542       return Sh;
5543
5544     // For SSE 4.1, use insertps to put the high elements into the low element.
5545     if (getSubtarget()->hasSSE41()) {
5546       SDValue Result;
5547       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5548         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5549       else
5550         Result = DAG.getUNDEF(VT);
5551
5552       for (unsigned i = 1; i < NumElems; ++i) {
5553         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5554         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5555                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5556       }
5557       return Result;
5558     }
5559
5560     // Otherwise, expand into a number of unpckl*, start by extending each of
5561     // our (non-undef) elements to the full vector width with the element in the
5562     // bottom slot of the vector (which generates no code for SSE).
5563     for (unsigned i = 0; i < NumElems; ++i) {
5564       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5565         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5566       else
5567         V[i] = DAG.getUNDEF(VT);
5568     }
5569
5570     // Next, we iteratively mix elements, e.g. for v4f32:
5571     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5572     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5573     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5574     unsigned EltStride = NumElems >> 1;
5575     while (EltStride != 0) {
5576       for (unsigned i = 0; i < EltStride; ++i) {
5577         // If V[i+EltStride] is undef and this is the first round of mixing,
5578         // then it is safe to just drop this shuffle: V[i] is already in the
5579         // right place, the one element (since it's the first round) being
5580         // inserted as undef can be dropped.  This isn't safe for successive
5581         // rounds because they will permute elements within both vectors.
5582         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5583             EltStride == NumElems/2)
5584           continue;
5585
5586         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5587       }
5588       EltStride >>= 1;
5589     }
5590     return V[0];
5591   }
5592   return SDValue();
5593 }
5594
5595 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5596 // to create 256-bit vectors from two other 128-bit ones.
5597 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5598   DebugLoc dl = Op.getDebugLoc();
5599   EVT ResVT = Op.getValueType();
5600
5601   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5602
5603   SDValue V1 = Op.getOperand(0);
5604   SDValue V2 = Op.getOperand(1);
5605   unsigned NumElems = ResVT.getVectorNumElements();
5606
5607   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5608 }
5609
5610 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5611   assert(Op.getNumOperands() == 2);
5612
5613   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5614   // from two other 128-bit ones.
5615   return LowerAVXCONCAT_VECTORS(Op, DAG);
5616 }
5617
5618 // Try to lower a shuffle node into a simple blend instruction.
5619 static SDValue
5620 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5621                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5622   SDValue V1 = SVOp->getOperand(0);
5623   SDValue V2 = SVOp->getOperand(1);
5624   DebugLoc dl = SVOp->getDebugLoc();
5625   MVT VT = SVOp->getValueType(0).getSimpleVT();
5626   unsigned NumElems = VT.getVectorNumElements();
5627
5628   if (!Subtarget->hasSSE41())
5629     return SDValue();
5630
5631   unsigned ISDNo = 0;
5632   MVT OpTy;
5633
5634   switch (VT.SimpleTy) {
5635   default: return SDValue();
5636   case MVT::v8i16:
5637     ISDNo = X86ISD::BLENDPW;
5638     OpTy = MVT::v8i16;
5639     break;
5640   case MVT::v4i32:
5641   case MVT::v4f32:
5642     ISDNo = X86ISD::BLENDPS;
5643     OpTy = MVT::v4f32;
5644     break;
5645   case MVT::v2i64:
5646   case MVT::v2f64:
5647     ISDNo = X86ISD::BLENDPD;
5648     OpTy = MVT::v2f64;
5649     break;
5650   case MVT::v8i32:
5651   case MVT::v8f32:
5652     if (!Subtarget->hasAVX())
5653       return SDValue();
5654     ISDNo = X86ISD::BLENDPS;
5655     OpTy = MVT::v8f32;
5656     break;
5657   case MVT::v4i64:
5658   case MVT::v4f64:
5659     if (!Subtarget->hasAVX())
5660       return SDValue();
5661     ISDNo = X86ISD::BLENDPD;
5662     OpTy = MVT::v4f64;
5663     break;
5664   }
5665   assert(ISDNo && "Invalid Op Number");
5666
5667   unsigned MaskVals = 0;
5668
5669   for (unsigned i = 0; i != NumElems; ++i) {
5670     int EltIdx = SVOp->getMaskElt(i);
5671     if (EltIdx == (int)i || EltIdx < 0)
5672       MaskVals |= (1<<i);
5673     else if (EltIdx == (int)(i + NumElems))
5674       continue; // Bit is set to zero;
5675     else
5676       return SDValue();
5677   }
5678
5679   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5680   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5681   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5682                              DAG.getConstant(MaskVals, MVT::i32));
5683   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5684 }
5685
5686 // v8i16 shuffles - Prefer shuffles in the following order:
5687 // 1. [all]   pshuflw, pshufhw, optional move
5688 // 2. [ssse3] 1 x pshufb
5689 // 3. [ssse3] 2 x pshufb + 1 x por
5690 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5691 static SDValue
5692 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5693                          SelectionDAG &DAG) {
5694   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5695   SDValue V1 = SVOp->getOperand(0);
5696   SDValue V2 = SVOp->getOperand(1);
5697   DebugLoc dl = SVOp->getDebugLoc();
5698   SmallVector<int, 8> MaskVals;
5699
5700   // Determine if more than 1 of the words in each of the low and high quadwords
5701   // of the result come from the same quadword of one of the two inputs.  Undef
5702   // mask values count as coming from any quadword, for better codegen.
5703   unsigned LoQuad[] = { 0, 0, 0, 0 };
5704   unsigned HiQuad[] = { 0, 0, 0, 0 };
5705   std::bitset<4> InputQuads;
5706   for (unsigned i = 0; i < 8; ++i) {
5707     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5708     int EltIdx = SVOp->getMaskElt(i);
5709     MaskVals.push_back(EltIdx);
5710     if (EltIdx < 0) {
5711       ++Quad[0];
5712       ++Quad[1];
5713       ++Quad[2];
5714       ++Quad[3];
5715       continue;
5716     }
5717     ++Quad[EltIdx / 4];
5718     InputQuads.set(EltIdx / 4);
5719   }
5720
5721   int BestLoQuad = -1;
5722   unsigned MaxQuad = 1;
5723   for (unsigned i = 0; i < 4; ++i) {
5724     if (LoQuad[i] > MaxQuad) {
5725       BestLoQuad = i;
5726       MaxQuad = LoQuad[i];
5727     }
5728   }
5729
5730   int BestHiQuad = -1;
5731   MaxQuad = 1;
5732   for (unsigned i = 0; i < 4; ++i) {
5733     if (HiQuad[i] > MaxQuad) {
5734       BestHiQuad = i;
5735       MaxQuad = HiQuad[i];
5736     }
5737   }
5738
5739   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5740   // of the two input vectors, shuffle them into one input vector so only a
5741   // single pshufb instruction is necessary. If There are more than 2 input
5742   // quads, disable the next transformation since it does not help SSSE3.
5743   bool V1Used = InputQuads[0] || InputQuads[1];
5744   bool V2Used = InputQuads[2] || InputQuads[3];
5745   if (Subtarget->hasSSSE3()) {
5746     if (InputQuads.count() == 2 && V1Used && V2Used) {
5747       BestLoQuad = InputQuads[0] ? 0 : 1;
5748       BestHiQuad = InputQuads[2] ? 2 : 3;
5749     }
5750     if (InputQuads.count() > 2) {
5751       BestLoQuad = -1;
5752       BestHiQuad = -1;
5753     }
5754   }
5755
5756   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5757   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5758   // words from all 4 input quadwords.
5759   SDValue NewV;
5760   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5761     int MaskV[] = {
5762       BestLoQuad < 0 ? 0 : BestLoQuad,
5763       BestHiQuad < 0 ? 1 : BestHiQuad
5764     };
5765     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5766                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5767                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5768     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5769
5770     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5771     // source words for the shuffle, to aid later transformations.
5772     bool AllWordsInNewV = true;
5773     bool InOrder[2] = { true, true };
5774     for (unsigned i = 0; i != 8; ++i) {
5775       int idx = MaskVals[i];
5776       if (idx != (int)i)
5777         InOrder[i/4] = false;
5778       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5779         continue;
5780       AllWordsInNewV = false;
5781       break;
5782     }
5783
5784     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5785     if (AllWordsInNewV) {
5786       for (int i = 0; i != 8; ++i) {
5787         int idx = MaskVals[i];
5788         if (idx < 0)
5789           continue;
5790         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5791         if ((idx != i) && idx < 4)
5792           pshufhw = false;
5793         if ((idx != i) && idx > 3)
5794           pshuflw = false;
5795       }
5796       V1 = NewV;
5797       V2Used = false;
5798       BestLoQuad = 0;
5799       BestHiQuad = 1;
5800     }
5801
5802     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5803     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5804     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5805       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5806       unsigned TargetMask = 0;
5807       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5808                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5809       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5810       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5811                              getShufflePSHUFLWImmediate(SVOp);
5812       V1 = NewV.getOperand(0);
5813       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5814     }
5815   }
5816
5817   // If we have SSSE3, and all words of the result are from 1 input vector,
5818   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5819   // is present, fall back to case 4.
5820   if (Subtarget->hasSSSE3()) {
5821     SmallVector<SDValue,16> pshufbMask;
5822
5823     // If we have elements from both input vectors, set the high bit of the
5824     // shuffle mask element to zero out elements that come from V2 in the V1
5825     // mask, and elements that come from V1 in the V2 mask, so that the two
5826     // results can be OR'd together.
5827     bool TwoInputs = V1Used && V2Used;
5828     for (unsigned i = 0; i != 8; ++i) {
5829       int EltIdx = MaskVals[i] * 2;
5830       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5831       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5832       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5833       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5834     }
5835     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5836     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5837                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5838                                  MVT::v16i8, &pshufbMask[0], 16));
5839     if (!TwoInputs)
5840       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5841
5842     // Calculate the shuffle mask for the second input, shuffle it, and
5843     // OR it with the first shuffled input.
5844     pshufbMask.clear();
5845     for (unsigned i = 0; i != 8; ++i) {
5846       int EltIdx = MaskVals[i] * 2;
5847       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5848       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5849       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5850       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5851     }
5852     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5853     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5854                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5855                                  MVT::v16i8, &pshufbMask[0], 16));
5856     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5857     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5858   }
5859
5860   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5861   // and update MaskVals with new element order.
5862   std::bitset<8> InOrder;
5863   if (BestLoQuad >= 0) {
5864     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5865     for (int i = 0; i != 4; ++i) {
5866       int idx = MaskVals[i];
5867       if (idx < 0) {
5868         InOrder.set(i);
5869       } else if ((idx / 4) == BestLoQuad) {
5870         MaskV[i] = idx & 3;
5871         InOrder.set(i);
5872       }
5873     }
5874     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5875                                 &MaskV[0]);
5876
5877     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5878       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5879       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5880                                   NewV.getOperand(0),
5881                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5882     }
5883   }
5884
5885   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5886   // and update MaskVals with the new element order.
5887   if (BestHiQuad >= 0) {
5888     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5889     for (unsigned i = 4; i != 8; ++i) {
5890       int idx = MaskVals[i];
5891       if (idx < 0) {
5892         InOrder.set(i);
5893       } else if ((idx / 4) == BestHiQuad) {
5894         MaskV[i] = (idx & 3) + 4;
5895         InOrder.set(i);
5896       }
5897     }
5898     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5899                                 &MaskV[0]);
5900
5901     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5902       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5903       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5904                                   NewV.getOperand(0),
5905                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5906     }
5907   }
5908
5909   // In case BestHi & BestLo were both -1, which means each quadword has a word
5910   // from each of the four input quadwords, calculate the InOrder bitvector now
5911   // before falling through to the insert/extract cleanup.
5912   if (BestLoQuad == -1 && BestHiQuad == -1) {
5913     NewV = V1;
5914     for (int i = 0; i != 8; ++i)
5915       if (MaskVals[i] < 0 || MaskVals[i] == i)
5916         InOrder.set(i);
5917   }
5918
5919   // The other elements are put in the right place using pextrw and pinsrw.
5920   for (unsigned i = 0; i != 8; ++i) {
5921     if (InOrder[i])
5922       continue;
5923     int EltIdx = MaskVals[i];
5924     if (EltIdx < 0)
5925       continue;
5926     SDValue ExtOp = (EltIdx < 8) ?
5927       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5928                   DAG.getIntPtrConstant(EltIdx)) :
5929       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5930                   DAG.getIntPtrConstant(EltIdx - 8));
5931     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5932                        DAG.getIntPtrConstant(i));
5933   }
5934   return NewV;
5935 }
5936
5937 // v16i8 shuffles - Prefer shuffles in the following order:
5938 // 1. [ssse3] 1 x pshufb
5939 // 2. [ssse3] 2 x pshufb + 1 x por
5940 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5941 static
5942 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5943                                  SelectionDAG &DAG,
5944                                  const X86TargetLowering &TLI) {
5945   SDValue V1 = SVOp->getOperand(0);
5946   SDValue V2 = SVOp->getOperand(1);
5947   DebugLoc dl = SVOp->getDebugLoc();
5948   ArrayRef<int> MaskVals = SVOp->getMask();
5949
5950   // If we have SSSE3, case 1 is generated when all result bytes come from
5951   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5952   // present, fall back to case 3.
5953
5954   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5955   if (TLI.getSubtarget()->hasSSSE3()) {
5956     SmallVector<SDValue,16> pshufbMask;
5957
5958     // If all result elements are from one input vector, then only translate
5959     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5960     //
5961     // Otherwise, we have elements from both input vectors, and must zero out
5962     // elements that come from V2 in the first mask, and V1 in the second mask
5963     // so that we can OR them together.
5964     for (unsigned i = 0; i != 16; ++i) {
5965       int EltIdx = MaskVals[i];
5966       if (EltIdx < 0 || EltIdx >= 16)
5967         EltIdx = 0x80;
5968       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5969     }
5970     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5971                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5972                                  MVT::v16i8, &pshufbMask[0], 16));
5973
5974     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5975     // the 2nd operand if it's undefined or zero.
5976     if (V2.getOpcode() == ISD::UNDEF ||
5977         ISD::isBuildVectorAllZeros(V2.getNode()))
5978       return V1;
5979
5980     // Calculate the shuffle mask for the second input, shuffle it, and
5981     // OR it with the first shuffled input.
5982     pshufbMask.clear();
5983     for (unsigned i = 0; i != 16; ++i) {
5984       int EltIdx = MaskVals[i];
5985       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5986       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5987     }
5988     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5989                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5990                                  MVT::v16i8, &pshufbMask[0], 16));
5991     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5992   }
5993
5994   // No SSSE3 - Calculate in place words and then fix all out of place words
5995   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5996   // the 16 different words that comprise the two doublequadword input vectors.
5997   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5998   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5999   SDValue NewV = V1;
6000   for (int i = 0; i != 8; ++i) {
6001     int Elt0 = MaskVals[i*2];
6002     int Elt1 = MaskVals[i*2+1];
6003
6004     // This word of the result is all undef, skip it.
6005     if (Elt0 < 0 && Elt1 < 0)
6006       continue;
6007
6008     // This word of the result is already in the correct place, skip it.
6009     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6010       continue;
6011
6012     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6013     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6014     SDValue InsElt;
6015
6016     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6017     // using a single extract together, load it and store it.
6018     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6019       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6020                            DAG.getIntPtrConstant(Elt1 / 2));
6021       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6022                         DAG.getIntPtrConstant(i));
6023       continue;
6024     }
6025
6026     // If Elt1 is defined, extract it from the appropriate source.  If the
6027     // source byte is not also odd, shift the extracted word left 8 bits
6028     // otherwise clear the bottom 8 bits if we need to do an or.
6029     if (Elt1 >= 0) {
6030       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6031                            DAG.getIntPtrConstant(Elt1 / 2));
6032       if ((Elt1 & 1) == 0)
6033         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6034                              DAG.getConstant(8,
6035                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6036       else if (Elt0 >= 0)
6037         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6038                              DAG.getConstant(0xFF00, MVT::i16));
6039     }
6040     // If Elt0 is defined, extract it from the appropriate source.  If the
6041     // source byte is not also even, shift the extracted word right 8 bits. If
6042     // Elt1 was also defined, OR the extracted values together before
6043     // inserting them in the result.
6044     if (Elt0 >= 0) {
6045       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6046                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6047       if ((Elt0 & 1) != 0)
6048         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6049                               DAG.getConstant(8,
6050                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6051       else if (Elt1 >= 0)
6052         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6053                              DAG.getConstant(0x00FF, MVT::i16));
6054       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6055                          : InsElt0;
6056     }
6057     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6058                        DAG.getIntPtrConstant(i));
6059   }
6060   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6061 }
6062
6063 // v32i8 shuffles - Translate to VPSHUFB if possible.
6064 static
6065 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6066                                  const X86Subtarget *Subtarget,
6067                                  SelectionDAG &DAG) {
6068   EVT VT = SVOp->getValueType(0);
6069   SDValue V1 = SVOp->getOperand(0);
6070   SDValue V2 = SVOp->getOperand(1);
6071   DebugLoc dl = SVOp->getDebugLoc();
6072   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6073
6074   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6075   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6076   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6077
6078   // VPSHUFB may be generated if
6079   // (1) one of input vector is undefined or zeroinitializer.
6080   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6081   // And (2) the mask indexes don't cross the 128-bit lane.
6082   if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6083       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6084     return SDValue();
6085
6086   if (V1IsAllZero && !V2IsAllZero) {
6087     CommuteVectorShuffleMask(MaskVals, 32);
6088     V1 = V2;
6089   }
6090   SmallVector<SDValue, 32> pshufbMask;
6091   for (unsigned i = 0; i != 32; i++) {
6092     int EltIdx = MaskVals[i];
6093     if (EltIdx < 0 || EltIdx >= 32)
6094       EltIdx = 0x80;
6095     else {
6096       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6097         // Cross lane is not allowed.
6098         return SDValue();
6099       EltIdx &= 0xf;
6100     }
6101     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6102   }
6103   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6104                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6105                                   MVT::v32i8, &pshufbMask[0], 32));
6106 }
6107
6108 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6109 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6110 /// done when every pair / quad of shuffle mask elements point to elements in
6111 /// the right sequence. e.g.
6112 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6113 static
6114 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6115                                  SelectionDAG &DAG, DebugLoc dl) {
6116   MVT VT = SVOp->getValueType(0).getSimpleVT();
6117   unsigned NumElems = VT.getVectorNumElements();
6118   MVT NewVT;
6119   unsigned Scale;
6120   switch (VT.SimpleTy) {
6121   default: llvm_unreachable("Unexpected!");
6122   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6123   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6124   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6125   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6126   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6127   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6128   }
6129
6130   SmallVector<int, 8> MaskVec;
6131   for (unsigned i = 0; i != NumElems; i += Scale) {
6132     int StartIdx = -1;
6133     for (unsigned j = 0; j != Scale; ++j) {
6134       int EltIdx = SVOp->getMaskElt(i+j);
6135       if (EltIdx < 0)
6136         continue;
6137       if (StartIdx < 0)
6138         StartIdx = (EltIdx / Scale);
6139       if (EltIdx != (int)(StartIdx*Scale + j))
6140         return SDValue();
6141     }
6142     MaskVec.push_back(StartIdx);
6143   }
6144
6145   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6146   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6147   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6148 }
6149
6150 /// getVZextMovL - Return a zero-extending vector move low node.
6151 ///
6152 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6153                             SDValue SrcOp, SelectionDAG &DAG,
6154                             const X86Subtarget *Subtarget, DebugLoc dl) {
6155   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6156     LoadSDNode *LD = NULL;
6157     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6158       LD = dyn_cast<LoadSDNode>(SrcOp);
6159     if (!LD) {
6160       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6161       // instead.
6162       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6163       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6164           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6165           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6166           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6167         // PR2108
6168         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6169         return DAG.getNode(ISD::BITCAST, dl, VT,
6170                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6171                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6172                                                    OpVT,
6173                                                    SrcOp.getOperand(0)
6174                                                           .getOperand(0))));
6175       }
6176     }
6177   }
6178
6179   return DAG.getNode(ISD::BITCAST, dl, VT,
6180                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6181                                  DAG.getNode(ISD::BITCAST, dl,
6182                                              OpVT, SrcOp)));
6183 }
6184
6185 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6186 /// which could not be matched by any known target speficic shuffle
6187 static SDValue
6188 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6189
6190   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6191   if (NewOp.getNode())
6192     return NewOp;
6193
6194   EVT VT = SVOp->getValueType(0);
6195
6196   unsigned NumElems = VT.getVectorNumElements();
6197   unsigned NumLaneElems = NumElems / 2;
6198
6199   DebugLoc dl = SVOp->getDebugLoc();
6200   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6201   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6202   SDValue Output[2];
6203
6204   SmallVector<int, 16> Mask;
6205   for (unsigned l = 0; l < 2; ++l) {
6206     // Build a shuffle mask for the output, discovering on the fly which
6207     // input vectors to use as shuffle operands (recorded in InputUsed).
6208     // If building a suitable shuffle vector proves too hard, then bail
6209     // out with UseBuildVector set.
6210     bool UseBuildVector = false;
6211     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6212     unsigned LaneStart = l * NumLaneElems;
6213     for (unsigned i = 0; i != NumLaneElems; ++i) {
6214       // The mask element.  This indexes into the input.
6215       int Idx = SVOp->getMaskElt(i+LaneStart);
6216       if (Idx < 0) {
6217         // the mask element does not index into any input vector.
6218         Mask.push_back(-1);
6219         continue;
6220       }
6221
6222       // The input vector this mask element indexes into.
6223       int Input = Idx / NumLaneElems;
6224
6225       // Turn the index into an offset from the start of the input vector.
6226       Idx -= Input * NumLaneElems;
6227
6228       // Find or create a shuffle vector operand to hold this input.
6229       unsigned OpNo;
6230       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6231         if (InputUsed[OpNo] == Input)
6232           // This input vector is already an operand.
6233           break;
6234         if (InputUsed[OpNo] < 0) {
6235           // Create a new operand for this input vector.
6236           InputUsed[OpNo] = Input;
6237           break;
6238         }
6239       }
6240
6241       if (OpNo >= array_lengthof(InputUsed)) {
6242         // More than two input vectors used!  Give up on trying to create a
6243         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6244         UseBuildVector = true;
6245         break;
6246       }
6247
6248       // Add the mask index for the new shuffle vector.
6249       Mask.push_back(Idx + OpNo * NumLaneElems);
6250     }
6251
6252     if (UseBuildVector) {
6253       SmallVector<SDValue, 16> SVOps;
6254       for (unsigned i = 0; i != NumLaneElems; ++i) {
6255         // The mask element.  This indexes into the input.
6256         int Idx = SVOp->getMaskElt(i+LaneStart);
6257         if (Idx < 0) {
6258           SVOps.push_back(DAG.getUNDEF(EltVT));
6259           continue;
6260         }
6261
6262         // The input vector this mask element indexes into.
6263         int Input = Idx / NumElems;
6264
6265         // Turn the index into an offset from the start of the input vector.
6266         Idx -= Input * NumElems;
6267
6268         // Extract the vector element by hand.
6269         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6270                                     SVOp->getOperand(Input),
6271                                     DAG.getIntPtrConstant(Idx)));
6272       }
6273
6274       // Construct the output using a BUILD_VECTOR.
6275       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6276                               SVOps.size());
6277     } else if (InputUsed[0] < 0) {
6278       // No input vectors were used! The result is undefined.
6279       Output[l] = DAG.getUNDEF(NVT);
6280     } else {
6281       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6282                                         (InputUsed[0] % 2) * NumLaneElems,
6283                                         DAG, dl);
6284       // If only one input was used, use an undefined vector for the other.
6285       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6286         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6287                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6288       // At least one input vector was used. Create a new shuffle vector.
6289       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6290     }
6291
6292     Mask.clear();
6293   }
6294
6295   // Concatenate the result back
6296   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6297 }
6298
6299 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6300 /// 4 elements, and match them with several different shuffle types.
6301 static SDValue
6302 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6303   SDValue V1 = SVOp->getOperand(0);
6304   SDValue V2 = SVOp->getOperand(1);
6305   DebugLoc dl = SVOp->getDebugLoc();
6306   EVT VT = SVOp->getValueType(0);
6307
6308   assert(VT.is128BitVector() && "Unsupported vector size");
6309
6310   std::pair<int, int> Locs[4];
6311   int Mask1[] = { -1, -1, -1, -1 };
6312   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6313
6314   unsigned NumHi = 0;
6315   unsigned NumLo = 0;
6316   for (unsigned i = 0; i != 4; ++i) {
6317     int Idx = PermMask[i];
6318     if (Idx < 0) {
6319       Locs[i] = std::make_pair(-1, -1);
6320     } else {
6321       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6322       if (Idx < 4) {
6323         Locs[i] = std::make_pair(0, NumLo);
6324         Mask1[NumLo] = Idx;
6325         NumLo++;
6326       } else {
6327         Locs[i] = std::make_pair(1, NumHi);
6328         if (2+NumHi < 4)
6329           Mask1[2+NumHi] = Idx;
6330         NumHi++;
6331       }
6332     }
6333   }
6334
6335   if (NumLo <= 2 && NumHi <= 2) {
6336     // If no more than two elements come from either vector. This can be
6337     // implemented with two shuffles. First shuffle gather the elements.
6338     // The second shuffle, which takes the first shuffle as both of its
6339     // vector operands, put the elements into the right order.
6340     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6341
6342     int Mask2[] = { -1, -1, -1, -1 };
6343
6344     for (unsigned i = 0; i != 4; ++i)
6345       if (Locs[i].first != -1) {
6346         unsigned Idx = (i < 2) ? 0 : 4;
6347         Idx += Locs[i].first * 2 + Locs[i].second;
6348         Mask2[i] = Idx;
6349       }
6350
6351     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6352   }
6353
6354   if (NumLo == 3 || NumHi == 3) {
6355     // Otherwise, we must have three elements from one vector, call it X, and
6356     // one element from the other, call it Y.  First, use a shufps to build an
6357     // intermediate vector with the one element from Y and the element from X
6358     // that will be in the same half in the final destination (the indexes don't
6359     // matter). Then, use a shufps to build the final vector, taking the half
6360     // containing the element from Y from the intermediate, and the other half
6361     // from X.
6362     if (NumHi == 3) {
6363       // Normalize it so the 3 elements come from V1.
6364       CommuteVectorShuffleMask(PermMask, 4);
6365       std::swap(V1, V2);
6366     }
6367
6368     // Find the element from V2.
6369     unsigned HiIndex;
6370     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6371       int Val = PermMask[HiIndex];
6372       if (Val < 0)
6373         continue;
6374       if (Val >= 4)
6375         break;
6376     }
6377
6378     Mask1[0] = PermMask[HiIndex];
6379     Mask1[1] = -1;
6380     Mask1[2] = PermMask[HiIndex^1];
6381     Mask1[3] = -1;
6382     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6383
6384     if (HiIndex >= 2) {
6385       Mask1[0] = PermMask[0];
6386       Mask1[1] = PermMask[1];
6387       Mask1[2] = HiIndex & 1 ? 6 : 4;
6388       Mask1[3] = HiIndex & 1 ? 4 : 6;
6389       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6390     }
6391
6392     Mask1[0] = HiIndex & 1 ? 2 : 0;
6393     Mask1[1] = HiIndex & 1 ? 0 : 2;
6394     Mask1[2] = PermMask[2];
6395     Mask1[3] = PermMask[3];
6396     if (Mask1[2] >= 0)
6397       Mask1[2] += 4;
6398     if (Mask1[3] >= 0)
6399       Mask1[3] += 4;
6400     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6401   }
6402
6403   // Break it into (shuffle shuffle_hi, shuffle_lo).
6404   int LoMask[] = { -1, -1, -1, -1 };
6405   int HiMask[] = { -1, -1, -1, -1 };
6406
6407   int *MaskPtr = LoMask;
6408   unsigned MaskIdx = 0;
6409   unsigned LoIdx = 0;
6410   unsigned HiIdx = 2;
6411   for (unsigned i = 0; i != 4; ++i) {
6412     if (i == 2) {
6413       MaskPtr = HiMask;
6414       MaskIdx = 1;
6415       LoIdx = 0;
6416       HiIdx = 2;
6417     }
6418     int Idx = PermMask[i];
6419     if (Idx < 0) {
6420       Locs[i] = std::make_pair(-1, -1);
6421     } else if (Idx < 4) {
6422       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6423       MaskPtr[LoIdx] = Idx;
6424       LoIdx++;
6425     } else {
6426       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6427       MaskPtr[HiIdx] = Idx;
6428       HiIdx++;
6429     }
6430   }
6431
6432   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6433   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6434   int MaskOps[] = { -1, -1, -1, -1 };
6435   for (unsigned i = 0; i != 4; ++i)
6436     if (Locs[i].first != -1)
6437       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6438   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6439 }
6440
6441 static bool MayFoldVectorLoad(SDValue V) {
6442   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6443     V = V.getOperand(0);
6444
6445   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6446     V = V.getOperand(0);
6447   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6448       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6449     // BUILD_VECTOR (load), undef
6450     V = V.getOperand(0);
6451
6452   return MayFoldLoad(V);
6453 }
6454
6455 // FIXME: the version above should always be used. Since there's
6456 // a bug where several vector shuffles can't be folded because the
6457 // DAG is not updated during lowering and a node claims to have two
6458 // uses while it only has one, use this version, and let isel match
6459 // another instruction if the load really happens to have more than
6460 // one use. Remove this version after this bug get fixed.
6461 // rdar://8434668, PR8156
6462 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6463   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6464     V = V.getOperand(0);
6465   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6466     V = V.getOperand(0);
6467   if (ISD::isNormalLoad(V.getNode()))
6468     return true;
6469   return false;
6470 }
6471
6472 static
6473 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6474   EVT VT = Op.getValueType();
6475
6476   // Canonizalize to v2f64.
6477   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6478   return DAG.getNode(ISD::BITCAST, dl, VT,
6479                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6480                                           V1, DAG));
6481 }
6482
6483 static
6484 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6485                         bool HasSSE2) {
6486   SDValue V1 = Op.getOperand(0);
6487   SDValue V2 = Op.getOperand(1);
6488   EVT VT = Op.getValueType();
6489
6490   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6491
6492   if (HasSSE2 && VT == MVT::v2f64)
6493     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6494
6495   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6496   return DAG.getNode(ISD::BITCAST, dl, VT,
6497                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6498                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6499                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6500 }
6501
6502 static
6503 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6504   SDValue V1 = Op.getOperand(0);
6505   SDValue V2 = Op.getOperand(1);
6506   EVT VT = Op.getValueType();
6507
6508   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6509          "unsupported shuffle type");
6510
6511   if (V2.getOpcode() == ISD::UNDEF)
6512     V2 = V1;
6513
6514   // v4i32 or v4f32
6515   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6516 }
6517
6518 static
6519 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6520   SDValue V1 = Op.getOperand(0);
6521   SDValue V2 = Op.getOperand(1);
6522   EVT VT = Op.getValueType();
6523   unsigned NumElems = VT.getVectorNumElements();
6524
6525   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6526   // operand of these instructions is only memory, so check if there's a
6527   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6528   // same masks.
6529   bool CanFoldLoad = false;
6530
6531   // Trivial case, when V2 comes from a load.
6532   if (MayFoldVectorLoad(V2))
6533     CanFoldLoad = true;
6534
6535   // When V1 is a load, it can be folded later into a store in isel, example:
6536   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6537   //    turns into:
6538   //  (MOVLPSmr addr:$src1, VR128:$src2)
6539   // So, recognize this potential and also use MOVLPS or MOVLPD
6540   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6541     CanFoldLoad = true;
6542
6543   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6544   if (CanFoldLoad) {
6545     if (HasSSE2 && NumElems == 2)
6546       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6547
6548     if (NumElems == 4)
6549       // If we don't care about the second element, proceed to use movss.
6550       if (SVOp->getMaskElt(1) != -1)
6551         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6552   }
6553
6554   // movl and movlp will both match v2i64, but v2i64 is never matched by
6555   // movl earlier because we make it strict to avoid messing with the movlp load
6556   // folding logic (see the code above getMOVLP call). Match it here then,
6557   // this is horrible, but will stay like this until we move all shuffle
6558   // matching to x86 specific nodes. Note that for the 1st condition all
6559   // types are matched with movsd.
6560   if (HasSSE2) {
6561     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6562     // as to remove this logic from here, as much as possible
6563     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6564       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6565     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6566   }
6567
6568   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6569
6570   // Invert the operand order and use SHUFPS to match it.
6571   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6572                               getShuffleSHUFImmediate(SVOp), DAG);
6573 }
6574
6575 // Reduce a vector shuffle to zext.
6576 SDValue
6577 X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6578   // PMOVZX is only available from SSE41.
6579   if (!Subtarget->hasSSE41())
6580     return SDValue();
6581
6582   EVT VT = Op.getValueType();
6583
6584   // Only AVX2 support 256-bit vector integer extending.
6585   if (!Subtarget->hasAVX2() && VT.is256BitVector())
6586     return SDValue();
6587
6588   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6589   DebugLoc DL = Op.getDebugLoc();
6590   SDValue V1 = Op.getOperand(0);
6591   SDValue V2 = Op.getOperand(1);
6592   unsigned NumElems = VT.getVectorNumElements();
6593
6594   // Extending is an unary operation and the element type of the source vector
6595   // won't be equal to or larger than i64.
6596   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6597       VT.getVectorElementType() == MVT::i64)
6598     return SDValue();
6599
6600   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6601   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6602   while ((1U << Shift) < NumElems) {
6603     if (SVOp->getMaskElt(1U << Shift) == 1)
6604       break;
6605     Shift += 1;
6606     // The maximal ratio is 8, i.e. from i8 to i64.
6607     if (Shift > 3)
6608       return SDValue();
6609   }
6610
6611   // Check the shuffle mask.
6612   unsigned Mask = (1U << Shift) - 1;
6613   for (unsigned i = 0; i != NumElems; ++i) {
6614     int EltIdx = SVOp->getMaskElt(i);
6615     if ((i & Mask) != 0 && EltIdx != -1)
6616       return SDValue();
6617     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6618       return SDValue();
6619   }
6620
6621   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6622   EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6623   EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6624
6625   if (!isTypeLegal(NVT))
6626     return SDValue();
6627
6628   // Simplify the operand as it's prepared to be fed into shuffle.
6629   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6630   if (V1.getOpcode() == ISD::BITCAST &&
6631       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6632       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6633       V1.getOperand(0)
6634         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6635     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6636     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6637     ConstantSDNode *CIdx =
6638       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6639     // If it's foldable, i.e. normal load with single use, we will let code
6640     // selection to fold it. Otherwise, we will short the conversion sequence.
6641     if (CIdx && CIdx->getZExtValue() == 0 &&
6642         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6643       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6644   }
6645
6646   return DAG.getNode(ISD::BITCAST, DL, VT,
6647                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6648 }
6649
6650 SDValue
6651 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6652   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6653   EVT VT = Op.getValueType();
6654   DebugLoc dl = Op.getDebugLoc();
6655   SDValue V1 = Op.getOperand(0);
6656   SDValue V2 = Op.getOperand(1);
6657
6658   if (isZeroShuffle(SVOp))
6659     return getZeroVector(VT, Subtarget, DAG, dl);
6660
6661   // Handle splat operations
6662   if (SVOp->isSplat()) {
6663     unsigned NumElem = VT.getVectorNumElements();
6664     int Size = VT.getSizeInBits();
6665
6666     // Use vbroadcast whenever the splat comes from a foldable load
6667     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6668     if (Broadcast.getNode())
6669       return Broadcast;
6670
6671     // Handle splats by matching through known shuffle masks
6672     if ((Size == 128 && NumElem <= 4) ||
6673         (Size == 256 && NumElem < 8))
6674       return SDValue();
6675
6676     // All remaning splats are promoted to target supported vector shuffles.
6677     return PromoteSplat(SVOp, DAG);
6678   }
6679
6680   // Check integer expanding shuffles.
6681   SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6682   if (NewOp.getNode())
6683     return NewOp;
6684
6685   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6686   // do it!
6687   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6688       VT == MVT::v16i16 || VT == MVT::v32i8) {
6689     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6690     if (NewOp.getNode())
6691       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6692   } else if ((VT == MVT::v4i32 ||
6693              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6694     // FIXME: Figure out a cleaner way to do this.
6695     // Try to make use of movq to zero out the top part.
6696     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6697       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6698       if (NewOp.getNode()) {
6699         EVT NewVT = NewOp.getValueType();
6700         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6701                                NewVT, true, false))
6702           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6703                               DAG, Subtarget, dl);
6704       }
6705     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6706       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6707       if (NewOp.getNode()) {
6708         EVT NewVT = NewOp.getValueType();
6709         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6710           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6711                               DAG, Subtarget, dl);
6712       }
6713     }
6714   }
6715   return SDValue();
6716 }
6717
6718 SDValue
6719 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6720   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6721   SDValue V1 = Op.getOperand(0);
6722   SDValue V2 = Op.getOperand(1);
6723   EVT VT = Op.getValueType();
6724   DebugLoc dl = Op.getDebugLoc();
6725   unsigned NumElems = VT.getVectorNumElements();
6726   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6727   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6728   bool V1IsSplat = false;
6729   bool V2IsSplat = false;
6730   bool HasSSE2 = Subtarget->hasSSE2();
6731   bool HasAVX    = Subtarget->hasAVX();
6732   bool HasAVX2   = Subtarget->hasAVX2();
6733   MachineFunction &MF = DAG.getMachineFunction();
6734   bool OptForSize = MF.getFunction()->getFnAttributes().
6735     hasAttribute(Attributes::OptimizeForSize);
6736
6737   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6738
6739   if (V1IsUndef && V2IsUndef)
6740     return DAG.getUNDEF(VT);
6741
6742   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6743
6744   // Vector shuffle lowering takes 3 steps:
6745   //
6746   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6747   //    narrowing and commutation of operands should be handled.
6748   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6749   //    shuffle nodes.
6750   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6751   //    so the shuffle can be broken into other shuffles and the legalizer can
6752   //    try the lowering again.
6753   //
6754   // The general idea is that no vector_shuffle operation should be left to
6755   // be matched during isel, all of them must be converted to a target specific
6756   // node here.
6757
6758   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6759   // narrowing and commutation of operands should be handled. The actual code
6760   // doesn't include all of those, work in progress...
6761   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6762   if (NewOp.getNode())
6763     return NewOp;
6764
6765   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6766
6767   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6768   // unpckh_undef). Only use pshufd if speed is more important than size.
6769   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6770     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6771   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6772     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6773
6774   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6775       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6776     return getMOVDDup(Op, dl, V1, DAG);
6777
6778   if (isMOVHLPS_v_undef_Mask(M, VT))
6779     return getMOVHighToLow(Op, dl, DAG);
6780
6781   // Use to match splats
6782   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6783       (VT == MVT::v2f64 || VT == MVT::v2i64))
6784     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6785
6786   if (isPSHUFDMask(M, VT)) {
6787     // The actual implementation will match the mask in the if above and then
6788     // during isel it can match several different instructions, not only pshufd
6789     // as its name says, sad but true, emulate the behavior for now...
6790     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6791       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6792
6793     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6794
6795     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6796       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6797
6798     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6799       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6800
6801     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6802                                 TargetMask, DAG);
6803   }
6804
6805   // Check if this can be converted into a logical shift.
6806   bool isLeft = false;
6807   unsigned ShAmt = 0;
6808   SDValue ShVal;
6809   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6810   if (isShift && ShVal.hasOneUse()) {
6811     // If the shifted value has multiple uses, it may be cheaper to use
6812     // v_set0 + movlhps or movhlps, etc.
6813     EVT EltVT = VT.getVectorElementType();
6814     ShAmt *= EltVT.getSizeInBits();
6815     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6816   }
6817
6818   if (isMOVLMask(M, VT)) {
6819     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6820       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6821     if (!isMOVLPMask(M, VT)) {
6822       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6823         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6824
6825       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6826         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6827     }
6828   }
6829
6830   // FIXME: fold these into legal mask.
6831   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6832     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6833
6834   if (isMOVHLPSMask(M, VT))
6835     return getMOVHighToLow(Op, dl, DAG);
6836
6837   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6838     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6839
6840   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6841     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6842
6843   if (isMOVLPMask(M, VT))
6844     return getMOVLP(Op, dl, DAG, HasSSE2);
6845
6846   if (ShouldXformToMOVHLPS(M, VT) ||
6847       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6848     return CommuteVectorShuffle(SVOp, DAG);
6849
6850   if (isShift) {
6851     // No better options. Use a vshldq / vsrldq.
6852     EVT EltVT = VT.getVectorElementType();
6853     ShAmt *= EltVT.getSizeInBits();
6854     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6855   }
6856
6857   bool Commuted = false;
6858   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6859   // 1,1,1,1 -> v8i16 though.
6860   V1IsSplat = isSplatVector(V1.getNode());
6861   V2IsSplat = isSplatVector(V2.getNode());
6862
6863   // Canonicalize the splat or undef, if present, to be on the RHS.
6864   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6865     CommuteVectorShuffleMask(M, NumElems);
6866     std::swap(V1, V2);
6867     std::swap(V1IsSplat, V2IsSplat);
6868     Commuted = true;
6869   }
6870
6871   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6872     // Shuffling low element of v1 into undef, just return v1.
6873     if (V2IsUndef)
6874       return V1;
6875     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6876     // the instruction selector will not match, so get a canonical MOVL with
6877     // swapped operands to undo the commute.
6878     return getMOVL(DAG, dl, VT, V2, V1);
6879   }
6880
6881   if (isUNPCKLMask(M, VT, HasAVX2))
6882     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6883
6884   if (isUNPCKHMask(M, VT, HasAVX2))
6885     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6886
6887   if (V2IsSplat) {
6888     // Normalize mask so all entries that point to V2 points to its first
6889     // element then try to match unpck{h|l} again. If match, return a
6890     // new vector_shuffle with the corrected mask.p
6891     SmallVector<int, 8> NewMask(M.begin(), M.end());
6892     NormalizeMask(NewMask, NumElems);
6893     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6894       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6895     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6896       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6897   }
6898
6899   if (Commuted) {
6900     // Commute is back and try unpck* again.
6901     // FIXME: this seems wrong.
6902     CommuteVectorShuffleMask(M, NumElems);
6903     std::swap(V1, V2);
6904     std::swap(V1IsSplat, V2IsSplat);
6905     Commuted = false;
6906
6907     if (isUNPCKLMask(M, VT, HasAVX2))
6908       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6909
6910     if (isUNPCKHMask(M, VT, HasAVX2))
6911       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6912   }
6913
6914   // Normalize the node to match x86 shuffle ops if needed
6915   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6916     return CommuteVectorShuffle(SVOp, DAG);
6917
6918   // The checks below are all present in isShuffleMaskLegal, but they are
6919   // inlined here right now to enable us to directly emit target specific
6920   // nodes, and remove one by one until they don't return Op anymore.
6921
6922   if (isPALIGNRMask(M, VT, Subtarget))
6923     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6924                                 getShufflePALIGNRImmediate(SVOp),
6925                                 DAG);
6926
6927   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6928       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6929     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6930       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6931   }
6932
6933   if (isPSHUFHWMask(M, VT, HasAVX2))
6934     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6935                                 getShufflePSHUFHWImmediate(SVOp),
6936                                 DAG);
6937
6938   if (isPSHUFLWMask(M, VT, HasAVX2))
6939     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6940                                 getShufflePSHUFLWImmediate(SVOp),
6941                                 DAG);
6942
6943   if (isSHUFPMask(M, VT, HasAVX))
6944     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6945                                 getShuffleSHUFImmediate(SVOp), DAG);
6946
6947   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6948     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6949   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6950     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6951
6952   //===--------------------------------------------------------------------===//
6953   // Generate target specific nodes for 128 or 256-bit shuffles only
6954   // supported in the AVX instruction set.
6955   //
6956
6957   // Handle VMOVDDUPY permutations
6958   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6959     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6960
6961   // Handle VPERMILPS/D* permutations
6962   if (isVPERMILPMask(M, VT, HasAVX)) {
6963     if (HasAVX2 && VT == MVT::v8i32)
6964       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6965                                   getShuffleSHUFImmediate(SVOp), DAG);
6966     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6967                                 getShuffleSHUFImmediate(SVOp), DAG);
6968   }
6969
6970   // Handle VPERM2F128/VPERM2I128 permutations
6971   if (isVPERM2X128Mask(M, VT, HasAVX))
6972     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6973                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6974
6975   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6976   if (BlendOp.getNode())
6977     return BlendOp;
6978
6979   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6980     SmallVector<SDValue, 8> permclMask;
6981     for (unsigned i = 0; i != 8; ++i) {
6982       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6983     }
6984     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6985                                &permclMask[0], 8);
6986     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6987     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6988                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6989   }
6990
6991   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6992     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6993                                 getShuffleCLImmediate(SVOp), DAG);
6994
6995
6996   //===--------------------------------------------------------------------===//
6997   // Since no target specific shuffle was selected for this generic one,
6998   // lower it into other known shuffles. FIXME: this isn't true yet, but
6999   // this is the plan.
7000   //
7001
7002   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7003   if (VT == MVT::v8i16) {
7004     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7005     if (NewOp.getNode())
7006       return NewOp;
7007   }
7008
7009   if (VT == MVT::v16i8) {
7010     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7011     if (NewOp.getNode())
7012       return NewOp;
7013   }
7014
7015   if (VT == MVT::v32i8) {
7016     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7017     if (NewOp.getNode())
7018       return NewOp;
7019   }
7020
7021   // Handle all 128-bit wide vectors with 4 elements, and match them with
7022   // several different shuffle types.
7023   if (NumElems == 4 && VT.is128BitVector())
7024     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7025
7026   // Handle general 256-bit shuffles
7027   if (VT.is256BitVector())
7028     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7029
7030   return SDValue();
7031 }
7032
7033 SDValue
7034 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7035                                                 SelectionDAG &DAG) const {
7036   EVT VT = Op.getValueType();
7037   DebugLoc dl = Op.getDebugLoc();
7038
7039   if (!Op.getOperand(0).getValueType().is128BitVector())
7040     return SDValue();
7041
7042   if (VT.getSizeInBits() == 8) {
7043     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7044                                   Op.getOperand(0), Op.getOperand(1));
7045     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7046                                   DAG.getValueType(VT));
7047     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7048   }
7049
7050   if (VT.getSizeInBits() == 16) {
7051     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7052     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7053     if (Idx == 0)
7054       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7055                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7056                                      DAG.getNode(ISD::BITCAST, dl,
7057                                                  MVT::v4i32,
7058                                                  Op.getOperand(0)),
7059                                      Op.getOperand(1)));
7060     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7061                                   Op.getOperand(0), Op.getOperand(1));
7062     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7063                                   DAG.getValueType(VT));
7064     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7065   }
7066
7067   if (VT == MVT::f32) {
7068     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7069     // the result back to FR32 register. It's only worth matching if the
7070     // result has a single use which is a store or a bitcast to i32.  And in
7071     // the case of a store, it's not worth it if the index is a constant 0,
7072     // because a MOVSSmr can be used instead, which is smaller and faster.
7073     if (!Op.hasOneUse())
7074       return SDValue();
7075     SDNode *User = *Op.getNode()->use_begin();
7076     if ((User->getOpcode() != ISD::STORE ||
7077          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7078           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7079         (User->getOpcode() != ISD::BITCAST ||
7080          User->getValueType(0) != MVT::i32))
7081       return SDValue();
7082     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7083                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7084                                               Op.getOperand(0)),
7085                                               Op.getOperand(1));
7086     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7087   }
7088
7089   if (VT == MVT::i32 || VT == MVT::i64) {
7090     // ExtractPS/pextrq works with constant index.
7091     if (isa<ConstantSDNode>(Op.getOperand(1)))
7092       return Op;
7093   }
7094   return SDValue();
7095 }
7096
7097
7098 SDValue
7099 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7100                                            SelectionDAG &DAG) const {
7101   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7102     return SDValue();
7103
7104   SDValue Vec = Op.getOperand(0);
7105   EVT VecVT = Vec.getValueType();
7106
7107   // If this is a 256-bit vector result, first extract the 128-bit vector and
7108   // then extract the element from the 128-bit vector.
7109   if (VecVT.is256BitVector()) {
7110     DebugLoc dl = Op.getNode()->getDebugLoc();
7111     unsigned NumElems = VecVT.getVectorNumElements();
7112     SDValue Idx = Op.getOperand(1);
7113     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7114
7115     // Get the 128-bit vector.
7116     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7117
7118     if (IdxVal >= NumElems/2)
7119       IdxVal -= NumElems/2;
7120     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7121                        DAG.getConstant(IdxVal, MVT::i32));
7122   }
7123
7124   assert(VecVT.is128BitVector() && "Unexpected vector length");
7125
7126   if (Subtarget->hasSSE41()) {
7127     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7128     if (Res.getNode())
7129       return Res;
7130   }
7131
7132   EVT VT = Op.getValueType();
7133   DebugLoc dl = Op.getDebugLoc();
7134   // TODO: handle v16i8.
7135   if (VT.getSizeInBits() == 16) {
7136     SDValue Vec = Op.getOperand(0);
7137     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7138     if (Idx == 0)
7139       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7140                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7141                                      DAG.getNode(ISD::BITCAST, dl,
7142                                                  MVT::v4i32, Vec),
7143                                      Op.getOperand(1)));
7144     // Transform it so it match pextrw which produces a 32-bit result.
7145     EVT EltVT = MVT::i32;
7146     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7147                                   Op.getOperand(0), Op.getOperand(1));
7148     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7149                                   DAG.getValueType(VT));
7150     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7151   }
7152
7153   if (VT.getSizeInBits() == 32) {
7154     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7155     if (Idx == 0)
7156       return Op;
7157
7158     // SHUFPS the element to the lowest double word, then movss.
7159     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7160     EVT VVT = Op.getOperand(0).getValueType();
7161     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7162                                        DAG.getUNDEF(VVT), Mask);
7163     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7164                        DAG.getIntPtrConstant(0));
7165   }
7166
7167   if (VT.getSizeInBits() == 64) {
7168     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7169     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7170     //        to match extract_elt for f64.
7171     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7172     if (Idx == 0)
7173       return Op;
7174
7175     // UNPCKHPD the element to the lowest double word, then movsd.
7176     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7177     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7178     int Mask[2] = { 1, -1 };
7179     EVT VVT = Op.getOperand(0).getValueType();
7180     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7181                                        DAG.getUNDEF(VVT), Mask);
7182     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7183                        DAG.getIntPtrConstant(0));
7184   }
7185
7186   return SDValue();
7187 }
7188
7189 SDValue
7190 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7191                                                SelectionDAG &DAG) const {
7192   EVT VT = Op.getValueType();
7193   EVT EltVT = VT.getVectorElementType();
7194   DebugLoc dl = Op.getDebugLoc();
7195
7196   SDValue N0 = Op.getOperand(0);
7197   SDValue N1 = Op.getOperand(1);
7198   SDValue N2 = Op.getOperand(2);
7199
7200   if (!VT.is128BitVector())
7201     return SDValue();
7202
7203   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7204       isa<ConstantSDNode>(N2)) {
7205     unsigned Opc;
7206     if (VT == MVT::v8i16)
7207       Opc = X86ISD::PINSRW;
7208     else if (VT == MVT::v16i8)
7209       Opc = X86ISD::PINSRB;
7210     else
7211       Opc = X86ISD::PINSRB;
7212
7213     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7214     // argument.
7215     if (N1.getValueType() != MVT::i32)
7216       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7217     if (N2.getValueType() != MVT::i32)
7218       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7219     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7220   }
7221
7222   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7223     // Bits [7:6] of the constant are the source select.  This will always be
7224     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7225     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7226     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7227     // Bits [5:4] of the constant are the destination select.  This is the
7228     //  value of the incoming immediate.
7229     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7230     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7231     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7232     // Create this as a scalar to vector..
7233     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7234     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7235   }
7236
7237   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7238     // PINSR* works with constant index.
7239     return Op;
7240   }
7241   return SDValue();
7242 }
7243
7244 SDValue
7245 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7246   EVT VT = Op.getValueType();
7247   EVT EltVT = VT.getVectorElementType();
7248
7249   DebugLoc dl = Op.getDebugLoc();
7250   SDValue N0 = Op.getOperand(0);
7251   SDValue N1 = Op.getOperand(1);
7252   SDValue N2 = Op.getOperand(2);
7253
7254   // If this is a 256-bit vector result, first extract the 128-bit vector,
7255   // insert the element into the extracted half and then place it back.
7256   if (VT.is256BitVector()) {
7257     if (!isa<ConstantSDNode>(N2))
7258       return SDValue();
7259
7260     // Get the desired 128-bit vector half.
7261     unsigned NumElems = VT.getVectorNumElements();
7262     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7263     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7264
7265     // Insert the element into the desired half.
7266     bool Upper = IdxVal >= NumElems/2;
7267     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7268                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7269
7270     // Insert the changed part back to the 256-bit vector
7271     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7272   }
7273
7274   if (Subtarget->hasSSE41())
7275     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7276
7277   if (EltVT == MVT::i8)
7278     return SDValue();
7279
7280   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7281     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7282     // as its second argument.
7283     if (N1.getValueType() != MVT::i32)
7284       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7285     if (N2.getValueType() != MVT::i32)
7286       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7287     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7288   }
7289   return SDValue();
7290 }
7291
7292 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7293   LLVMContext *Context = DAG.getContext();
7294   DebugLoc dl = Op.getDebugLoc();
7295   EVT OpVT = Op.getValueType();
7296
7297   // If this is a 256-bit vector result, first insert into a 128-bit
7298   // vector and then insert into the 256-bit vector.
7299   if (!OpVT.is128BitVector()) {
7300     // Insert into a 128-bit vector.
7301     EVT VT128 = EVT::getVectorVT(*Context,
7302                                  OpVT.getVectorElementType(),
7303                                  OpVT.getVectorNumElements() / 2);
7304
7305     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7306
7307     // Insert the 128-bit vector.
7308     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7309   }
7310
7311   if (OpVT == MVT::v1i64 &&
7312       Op.getOperand(0).getValueType() == MVT::i64)
7313     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7314
7315   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7316   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7317   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7318                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7319 }
7320
7321 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7322 // a simple subregister reference or explicit instructions to grab
7323 // upper bits of a vector.
7324 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7325                                       SelectionDAG &DAG) {
7326   if (Subtarget->hasAVX()) {
7327     DebugLoc dl = Op.getNode()->getDebugLoc();
7328     SDValue Vec = Op.getNode()->getOperand(0);
7329     SDValue Idx = Op.getNode()->getOperand(1);
7330
7331     if (Op.getNode()->getValueType(0).is128BitVector() &&
7332         Vec.getNode()->getValueType(0).is256BitVector() &&
7333         isa<ConstantSDNode>(Idx)) {
7334       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7335       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7336     }
7337   }
7338   return SDValue();
7339 }
7340
7341 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7342 // simple superregister reference or explicit instructions to insert
7343 // the upper bits of a vector.
7344 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7345                                      SelectionDAG &DAG) {
7346   if (Subtarget->hasAVX()) {
7347     DebugLoc dl = Op.getNode()->getDebugLoc();
7348     SDValue Vec = Op.getNode()->getOperand(0);
7349     SDValue SubVec = Op.getNode()->getOperand(1);
7350     SDValue Idx = Op.getNode()->getOperand(2);
7351
7352     if (Op.getNode()->getValueType(0).is256BitVector() &&
7353         SubVec.getNode()->getValueType(0).is128BitVector() &&
7354         isa<ConstantSDNode>(Idx)) {
7355       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7356       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7357     }
7358   }
7359   return SDValue();
7360 }
7361
7362 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7363 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7364 // one of the above mentioned nodes. It has to be wrapped because otherwise
7365 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7366 // be used to form addressing mode. These wrapped nodes will be selected
7367 // into MOV32ri.
7368 SDValue
7369 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7370   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7371
7372   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7373   // global base reg.
7374   unsigned char OpFlag = 0;
7375   unsigned WrapperKind = X86ISD::Wrapper;
7376   CodeModel::Model M = getTargetMachine().getCodeModel();
7377
7378   if (Subtarget->isPICStyleRIPRel() &&
7379       (M == CodeModel::Small || M == CodeModel::Kernel))
7380     WrapperKind = X86ISD::WrapperRIP;
7381   else if (Subtarget->isPICStyleGOT())
7382     OpFlag = X86II::MO_GOTOFF;
7383   else if (Subtarget->isPICStyleStubPIC())
7384     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7385
7386   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7387                                              CP->getAlignment(),
7388                                              CP->getOffset(), OpFlag);
7389   DebugLoc DL = CP->getDebugLoc();
7390   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7391   // With PIC, the address is actually $g + Offset.
7392   if (OpFlag) {
7393     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7394                          DAG.getNode(X86ISD::GlobalBaseReg,
7395                                      DebugLoc(), getPointerTy()),
7396                          Result);
7397   }
7398
7399   return Result;
7400 }
7401
7402 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7403   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7404
7405   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7406   // global base reg.
7407   unsigned char OpFlag = 0;
7408   unsigned WrapperKind = X86ISD::Wrapper;
7409   CodeModel::Model M = getTargetMachine().getCodeModel();
7410
7411   if (Subtarget->isPICStyleRIPRel() &&
7412       (M == CodeModel::Small || M == CodeModel::Kernel))
7413     WrapperKind = X86ISD::WrapperRIP;
7414   else if (Subtarget->isPICStyleGOT())
7415     OpFlag = X86II::MO_GOTOFF;
7416   else if (Subtarget->isPICStyleStubPIC())
7417     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7418
7419   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7420                                           OpFlag);
7421   DebugLoc DL = JT->getDebugLoc();
7422   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7423
7424   // With PIC, the address is actually $g + Offset.
7425   if (OpFlag)
7426     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7427                          DAG.getNode(X86ISD::GlobalBaseReg,
7428                                      DebugLoc(), getPointerTy()),
7429                          Result);
7430
7431   return Result;
7432 }
7433
7434 SDValue
7435 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7436   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7437
7438   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7439   // global base reg.
7440   unsigned char OpFlag = 0;
7441   unsigned WrapperKind = X86ISD::Wrapper;
7442   CodeModel::Model M = getTargetMachine().getCodeModel();
7443
7444   if (Subtarget->isPICStyleRIPRel() &&
7445       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7446     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7447       OpFlag = X86II::MO_GOTPCREL;
7448     WrapperKind = X86ISD::WrapperRIP;
7449   } else if (Subtarget->isPICStyleGOT()) {
7450     OpFlag = X86II::MO_GOT;
7451   } else if (Subtarget->isPICStyleStubPIC()) {
7452     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7453   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7454     OpFlag = X86II::MO_DARWIN_NONLAZY;
7455   }
7456
7457   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7458
7459   DebugLoc DL = Op.getDebugLoc();
7460   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7461
7462
7463   // With PIC, the address is actually $g + Offset.
7464   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7465       !Subtarget->is64Bit()) {
7466     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7467                          DAG.getNode(X86ISD::GlobalBaseReg,
7468                                      DebugLoc(), getPointerTy()),
7469                          Result);
7470   }
7471
7472   // For symbols that require a load from a stub to get the address, emit the
7473   // load.
7474   if (isGlobalStubReference(OpFlag))
7475     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7476                          MachinePointerInfo::getGOT(), false, false, false, 0);
7477
7478   return Result;
7479 }
7480
7481 SDValue
7482 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7483   // Create the TargetBlockAddressAddress node.
7484   unsigned char OpFlags =
7485     Subtarget->ClassifyBlockAddressReference();
7486   CodeModel::Model M = getTargetMachine().getCodeModel();
7487   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7488   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7489   DebugLoc dl = Op.getDebugLoc();
7490   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7491                                              OpFlags);
7492
7493   if (Subtarget->isPICStyleRIPRel() &&
7494       (M == CodeModel::Small || M == CodeModel::Kernel))
7495     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7496   else
7497     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7498
7499   // With PIC, the address is actually $g + Offset.
7500   if (isGlobalRelativeToPICBase(OpFlags)) {
7501     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7502                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7503                          Result);
7504   }
7505
7506   return Result;
7507 }
7508
7509 SDValue
7510 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7511                                       int64_t Offset,
7512                                       SelectionDAG &DAG) const {
7513   // Create the TargetGlobalAddress node, folding in the constant
7514   // offset if it is legal.
7515   unsigned char OpFlags =
7516     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7517   CodeModel::Model M = getTargetMachine().getCodeModel();
7518   SDValue Result;
7519   if (OpFlags == X86II::MO_NO_FLAG &&
7520       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7521     // A direct static reference to a global.
7522     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7523     Offset = 0;
7524   } else {
7525     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7526   }
7527
7528   if (Subtarget->isPICStyleRIPRel() &&
7529       (M == CodeModel::Small || M == CodeModel::Kernel))
7530     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7531   else
7532     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7533
7534   // With PIC, the address is actually $g + Offset.
7535   if (isGlobalRelativeToPICBase(OpFlags)) {
7536     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7537                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7538                          Result);
7539   }
7540
7541   // For globals that require a load from a stub to get the address, emit the
7542   // load.
7543   if (isGlobalStubReference(OpFlags))
7544     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7545                          MachinePointerInfo::getGOT(), false, false, false, 0);
7546
7547   // If there was a non-zero offset that we didn't fold, create an explicit
7548   // addition for it.
7549   if (Offset != 0)
7550     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7551                          DAG.getConstant(Offset, getPointerTy()));
7552
7553   return Result;
7554 }
7555
7556 SDValue
7557 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7558   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7559   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7560   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7561 }
7562
7563 static SDValue
7564 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7565            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7566            unsigned char OperandFlags, bool LocalDynamic = false) {
7567   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7568   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7569   DebugLoc dl = GA->getDebugLoc();
7570   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7571                                            GA->getValueType(0),
7572                                            GA->getOffset(),
7573                                            OperandFlags);
7574
7575   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7576                                            : X86ISD::TLSADDR;
7577
7578   if (InFlag) {
7579     SDValue Ops[] = { Chain,  TGA, *InFlag };
7580     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7581   } else {
7582     SDValue Ops[]  = { Chain, TGA };
7583     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7584   }
7585
7586   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7587   MFI->setAdjustsStack(true);
7588
7589   SDValue Flag = Chain.getValue(1);
7590   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7591 }
7592
7593 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7594 static SDValue
7595 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7596                                 const EVT PtrVT) {
7597   SDValue InFlag;
7598   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7599   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7600                                    DAG.getNode(X86ISD::GlobalBaseReg,
7601                                                DebugLoc(), PtrVT), InFlag);
7602   InFlag = Chain.getValue(1);
7603
7604   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7605 }
7606
7607 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7608 static SDValue
7609 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7610                                 const EVT PtrVT) {
7611   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7612                     X86::RAX, X86II::MO_TLSGD);
7613 }
7614
7615 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7616                                            SelectionDAG &DAG,
7617                                            const EVT PtrVT,
7618                                            bool is64Bit) {
7619   DebugLoc dl = GA->getDebugLoc();
7620
7621   // Get the start address of the TLS block for this module.
7622   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7623       .getInfo<X86MachineFunctionInfo>();
7624   MFI->incNumLocalDynamicTLSAccesses();
7625
7626   SDValue Base;
7627   if (is64Bit) {
7628     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7629                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7630   } else {
7631     SDValue InFlag;
7632     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7633         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7634     InFlag = Chain.getValue(1);
7635     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7636                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7637   }
7638
7639   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7640   // of Base.
7641
7642   // Build x@dtpoff.
7643   unsigned char OperandFlags = X86II::MO_DTPOFF;
7644   unsigned WrapperKind = X86ISD::Wrapper;
7645   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7646                                            GA->getValueType(0),
7647                                            GA->getOffset(), OperandFlags);
7648   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7649
7650   // Add x@dtpoff with the base.
7651   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7652 }
7653
7654 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7655 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7656                                    const EVT PtrVT, TLSModel::Model model,
7657                                    bool is64Bit, bool isPIC) {
7658   DebugLoc dl = GA->getDebugLoc();
7659
7660   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7661   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7662                                                          is64Bit ? 257 : 256));
7663
7664   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7665                                       DAG.getIntPtrConstant(0),
7666                                       MachinePointerInfo(Ptr),
7667                                       false, false, false, 0);
7668
7669   unsigned char OperandFlags = 0;
7670   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7671   // initialexec.
7672   unsigned WrapperKind = X86ISD::Wrapper;
7673   if (model == TLSModel::LocalExec) {
7674     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7675   } else if (model == TLSModel::InitialExec) {
7676     if (is64Bit) {
7677       OperandFlags = X86II::MO_GOTTPOFF;
7678       WrapperKind = X86ISD::WrapperRIP;
7679     } else {
7680       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7681     }
7682   } else {
7683     llvm_unreachable("Unexpected model");
7684   }
7685
7686   // emit "addl x@ntpoff,%eax" (local exec)
7687   // or "addl x@indntpoff,%eax" (initial exec)
7688   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7689   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7690                                            GA->getValueType(0),
7691                                            GA->getOffset(), OperandFlags);
7692   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7693
7694   if (model == TLSModel::InitialExec) {
7695     if (isPIC && !is64Bit) {
7696       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7697                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7698                            Offset);
7699     }
7700
7701     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7702                          MachinePointerInfo::getGOT(), false, false, false,
7703                          0);
7704   }
7705
7706   // The address of the thread local variable is the add of the thread
7707   // pointer with the offset of the variable.
7708   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7709 }
7710
7711 SDValue
7712 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7713
7714   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7715   const GlobalValue *GV = GA->getGlobal();
7716
7717   if (Subtarget->isTargetELF()) {
7718     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7719
7720     switch (model) {
7721       case TLSModel::GeneralDynamic:
7722         if (Subtarget->is64Bit())
7723           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7724         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7725       case TLSModel::LocalDynamic:
7726         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7727                                            Subtarget->is64Bit());
7728       case TLSModel::InitialExec:
7729       case TLSModel::LocalExec:
7730         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7731                                    Subtarget->is64Bit(),
7732                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7733     }
7734     llvm_unreachable("Unknown TLS model.");
7735   }
7736
7737   if (Subtarget->isTargetDarwin()) {
7738     // Darwin only has one model of TLS.  Lower to that.
7739     unsigned char OpFlag = 0;
7740     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7741                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7742
7743     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7744     // global base reg.
7745     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7746                   !Subtarget->is64Bit();
7747     if (PIC32)
7748       OpFlag = X86II::MO_TLVP_PIC_BASE;
7749     else
7750       OpFlag = X86II::MO_TLVP;
7751     DebugLoc DL = Op.getDebugLoc();
7752     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7753                                                 GA->getValueType(0),
7754                                                 GA->getOffset(), OpFlag);
7755     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7756
7757     // With PIC32, the address is actually $g + Offset.
7758     if (PIC32)
7759       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7760                            DAG.getNode(X86ISD::GlobalBaseReg,
7761                                        DebugLoc(), getPointerTy()),
7762                            Offset);
7763
7764     // Lowering the machine isd will make sure everything is in the right
7765     // location.
7766     SDValue Chain = DAG.getEntryNode();
7767     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7768     SDValue Args[] = { Chain, Offset };
7769     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7770
7771     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7772     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7773     MFI->setAdjustsStack(true);
7774
7775     // And our return value (tls address) is in the standard call return value
7776     // location.
7777     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7778     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7779                               Chain.getValue(1));
7780   }
7781
7782   if (Subtarget->isTargetWindows()) {
7783     // Just use the implicit TLS architecture
7784     // Need to generate someting similar to:
7785     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7786     //                                  ; from TEB
7787     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7788     //   mov     rcx, qword [rdx+rcx*8]
7789     //   mov     eax, .tls$:tlsvar
7790     //   [rax+rcx] contains the address
7791     // Windows 64bit: gs:0x58
7792     // Windows 32bit: fs:__tls_array
7793
7794     // If GV is an alias then use the aliasee for determining
7795     // thread-localness.
7796     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7797       GV = GA->resolveAliasedGlobal(false);
7798     DebugLoc dl = GA->getDebugLoc();
7799     SDValue Chain = DAG.getEntryNode();
7800
7801     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7802     // %gs:0x58 (64-bit).
7803     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7804                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7805                                                              256)
7806                                         : Type::getInt32PtrTy(*DAG.getContext(),
7807                                                               257));
7808
7809     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7810                                         Subtarget->is64Bit()
7811                                         ? DAG.getIntPtrConstant(0x58)
7812                                         : DAG.getExternalSymbol("_tls_array",
7813                                                                 getPointerTy()),
7814                                         MachinePointerInfo(Ptr),
7815                                         false, false, false, 0);
7816
7817     // Load the _tls_index variable
7818     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7819     if (Subtarget->is64Bit())
7820       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7821                            IDX, MachinePointerInfo(), MVT::i32,
7822                            false, false, 0);
7823     else
7824       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7825                         false, false, false, 0);
7826
7827     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize(0)),
7828                                     getPointerTy());
7829     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7830
7831     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7832     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7833                       false, false, false, 0);
7834
7835     // Get the offset of start of .tls section
7836     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7837                                              GA->getValueType(0),
7838                                              GA->getOffset(), X86II::MO_SECREL);
7839     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7840
7841     // The address of the thread local variable is the add of the thread
7842     // pointer with the offset of the variable.
7843     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7844   }
7845
7846   llvm_unreachable("TLS not implemented for this target.");
7847 }
7848
7849
7850 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7851 /// and take a 2 x i32 value to shift plus a shift amount.
7852 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7853   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7854   EVT VT = Op.getValueType();
7855   unsigned VTBits = VT.getSizeInBits();
7856   DebugLoc dl = Op.getDebugLoc();
7857   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7858   SDValue ShOpLo = Op.getOperand(0);
7859   SDValue ShOpHi = Op.getOperand(1);
7860   SDValue ShAmt  = Op.getOperand(2);
7861   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7862                                      DAG.getConstant(VTBits - 1, MVT::i8))
7863                        : DAG.getConstant(0, VT);
7864
7865   SDValue Tmp2, Tmp3;
7866   if (Op.getOpcode() == ISD::SHL_PARTS) {
7867     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7868     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7869   } else {
7870     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7871     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7872   }
7873
7874   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7875                                 DAG.getConstant(VTBits, MVT::i8));
7876   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7877                              AndNode, DAG.getConstant(0, MVT::i8));
7878
7879   SDValue Hi, Lo;
7880   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7881   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7882   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7883
7884   if (Op.getOpcode() == ISD::SHL_PARTS) {
7885     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7886     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7887   } else {
7888     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7889     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7890   }
7891
7892   SDValue Ops[2] = { Lo, Hi };
7893   return DAG.getMergeValues(Ops, 2, dl);
7894 }
7895
7896 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7897                                            SelectionDAG &DAG) const {
7898   EVT SrcVT = Op.getOperand(0).getValueType();
7899
7900   if (SrcVT.isVector())
7901     return SDValue();
7902
7903   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7904          "Unknown SINT_TO_FP to lower!");
7905
7906   // These are really Legal; return the operand so the caller accepts it as
7907   // Legal.
7908   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7909     return Op;
7910   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7911       Subtarget->is64Bit()) {
7912     return Op;
7913   }
7914
7915   DebugLoc dl = Op.getDebugLoc();
7916   unsigned Size = SrcVT.getSizeInBits()/8;
7917   MachineFunction &MF = DAG.getMachineFunction();
7918   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7919   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7920   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7921                                StackSlot,
7922                                MachinePointerInfo::getFixedStack(SSFI),
7923                                false, false, 0);
7924   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7925 }
7926
7927 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7928                                      SDValue StackSlot,
7929                                      SelectionDAG &DAG) const {
7930   // Build the FILD
7931   DebugLoc DL = Op.getDebugLoc();
7932   SDVTList Tys;
7933   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7934   if (useSSE)
7935     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7936   else
7937     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7938
7939   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7940
7941   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7942   MachineMemOperand *MMO;
7943   if (FI) {
7944     int SSFI = FI->getIndex();
7945     MMO =
7946       DAG.getMachineFunction()
7947       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7948                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7949   } else {
7950     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7951     StackSlot = StackSlot.getOperand(1);
7952   }
7953   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7954   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7955                                            X86ISD::FILD, DL,
7956                                            Tys, Ops, array_lengthof(Ops),
7957                                            SrcVT, MMO);
7958
7959   if (useSSE) {
7960     Chain = Result.getValue(1);
7961     SDValue InFlag = Result.getValue(2);
7962
7963     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7964     // shouldn't be necessary except that RFP cannot be live across
7965     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7966     MachineFunction &MF = DAG.getMachineFunction();
7967     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7968     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7969     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7970     Tys = DAG.getVTList(MVT::Other);
7971     SDValue Ops[] = {
7972       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7973     };
7974     MachineMemOperand *MMO =
7975       DAG.getMachineFunction()
7976       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7977                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7978
7979     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7980                                     Ops, array_lengthof(Ops),
7981                                     Op.getValueType(), MMO);
7982     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7983                          MachinePointerInfo::getFixedStack(SSFI),
7984                          false, false, false, 0);
7985   }
7986
7987   return Result;
7988 }
7989
7990 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7991 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7992                                                SelectionDAG &DAG) const {
7993   // This algorithm is not obvious. Here it is what we're trying to output:
7994   /*
7995      movq       %rax,  %xmm0
7996      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7997      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7998      #ifdef __SSE3__
7999        haddpd   %xmm0, %xmm0
8000      #else
8001        pshufd   $0x4e, %xmm0, %xmm1
8002        addpd    %xmm1, %xmm0
8003      #endif
8004   */
8005
8006   DebugLoc dl = Op.getDebugLoc();
8007   LLVMContext *Context = DAG.getContext();
8008
8009   // Build some magic constants.
8010   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8011   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8012   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8013
8014   SmallVector<Constant*,2> CV1;
8015   CV1.push_back(
8016         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8017   CV1.push_back(
8018         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8019   Constant *C1 = ConstantVector::get(CV1);
8020   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8021
8022   // Load the 64-bit value into an XMM register.
8023   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8024                             Op.getOperand(0));
8025   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8026                               MachinePointerInfo::getConstantPool(),
8027                               false, false, false, 16);
8028   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8029                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8030                               CLod0);
8031
8032   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8033                               MachinePointerInfo::getConstantPool(),
8034                               false, false, false, 16);
8035   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8036   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8037   SDValue Result;
8038
8039   if (Subtarget->hasSSE3()) {
8040     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8041     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8042   } else {
8043     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8044     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8045                                            S2F, 0x4E, DAG);
8046     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8047                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8048                          Sub);
8049   }
8050
8051   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8052                      DAG.getIntPtrConstant(0));
8053 }
8054
8055 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8056 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8057                                                SelectionDAG &DAG) const {
8058   DebugLoc dl = Op.getDebugLoc();
8059   // FP constant to bias correct the final result.
8060   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8061                                    MVT::f64);
8062
8063   // Load the 32-bit value into an XMM register.
8064   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8065                              Op.getOperand(0));
8066
8067   // Zero out the upper parts of the register.
8068   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8069
8070   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8071                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8072                      DAG.getIntPtrConstant(0));
8073
8074   // Or the load with the bias.
8075   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8076                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8077                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8078                                                    MVT::v2f64, Load)),
8079                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8080                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8081                                                    MVT::v2f64, Bias)));
8082   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8083                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8084                    DAG.getIntPtrConstant(0));
8085
8086   // Subtract the bias.
8087   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8088
8089   // Handle final rounding.
8090   EVT DestVT = Op.getValueType();
8091
8092   if (DestVT.bitsLT(MVT::f64))
8093     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8094                        DAG.getIntPtrConstant(0));
8095   if (DestVT.bitsGT(MVT::f64))
8096     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8097
8098   // Handle final rounding.
8099   return Sub;
8100 }
8101
8102 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8103                                                SelectionDAG &DAG) const {
8104   SDValue N0 = Op.getOperand(0);
8105   EVT SVT = N0.getValueType();
8106   DebugLoc dl = Op.getDebugLoc();
8107
8108   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8109           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8110          "Custom UINT_TO_FP is not supported!");
8111
8112   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements());
8113   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8114                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8115 }
8116
8117 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8118                                            SelectionDAG &DAG) const {
8119   SDValue N0 = Op.getOperand(0);
8120   DebugLoc dl = Op.getDebugLoc();
8121
8122   if (Op.getValueType().isVector())
8123     return lowerUINT_TO_FP_vec(Op, DAG);
8124
8125   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8126   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8127   // the optimization here.
8128   if (DAG.SignBitIsZero(N0))
8129     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8130
8131   EVT SrcVT = N0.getValueType();
8132   EVT DstVT = Op.getValueType();
8133   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8134     return LowerUINT_TO_FP_i64(Op, DAG);
8135   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8136     return LowerUINT_TO_FP_i32(Op, DAG);
8137   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8138     return SDValue();
8139
8140   // Make a 64-bit buffer, and use it to build an FILD.
8141   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8142   if (SrcVT == MVT::i32) {
8143     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8144     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8145                                      getPointerTy(), StackSlot, WordOff);
8146     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8147                                   StackSlot, MachinePointerInfo(),
8148                                   false, false, 0);
8149     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8150                                   OffsetSlot, MachinePointerInfo(),
8151                                   false, false, 0);
8152     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8153     return Fild;
8154   }
8155
8156   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8157   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8158                                StackSlot, MachinePointerInfo(),
8159                                false, false, 0);
8160   // For i64 source, we need to add the appropriate power of 2 if the input
8161   // was negative.  This is the same as the optimization in
8162   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8163   // we must be careful to do the computation in x87 extended precision, not
8164   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8165   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8166   MachineMemOperand *MMO =
8167     DAG.getMachineFunction()
8168     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8169                           MachineMemOperand::MOLoad, 8, 8);
8170
8171   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8172   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8173   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8174                                          MVT::i64, MMO);
8175
8176   APInt FF(32, 0x5F800000ULL);
8177
8178   // Check whether the sign bit is set.
8179   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8180                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8181                                  ISD::SETLT);
8182
8183   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8184   SDValue FudgePtr = DAG.getConstantPool(
8185                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8186                                          getPointerTy());
8187
8188   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8189   SDValue Zero = DAG.getIntPtrConstant(0);
8190   SDValue Four = DAG.getIntPtrConstant(4);
8191   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8192                                Zero, Four);
8193   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8194
8195   // Load the value out, extending it from f32 to f80.
8196   // FIXME: Avoid the extend by constructing the right constant pool?
8197   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8198                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8199                                  MVT::f32, false, false, 4);
8200   // Extend everything to 80 bits to force it to be done on x87.
8201   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8202   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8203 }
8204
8205 std::pair<SDValue,SDValue> X86TargetLowering::
8206 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8207   DebugLoc DL = Op.getDebugLoc();
8208
8209   EVT DstTy = Op.getValueType();
8210
8211   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8212     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8213     DstTy = MVT::i64;
8214   }
8215
8216   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8217          DstTy.getSimpleVT() >= MVT::i16 &&
8218          "Unknown FP_TO_INT to lower!");
8219
8220   // These are really Legal.
8221   if (DstTy == MVT::i32 &&
8222       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8223     return std::make_pair(SDValue(), SDValue());
8224   if (Subtarget->is64Bit() &&
8225       DstTy == MVT::i64 &&
8226       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8227     return std::make_pair(SDValue(), SDValue());
8228
8229   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8230   // stack slot, or into the FTOL runtime function.
8231   MachineFunction &MF = DAG.getMachineFunction();
8232   unsigned MemSize = DstTy.getSizeInBits()/8;
8233   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8234   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8235
8236   unsigned Opc;
8237   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8238     Opc = X86ISD::WIN_FTOL;
8239   else
8240     switch (DstTy.getSimpleVT().SimpleTy) {
8241     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8242     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8243     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8244     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8245     }
8246
8247   SDValue Chain = DAG.getEntryNode();
8248   SDValue Value = Op.getOperand(0);
8249   EVT TheVT = Op.getOperand(0).getValueType();
8250   // FIXME This causes a redundant load/store if the SSE-class value is already
8251   // in memory, such as if it is on the callstack.
8252   if (isScalarFPTypeInSSEReg(TheVT)) {
8253     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8254     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8255                          MachinePointerInfo::getFixedStack(SSFI),
8256                          false, false, 0);
8257     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8258     SDValue Ops[] = {
8259       Chain, StackSlot, DAG.getValueType(TheVT)
8260     };
8261
8262     MachineMemOperand *MMO =
8263       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8264                               MachineMemOperand::MOLoad, MemSize, MemSize);
8265     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8266                                     DstTy, MMO);
8267     Chain = Value.getValue(1);
8268     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8269     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8270   }
8271
8272   MachineMemOperand *MMO =
8273     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8274                             MachineMemOperand::MOStore, MemSize, MemSize);
8275
8276   if (Opc != X86ISD::WIN_FTOL) {
8277     // Build the FP_TO_INT*_IN_MEM
8278     SDValue Ops[] = { Chain, Value, StackSlot };
8279     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8280                                            Ops, 3, DstTy, MMO);
8281     return std::make_pair(FIST, StackSlot);
8282   } else {
8283     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8284       DAG.getVTList(MVT::Other, MVT::Glue),
8285       Chain, Value);
8286     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8287       MVT::i32, ftol.getValue(1));
8288     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8289       MVT::i32, eax.getValue(2));
8290     SDValue Ops[] = { eax, edx };
8291     SDValue pair = IsReplace
8292       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8293       : DAG.getMergeValues(Ops, 2, DL);
8294     return std::make_pair(pair, SDValue());
8295   }
8296 }
8297
8298 SDValue X86TargetLowering::lowerZERO_EXTEND(SDValue Op, SelectionDAG &DAG) const {
8299   DebugLoc DL = Op.getDebugLoc();
8300   EVT VT = Op.getValueType();
8301   SDValue In = Op.getOperand(0);
8302   EVT SVT = In.getValueType();
8303
8304   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8305       VT.getVectorNumElements() != SVT.getVectorNumElements())
8306     return SDValue();
8307
8308   assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8309
8310   // AVX2 has better support of integer extending.
8311   if (Subtarget->hasAVX2())
8312     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8313
8314   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8315   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8316   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8317                            DAG.getVectorShuffle(MVT::v8i16, DL, In, DAG.getUNDEF(MVT::v8i16), &Mask[0]));
8318
8319   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8320 }
8321
8322 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8323   DebugLoc DL = Op.getDebugLoc();
8324   EVT VT = Op.getValueType();
8325   EVT SVT = Op.getOperand(0).getValueType();
8326
8327   if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8328       VT.getVectorNumElements() != SVT.getVectorNumElements())
8329     return SDValue();
8330
8331   assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8332
8333   unsigned NumElems = VT.getVectorNumElements();
8334   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8335                              NumElems * 2);
8336
8337   SDValue In = Op.getOperand(0);
8338   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8339   // Prepare truncation shuffle mask
8340   for (unsigned i = 0; i != NumElems; ++i)
8341     MaskVec[i] = i * 2;
8342   SDValue V = DAG.getVectorShuffle(NVT, DL,
8343                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8344                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8345   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8346                      DAG.getIntPtrConstant(0));
8347 }
8348
8349 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8350                                            SelectionDAG &DAG) const {
8351   if (Op.getValueType().isVector()) {
8352     if (Op.getValueType() == MVT::v8i16)
8353       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8354                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8355                                      MVT::v8i32, Op.getOperand(0)));
8356     return SDValue();
8357   }
8358
8359   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8360     /*IsSigned=*/ true, /*IsReplace=*/ false);
8361   SDValue FIST = Vals.first, StackSlot = Vals.second;
8362   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8363   if (FIST.getNode() == 0) return Op;
8364
8365   if (StackSlot.getNode())
8366     // Load the result.
8367     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8368                        FIST, StackSlot, MachinePointerInfo(),
8369                        false, false, false, 0);
8370
8371   // The node is the result.
8372   return FIST;
8373 }
8374
8375 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8376                                            SelectionDAG &DAG) const {
8377   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8378     /*IsSigned=*/ false, /*IsReplace=*/ false);
8379   SDValue FIST = Vals.first, StackSlot = Vals.second;
8380   assert(FIST.getNode() && "Unexpected failure");
8381
8382   if (StackSlot.getNode())
8383     // Load the result.
8384     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8385                        FIST, StackSlot, MachinePointerInfo(),
8386                        false, false, false, 0);
8387
8388   // The node is the result.
8389   return FIST;
8390 }
8391
8392 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8393                                           SelectionDAG &DAG) const {
8394   DebugLoc DL = Op.getDebugLoc();
8395   EVT VT = Op.getValueType();
8396   SDValue In = Op.getOperand(0);
8397   EVT SVT = In.getValueType();
8398
8399   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8400
8401   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8402                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8403                                  In, DAG.getUNDEF(SVT)));
8404 }
8405
8406 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8407   LLVMContext *Context = DAG.getContext();
8408   DebugLoc dl = Op.getDebugLoc();
8409   EVT VT = Op.getValueType();
8410   EVT EltVT = VT;
8411   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8412   if (VT.isVector()) {
8413     EltVT = VT.getVectorElementType();
8414     NumElts = VT.getVectorNumElements();
8415   }
8416   Constant *C;
8417   if (EltVT == MVT::f64)
8418     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8419   else
8420     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8421   C = ConstantVector::getSplat(NumElts, C);
8422   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8423   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8424   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8425                              MachinePointerInfo::getConstantPool(),
8426                              false, false, false, Alignment);
8427   if (VT.isVector()) {
8428     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8429     return DAG.getNode(ISD::BITCAST, dl, VT,
8430                        DAG.getNode(ISD::AND, dl, ANDVT,
8431                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8432                                                Op.getOperand(0)),
8433                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8434   }
8435   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8436 }
8437
8438 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8439   LLVMContext *Context = DAG.getContext();
8440   DebugLoc dl = Op.getDebugLoc();
8441   EVT VT = Op.getValueType();
8442   EVT EltVT = VT;
8443   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8444   if (VT.isVector()) {
8445     EltVT = VT.getVectorElementType();
8446     NumElts = VT.getVectorNumElements();
8447   }
8448   Constant *C;
8449   if (EltVT == MVT::f64)
8450     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8451   else
8452     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8453   C = ConstantVector::getSplat(NumElts, C);
8454   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8455   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8456   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8457                              MachinePointerInfo::getConstantPool(),
8458                              false, false, false, Alignment);
8459   if (VT.isVector()) {
8460     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8461     return DAG.getNode(ISD::BITCAST, dl, VT,
8462                        DAG.getNode(ISD::XOR, dl, XORVT,
8463                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8464                                                Op.getOperand(0)),
8465                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8466   }
8467
8468   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8469 }
8470
8471 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8472   LLVMContext *Context = DAG.getContext();
8473   SDValue Op0 = Op.getOperand(0);
8474   SDValue Op1 = Op.getOperand(1);
8475   DebugLoc dl = Op.getDebugLoc();
8476   EVT VT = Op.getValueType();
8477   EVT SrcVT = Op1.getValueType();
8478
8479   // If second operand is smaller, extend it first.
8480   if (SrcVT.bitsLT(VT)) {
8481     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8482     SrcVT = VT;
8483   }
8484   // And if it is bigger, shrink it first.
8485   if (SrcVT.bitsGT(VT)) {
8486     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8487     SrcVT = VT;
8488   }
8489
8490   // At this point the operands and the result should have the same
8491   // type, and that won't be f80 since that is not custom lowered.
8492
8493   // First get the sign bit of second operand.
8494   SmallVector<Constant*,4> CV;
8495   if (SrcVT == MVT::f64) {
8496     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8497     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8498   } else {
8499     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8500     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8501     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8502     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8503   }
8504   Constant *C = ConstantVector::get(CV);
8505   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8506   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8507                               MachinePointerInfo::getConstantPool(),
8508                               false, false, false, 16);
8509   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8510
8511   // Shift sign bit right or left if the two operands have different types.
8512   if (SrcVT.bitsGT(VT)) {
8513     // Op0 is MVT::f32, Op1 is MVT::f64.
8514     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8515     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8516                           DAG.getConstant(32, MVT::i32));
8517     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8518     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8519                           DAG.getIntPtrConstant(0));
8520   }
8521
8522   // Clear first operand sign bit.
8523   CV.clear();
8524   if (VT == MVT::f64) {
8525     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8526     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8527   } else {
8528     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8529     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8530     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8531     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8532   }
8533   C = ConstantVector::get(CV);
8534   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8535   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8536                               MachinePointerInfo::getConstantPool(),
8537                               false, false, false, 16);
8538   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8539
8540   // Or the value with the sign bit.
8541   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8542 }
8543
8544 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8545   SDValue N0 = Op.getOperand(0);
8546   DebugLoc dl = Op.getDebugLoc();
8547   EVT VT = Op.getValueType();
8548
8549   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8550   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8551                                   DAG.getConstant(1, VT));
8552   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8553 }
8554
8555 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8556 //
8557 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8558   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8559
8560   if (!Subtarget->hasSSE41())
8561     return SDValue();
8562
8563   if (!Op->hasOneUse())
8564     return SDValue();
8565
8566   SDNode *N = Op.getNode();
8567   DebugLoc DL = N->getDebugLoc();
8568
8569   SmallVector<SDValue, 8> Opnds;
8570   DenseMap<SDValue, unsigned> VecInMap;
8571   EVT VT = MVT::Other;
8572
8573   // Recognize a special case where a vector is casted into wide integer to
8574   // test all 0s.
8575   Opnds.push_back(N->getOperand(0));
8576   Opnds.push_back(N->getOperand(1));
8577
8578   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8579     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8580     // BFS traverse all OR'd operands.
8581     if (I->getOpcode() == ISD::OR) {
8582       Opnds.push_back(I->getOperand(0));
8583       Opnds.push_back(I->getOperand(1));
8584       // Re-evaluate the number of nodes to be traversed.
8585       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8586       continue;
8587     }
8588
8589     // Quit if a non-EXTRACT_VECTOR_ELT
8590     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8591       return SDValue();
8592
8593     // Quit if without a constant index.
8594     SDValue Idx = I->getOperand(1);
8595     if (!isa<ConstantSDNode>(Idx))
8596       return SDValue();
8597
8598     SDValue ExtractedFromVec = I->getOperand(0);
8599     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8600     if (M == VecInMap.end()) {
8601       VT = ExtractedFromVec.getValueType();
8602       // Quit if not 128/256-bit vector.
8603       if (!VT.is128BitVector() && !VT.is256BitVector())
8604         return SDValue();
8605       // Quit if not the same type.
8606       if (VecInMap.begin() != VecInMap.end() &&
8607           VT != VecInMap.begin()->first.getValueType())
8608         return SDValue();
8609       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8610     }
8611     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8612   }
8613
8614   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8615          "Not extracted from 128-/256-bit vector.");
8616
8617   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8618   SmallVector<SDValue, 8> VecIns;
8619
8620   for (DenseMap<SDValue, unsigned>::const_iterator
8621         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8622     // Quit if not all elements are used.
8623     if (I->second != FullMask)
8624       return SDValue();
8625     VecIns.push_back(I->first);
8626   }
8627
8628   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8629
8630   // Cast all vectors into TestVT for PTEST.
8631   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8632     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8633
8634   // If more than one full vectors are evaluated, OR them first before PTEST.
8635   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8636     // Each iteration will OR 2 nodes and append the result until there is only
8637     // 1 node left, i.e. the final OR'd value of all vectors.
8638     SDValue LHS = VecIns[Slot];
8639     SDValue RHS = VecIns[Slot + 1];
8640     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8641   }
8642
8643   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8644                      VecIns.back(), VecIns.back());
8645 }
8646
8647 /// Emit nodes that will be selected as "test Op0,Op0", or something
8648 /// equivalent.
8649 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8650                                     SelectionDAG &DAG) const {
8651   DebugLoc dl = Op.getDebugLoc();
8652
8653   // CF and OF aren't always set the way we want. Determine which
8654   // of these we need.
8655   bool NeedCF = false;
8656   bool NeedOF = false;
8657   switch (X86CC) {
8658   default: break;
8659   case X86::COND_A: case X86::COND_AE:
8660   case X86::COND_B: case X86::COND_BE:
8661     NeedCF = true;
8662     break;
8663   case X86::COND_G: case X86::COND_GE:
8664   case X86::COND_L: case X86::COND_LE:
8665   case X86::COND_O: case X86::COND_NO:
8666     NeedOF = true;
8667     break;
8668   }
8669
8670   // See if we can use the EFLAGS value from the operand instead of
8671   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8672   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8673   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8674     // Emit a CMP with 0, which is the TEST pattern.
8675     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8676                        DAG.getConstant(0, Op.getValueType()));
8677
8678   unsigned Opcode = 0;
8679   unsigned NumOperands = 0;
8680
8681   // Truncate operations may prevent the merge of the SETCC instruction
8682   // and the arithmetic intruction before it. Attempt to truncate the operands
8683   // of the arithmetic instruction and use a reduced bit-width instruction.
8684   bool NeedTruncation = false;
8685   SDValue ArithOp = Op;
8686   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8687     SDValue Arith = Op->getOperand(0);
8688     // Both the trunc and the arithmetic op need to have one user each.
8689     if (Arith->hasOneUse())
8690       switch (Arith.getOpcode()) {
8691         default: break;
8692         case ISD::ADD:
8693         case ISD::SUB:
8694         case ISD::AND:
8695         case ISD::OR:
8696         case ISD::XOR: {
8697           NeedTruncation = true;
8698           ArithOp = Arith;
8699         }
8700       }
8701   }
8702
8703   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8704   // which may be the result of a CAST.  We use the variable 'Op', which is the
8705   // non-casted variable when we check for possible users.
8706   switch (ArithOp.getOpcode()) {
8707   case ISD::ADD:
8708     // Due to an isel shortcoming, be conservative if this add is likely to be
8709     // selected as part of a load-modify-store instruction. When the root node
8710     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8711     // uses of other nodes in the match, such as the ADD in this case. This
8712     // leads to the ADD being left around and reselected, with the result being
8713     // two adds in the output.  Alas, even if none our users are stores, that
8714     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8715     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8716     // climbing the DAG back to the root, and it doesn't seem to be worth the
8717     // effort.
8718     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8719          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8720       if (UI->getOpcode() != ISD::CopyToReg &&
8721           UI->getOpcode() != ISD::SETCC &&
8722           UI->getOpcode() != ISD::STORE)
8723         goto default_case;
8724
8725     if (ConstantSDNode *C =
8726         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8727       // An add of one will be selected as an INC.
8728       if (C->getAPIntValue() == 1) {
8729         Opcode = X86ISD::INC;
8730         NumOperands = 1;
8731         break;
8732       }
8733
8734       // An add of negative one (subtract of one) will be selected as a DEC.
8735       if (C->getAPIntValue().isAllOnesValue()) {
8736         Opcode = X86ISD::DEC;
8737         NumOperands = 1;
8738         break;
8739       }
8740     }
8741
8742     // Otherwise use a regular EFLAGS-setting add.
8743     Opcode = X86ISD::ADD;
8744     NumOperands = 2;
8745     break;
8746   case ISD::AND: {
8747     // If the primary and result isn't used, don't bother using X86ISD::AND,
8748     // because a TEST instruction will be better.
8749     bool NonFlagUse = false;
8750     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8751            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8752       SDNode *User = *UI;
8753       unsigned UOpNo = UI.getOperandNo();
8754       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8755         // Look pass truncate.
8756         UOpNo = User->use_begin().getOperandNo();
8757         User = *User->use_begin();
8758       }
8759
8760       if (User->getOpcode() != ISD::BRCOND &&
8761           User->getOpcode() != ISD::SETCC &&
8762           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8763         NonFlagUse = true;
8764         break;
8765       }
8766     }
8767
8768     if (!NonFlagUse)
8769       break;
8770   }
8771     // FALL THROUGH
8772   case ISD::SUB:
8773   case ISD::OR:
8774   case ISD::XOR:
8775     // Due to the ISEL shortcoming noted above, be conservative if this op is
8776     // likely to be selected as part of a load-modify-store instruction.
8777     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8778            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8779       if (UI->getOpcode() == ISD::STORE)
8780         goto default_case;
8781
8782     // Otherwise use a regular EFLAGS-setting instruction.
8783     switch (ArithOp.getOpcode()) {
8784     default: llvm_unreachable("unexpected operator!");
8785     case ISD::SUB: Opcode = X86ISD::SUB; break;
8786     case ISD::XOR: Opcode = X86ISD::XOR; break;
8787     case ISD::AND: Opcode = X86ISD::AND; break;
8788     case ISD::OR: {
8789       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8790         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8791         if (EFLAGS.getNode())
8792           return EFLAGS;
8793       }
8794       Opcode = X86ISD::OR;
8795       break;
8796     }
8797     }
8798
8799     NumOperands = 2;
8800     break;
8801   case X86ISD::ADD:
8802   case X86ISD::SUB:
8803   case X86ISD::INC:
8804   case X86ISD::DEC:
8805   case X86ISD::OR:
8806   case X86ISD::XOR:
8807   case X86ISD::AND:
8808     return SDValue(Op.getNode(), 1);
8809   default:
8810   default_case:
8811     break;
8812   }
8813
8814   // If we found that truncation is beneficial, perform the truncation and
8815   // update 'Op'.
8816   if (NeedTruncation) {
8817     EVT VT = Op.getValueType();
8818     SDValue WideVal = Op->getOperand(0);
8819     EVT WideVT = WideVal.getValueType();
8820     unsigned ConvertedOp = 0;
8821     // Use a target machine opcode to prevent further DAGCombine
8822     // optimizations that may separate the arithmetic operations
8823     // from the setcc node.
8824     switch (WideVal.getOpcode()) {
8825       default: break;
8826       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8827       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8828       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8829       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8830       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8831     }
8832
8833     if (ConvertedOp) {
8834       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8835       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8836         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8837         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8838         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8839       }
8840     }
8841   }
8842
8843   if (Opcode == 0)
8844     // Emit a CMP with 0, which is the TEST pattern.
8845     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8846                        DAG.getConstant(0, Op.getValueType()));
8847
8848   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8849   SmallVector<SDValue, 4> Ops;
8850   for (unsigned i = 0; i != NumOperands; ++i)
8851     Ops.push_back(Op.getOperand(i));
8852
8853   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8854   DAG.ReplaceAllUsesWith(Op, New);
8855   return SDValue(New.getNode(), 1);
8856 }
8857
8858 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8859 /// equivalent.
8860 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8861                                    SelectionDAG &DAG) const {
8862   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8863     if (C->getAPIntValue() == 0)
8864       return EmitTest(Op0, X86CC, DAG);
8865
8866   DebugLoc dl = Op0.getDebugLoc();
8867   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8868        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8869     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8870     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8871     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8872                               Op0, Op1);
8873     return SDValue(Sub.getNode(), 1);
8874   }
8875   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8876 }
8877
8878 /// Convert a comparison if required by the subtarget.
8879 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8880                                                  SelectionDAG &DAG) const {
8881   // If the subtarget does not support the FUCOMI instruction, floating-point
8882   // comparisons have to be converted.
8883   if (Subtarget->hasCMov() ||
8884       Cmp.getOpcode() != X86ISD::CMP ||
8885       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8886       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8887     return Cmp;
8888
8889   // The instruction selector will select an FUCOM instruction instead of
8890   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8891   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8892   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8893   DebugLoc dl = Cmp.getDebugLoc();
8894   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8895   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8896   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8897                             DAG.getConstant(8, MVT::i8));
8898   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8899   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8900 }
8901
8902 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8903 /// if it's possible.
8904 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8905                                      DebugLoc dl, SelectionDAG &DAG) const {
8906   SDValue Op0 = And.getOperand(0);
8907   SDValue Op1 = And.getOperand(1);
8908   if (Op0.getOpcode() == ISD::TRUNCATE)
8909     Op0 = Op0.getOperand(0);
8910   if (Op1.getOpcode() == ISD::TRUNCATE)
8911     Op1 = Op1.getOperand(0);
8912
8913   SDValue LHS, RHS;
8914   if (Op1.getOpcode() == ISD::SHL)
8915     std::swap(Op0, Op1);
8916   if (Op0.getOpcode() == ISD::SHL) {
8917     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8918       if (And00C->getZExtValue() == 1) {
8919         // If we looked past a truncate, check that it's only truncating away
8920         // known zeros.
8921         unsigned BitWidth = Op0.getValueSizeInBits();
8922         unsigned AndBitWidth = And.getValueSizeInBits();
8923         if (BitWidth > AndBitWidth) {
8924           APInt Zeros, Ones;
8925           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8926           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8927             return SDValue();
8928         }
8929         LHS = Op1;
8930         RHS = Op0.getOperand(1);
8931       }
8932   } else if (Op1.getOpcode() == ISD::Constant) {
8933     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8934     uint64_t AndRHSVal = AndRHS->getZExtValue();
8935     SDValue AndLHS = Op0;
8936
8937     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8938       LHS = AndLHS.getOperand(0);
8939       RHS = AndLHS.getOperand(1);
8940     }
8941
8942     // Use BT if the immediate can't be encoded in a TEST instruction.
8943     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8944       LHS = AndLHS;
8945       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8946     }
8947   }
8948
8949   if (LHS.getNode()) {
8950     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8951     // instruction.  Since the shift amount is in-range-or-undefined, we know
8952     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8953     // the encoding for the i16 version is larger than the i32 version.
8954     // Also promote i16 to i32 for performance / code size reason.
8955     if (LHS.getValueType() == MVT::i8 ||
8956         LHS.getValueType() == MVT::i16)
8957       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8958
8959     // If the operand types disagree, extend the shift amount to match.  Since
8960     // BT ignores high bits (like shifts) we can use anyextend.
8961     if (LHS.getValueType() != RHS.getValueType())
8962       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8963
8964     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8965     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8966     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8967                        DAG.getConstant(Cond, MVT::i8), BT);
8968   }
8969
8970   return SDValue();
8971 }
8972
8973 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8974
8975   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8976
8977   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8978   SDValue Op0 = Op.getOperand(0);
8979   SDValue Op1 = Op.getOperand(1);
8980   DebugLoc dl = Op.getDebugLoc();
8981   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8982
8983   // Optimize to BT if possible.
8984   // Lower (X & (1 << N)) == 0 to BT(X, N).
8985   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8986   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8987   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8988       Op1.getOpcode() == ISD::Constant &&
8989       cast<ConstantSDNode>(Op1)->isNullValue() &&
8990       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8991     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8992     if (NewSetCC.getNode())
8993       return NewSetCC;
8994   }
8995
8996   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8997   // these.
8998   if (Op1.getOpcode() == ISD::Constant &&
8999       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9000        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9001       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9002
9003     // If the input is a setcc, then reuse the input setcc or use a new one with
9004     // the inverted condition.
9005     if (Op0.getOpcode() == X86ISD::SETCC) {
9006       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9007       bool Invert = (CC == ISD::SETNE) ^
9008         cast<ConstantSDNode>(Op1)->isNullValue();
9009       if (!Invert) return Op0;
9010
9011       CCode = X86::GetOppositeBranchCondition(CCode);
9012       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9013                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9014     }
9015   }
9016
9017   bool isFP = Op1.getValueType().isFloatingPoint();
9018   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9019   if (X86CC == X86::COND_INVALID)
9020     return SDValue();
9021
9022   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9023   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9024   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9025                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9026 }
9027
9028 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9029 // ones, and then concatenate the result back.
9030 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9031   EVT VT = Op.getValueType();
9032
9033   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9034          "Unsupported value type for operation");
9035
9036   unsigned NumElems = VT.getVectorNumElements();
9037   DebugLoc dl = Op.getDebugLoc();
9038   SDValue CC = Op.getOperand(2);
9039
9040   // Extract the LHS vectors
9041   SDValue LHS = Op.getOperand(0);
9042   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9043   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9044
9045   // Extract the RHS vectors
9046   SDValue RHS = Op.getOperand(1);
9047   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9048   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9049
9050   // Issue the operation on the smaller types and concatenate the result back
9051   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9052   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9053   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9054                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9055                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9056 }
9057
9058
9059 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9060   SDValue Cond;
9061   SDValue Op0 = Op.getOperand(0);
9062   SDValue Op1 = Op.getOperand(1);
9063   SDValue CC = Op.getOperand(2);
9064   EVT VT = Op.getValueType();
9065   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9066   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9067   DebugLoc dl = Op.getDebugLoc();
9068
9069   if (isFP) {
9070 #ifndef NDEBUG
9071     EVT EltVT = Op0.getValueType().getVectorElementType();
9072     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9073 #endif
9074
9075     unsigned SSECC;
9076     bool Swap = false;
9077
9078     // SSE Condition code mapping:
9079     //  0 - EQ
9080     //  1 - LT
9081     //  2 - LE
9082     //  3 - UNORD
9083     //  4 - NEQ
9084     //  5 - NLT
9085     //  6 - NLE
9086     //  7 - ORD
9087     switch (SetCCOpcode) {
9088     default: llvm_unreachable("Unexpected SETCC condition");
9089     case ISD::SETOEQ:
9090     case ISD::SETEQ:  SSECC = 0; break;
9091     case ISD::SETOGT:
9092     case ISD::SETGT: Swap = true; // Fallthrough
9093     case ISD::SETLT:
9094     case ISD::SETOLT: SSECC = 1; break;
9095     case ISD::SETOGE:
9096     case ISD::SETGE: Swap = true; // Fallthrough
9097     case ISD::SETLE:
9098     case ISD::SETOLE: SSECC = 2; break;
9099     case ISD::SETUO:  SSECC = 3; break;
9100     case ISD::SETUNE:
9101     case ISD::SETNE:  SSECC = 4; break;
9102     case ISD::SETULE: Swap = true; // Fallthrough
9103     case ISD::SETUGE: SSECC = 5; break;
9104     case ISD::SETULT: Swap = true; // Fallthrough
9105     case ISD::SETUGT: SSECC = 6; break;
9106     case ISD::SETO:   SSECC = 7; break;
9107     case ISD::SETUEQ:
9108     case ISD::SETONE: SSECC = 8; break;
9109     }
9110     if (Swap)
9111       std::swap(Op0, Op1);
9112
9113     // In the two special cases we can't handle, emit two comparisons.
9114     if (SSECC == 8) {
9115       unsigned CC0, CC1;
9116       unsigned CombineOpc;
9117       if (SetCCOpcode == ISD::SETUEQ) {
9118         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9119       } else {
9120         assert(SetCCOpcode == ISD::SETONE);
9121         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9122       }
9123
9124       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9125                                  DAG.getConstant(CC0, MVT::i8));
9126       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9127                                  DAG.getConstant(CC1, MVT::i8));
9128       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9129     }
9130     // Handle all other FP comparisons here.
9131     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9132                        DAG.getConstant(SSECC, MVT::i8));
9133   }
9134
9135   // Break 256-bit integer vector compare into smaller ones.
9136   if (VT.is256BitVector() && !Subtarget->hasAVX2())
9137     return Lower256IntVSETCC(Op, DAG);
9138
9139   // We are handling one of the integer comparisons here.  Since SSE only has
9140   // GT and EQ comparisons for integer, swapping operands and multiple
9141   // operations may be required for some comparisons.
9142   unsigned Opc;
9143   bool Swap = false, Invert = false, FlipSigns = false;
9144
9145   switch (SetCCOpcode) {
9146   default: llvm_unreachable("Unexpected SETCC condition");
9147   case ISD::SETNE:  Invert = true;
9148   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9149   case ISD::SETLT:  Swap = true;
9150   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9151   case ISD::SETGE:  Swap = true;
9152   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9153   case ISD::SETULT: Swap = true;
9154   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9155   case ISD::SETUGE: Swap = true;
9156   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9157   }
9158   if (Swap)
9159     std::swap(Op0, Op1);
9160
9161   // Check that the operation in question is available (most are plain SSE2,
9162   // but PCMPGTQ and PCMPEQQ have different requirements).
9163   if (VT == MVT::v2i64) {
9164     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9165       return SDValue();
9166     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
9167       return SDValue();
9168   }
9169
9170   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9171   // bits of the inputs before performing those operations.
9172   if (FlipSigns) {
9173     EVT EltVT = VT.getVectorElementType();
9174     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9175                                       EltVT);
9176     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9177     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9178                                     SignBits.size());
9179     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9180     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9181   }
9182
9183   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9184
9185   // If the logical-not of the result is required, perform that now.
9186   if (Invert)
9187     Result = DAG.getNOT(dl, Result, VT);
9188
9189   return Result;
9190 }
9191
9192 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9193 static bool isX86LogicalCmp(SDValue Op) {
9194   unsigned Opc = Op.getNode()->getOpcode();
9195   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9196       Opc == X86ISD::SAHF)
9197     return true;
9198   if (Op.getResNo() == 1 &&
9199       (Opc == X86ISD::ADD ||
9200        Opc == X86ISD::SUB ||
9201        Opc == X86ISD::ADC ||
9202        Opc == X86ISD::SBB ||
9203        Opc == X86ISD::SMUL ||
9204        Opc == X86ISD::UMUL ||
9205        Opc == X86ISD::INC ||
9206        Opc == X86ISD::DEC ||
9207        Opc == X86ISD::OR ||
9208        Opc == X86ISD::XOR ||
9209        Opc == X86ISD::AND))
9210     return true;
9211
9212   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9213     return true;
9214
9215   return false;
9216 }
9217
9218 static bool isZero(SDValue V) {
9219   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9220   return C && C->isNullValue();
9221 }
9222
9223 static bool isAllOnes(SDValue V) {
9224   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9225   return C && C->isAllOnesValue();
9226 }
9227
9228 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9229   if (V.getOpcode() != ISD::TRUNCATE)
9230     return false;
9231
9232   SDValue VOp0 = V.getOperand(0);
9233   unsigned InBits = VOp0.getValueSizeInBits();
9234   unsigned Bits = V.getValueSizeInBits();
9235   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9236 }
9237
9238 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9239   bool addTest = true;
9240   SDValue Cond  = Op.getOperand(0);
9241   SDValue Op1 = Op.getOperand(1);
9242   SDValue Op2 = Op.getOperand(2);
9243   DebugLoc DL = Op.getDebugLoc();
9244   SDValue CC;
9245
9246   if (Cond.getOpcode() == ISD::SETCC) {
9247     SDValue NewCond = LowerSETCC(Cond, DAG);
9248     if (NewCond.getNode())
9249       Cond = NewCond;
9250   }
9251
9252   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9253   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9254   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9255   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9256   if (Cond.getOpcode() == X86ISD::SETCC &&
9257       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9258       isZero(Cond.getOperand(1).getOperand(1))) {
9259     SDValue Cmp = Cond.getOperand(1);
9260
9261     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9262
9263     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9264         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9265       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9266
9267       SDValue CmpOp0 = Cmp.getOperand(0);
9268       // Apply further optimizations for special cases
9269       // (select (x != 0), -1, 0) -> neg & sbb
9270       // (select (x == 0), 0, -1) -> neg & sbb
9271       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9272         if (YC->isNullValue() &&
9273             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9274           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9275           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9276                                     DAG.getConstant(0, CmpOp0.getValueType()),
9277                                     CmpOp0);
9278           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9279                                     DAG.getConstant(X86::COND_B, MVT::i8),
9280                                     SDValue(Neg.getNode(), 1));
9281           return Res;
9282         }
9283
9284       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9285                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9286       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9287
9288       SDValue Res =   // Res = 0 or -1.
9289         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9290                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9291
9292       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9293         Res = DAG.getNOT(DL, Res, Res.getValueType());
9294
9295       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9296       if (N2C == 0 || !N2C->isNullValue())
9297         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9298       return Res;
9299     }
9300   }
9301
9302   // Look past (and (setcc_carry (cmp ...)), 1).
9303   if (Cond.getOpcode() == ISD::AND &&
9304       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9305     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9306     if (C && C->getAPIntValue() == 1)
9307       Cond = Cond.getOperand(0);
9308   }
9309
9310   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9311   // setting operand in place of the X86ISD::SETCC.
9312   unsigned CondOpcode = Cond.getOpcode();
9313   if (CondOpcode == X86ISD::SETCC ||
9314       CondOpcode == X86ISD::SETCC_CARRY) {
9315     CC = Cond.getOperand(0);
9316
9317     SDValue Cmp = Cond.getOperand(1);
9318     unsigned Opc = Cmp.getOpcode();
9319     EVT VT = Op.getValueType();
9320
9321     bool IllegalFPCMov = false;
9322     if (VT.isFloatingPoint() && !VT.isVector() &&
9323         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9324       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9325
9326     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9327         Opc == X86ISD::BT) { // FIXME
9328       Cond = Cmp;
9329       addTest = false;
9330     }
9331   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9332              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9333              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9334               Cond.getOperand(0).getValueType() != MVT::i8)) {
9335     SDValue LHS = Cond.getOperand(0);
9336     SDValue RHS = Cond.getOperand(1);
9337     unsigned X86Opcode;
9338     unsigned X86Cond;
9339     SDVTList VTs;
9340     switch (CondOpcode) {
9341     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9342     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9343     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9344     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9345     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9346     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9347     default: llvm_unreachable("unexpected overflowing operator");
9348     }
9349     if (CondOpcode == ISD::UMULO)
9350       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9351                           MVT::i32);
9352     else
9353       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9354
9355     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9356
9357     if (CondOpcode == ISD::UMULO)
9358       Cond = X86Op.getValue(2);
9359     else
9360       Cond = X86Op.getValue(1);
9361
9362     CC = DAG.getConstant(X86Cond, MVT::i8);
9363     addTest = false;
9364   }
9365
9366   if (addTest) {
9367     // Look pass the truncate if the high bits are known zero.
9368     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9369         Cond = Cond.getOperand(0);
9370
9371     // We know the result of AND is compared against zero. Try to match
9372     // it to BT.
9373     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9374       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9375       if (NewSetCC.getNode()) {
9376         CC = NewSetCC.getOperand(0);
9377         Cond = NewSetCC.getOperand(1);
9378         addTest = false;
9379       }
9380     }
9381   }
9382
9383   if (addTest) {
9384     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9385     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9386   }
9387
9388   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9389   // a <  b ?  0 : -1 -> RES = setcc_carry
9390   // a >= b ? -1 :  0 -> RES = setcc_carry
9391   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9392   if (Cond.getOpcode() == X86ISD::SUB) {
9393     Cond = ConvertCmpIfNecessary(Cond, DAG);
9394     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9395
9396     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9397         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9398       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9399                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9400       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9401         return DAG.getNOT(DL, Res, Res.getValueType());
9402       return Res;
9403     }
9404   }
9405
9406   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9407   // widen the cmov and push the truncate through. This avoids introducing a new
9408   // branch during isel and doesn't add any extensions.
9409   if (Op.getValueType() == MVT::i8 &&
9410       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9411     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9412     if (T1.getValueType() == T2.getValueType() &&
9413         // Blacklist CopyFromReg to avoid partial register stalls.
9414         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9415       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9416       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9417       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9418     }
9419   }
9420
9421   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9422   // condition is true.
9423   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9424   SDValue Ops[] = { Op2, Op1, CC, Cond };
9425   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9426 }
9427
9428 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9429 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9430 // from the AND / OR.
9431 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9432   Opc = Op.getOpcode();
9433   if (Opc != ISD::OR && Opc != ISD::AND)
9434     return false;
9435   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9436           Op.getOperand(0).hasOneUse() &&
9437           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9438           Op.getOperand(1).hasOneUse());
9439 }
9440
9441 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9442 // 1 and that the SETCC node has a single use.
9443 static bool isXor1OfSetCC(SDValue Op) {
9444   if (Op.getOpcode() != ISD::XOR)
9445     return false;
9446   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9447   if (N1C && N1C->getAPIntValue() == 1) {
9448     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9449       Op.getOperand(0).hasOneUse();
9450   }
9451   return false;
9452 }
9453
9454 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9455   bool addTest = true;
9456   SDValue Chain = Op.getOperand(0);
9457   SDValue Cond  = Op.getOperand(1);
9458   SDValue Dest  = Op.getOperand(2);
9459   DebugLoc dl = Op.getDebugLoc();
9460   SDValue CC;
9461   bool Inverted = false;
9462
9463   if (Cond.getOpcode() == ISD::SETCC) {
9464     // Check for setcc([su]{add,sub,mul}o == 0).
9465     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9466         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9467         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9468         Cond.getOperand(0).getResNo() == 1 &&
9469         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9470          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9471          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9472          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9473          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9474          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9475       Inverted = true;
9476       Cond = Cond.getOperand(0);
9477     } else {
9478       SDValue NewCond = LowerSETCC(Cond, DAG);
9479       if (NewCond.getNode())
9480         Cond = NewCond;
9481     }
9482   }
9483 #if 0
9484   // FIXME: LowerXALUO doesn't handle these!!
9485   else if (Cond.getOpcode() == X86ISD::ADD  ||
9486            Cond.getOpcode() == X86ISD::SUB  ||
9487            Cond.getOpcode() == X86ISD::SMUL ||
9488            Cond.getOpcode() == X86ISD::UMUL)
9489     Cond = LowerXALUO(Cond, DAG);
9490 #endif
9491
9492   // Look pass (and (setcc_carry (cmp ...)), 1).
9493   if (Cond.getOpcode() == ISD::AND &&
9494       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9495     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9496     if (C && C->getAPIntValue() == 1)
9497       Cond = Cond.getOperand(0);
9498   }
9499
9500   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9501   // setting operand in place of the X86ISD::SETCC.
9502   unsigned CondOpcode = Cond.getOpcode();
9503   if (CondOpcode == X86ISD::SETCC ||
9504       CondOpcode == X86ISD::SETCC_CARRY) {
9505     CC = Cond.getOperand(0);
9506
9507     SDValue Cmp = Cond.getOperand(1);
9508     unsigned Opc = Cmp.getOpcode();
9509     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9510     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9511       Cond = Cmp;
9512       addTest = false;
9513     } else {
9514       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9515       default: break;
9516       case X86::COND_O:
9517       case X86::COND_B:
9518         // These can only come from an arithmetic instruction with overflow,
9519         // e.g. SADDO, UADDO.
9520         Cond = Cond.getNode()->getOperand(1);
9521         addTest = false;
9522         break;
9523       }
9524     }
9525   }
9526   CondOpcode = Cond.getOpcode();
9527   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9528       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9529       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9530        Cond.getOperand(0).getValueType() != MVT::i8)) {
9531     SDValue LHS = Cond.getOperand(0);
9532     SDValue RHS = Cond.getOperand(1);
9533     unsigned X86Opcode;
9534     unsigned X86Cond;
9535     SDVTList VTs;
9536     switch (CondOpcode) {
9537     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9538     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9539     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9540     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9541     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9542     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9543     default: llvm_unreachable("unexpected overflowing operator");
9544     }
9545     if (Inverted)
9546       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9547     if (CondOpcode == ISD::UMULO)
9548       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9549                           MVT::i32);
9550     else
9551       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9552
9553     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9554
9555     if (CondOpcode == ISD::UMULO)
9556       Cond = X86Op.getValue(2);
9557     else
9558       Cond = X86Op.getValue(1);
9559
9560     CC = DAG.getConstant(X86Cond, MVT::i8);
9561     addTest = false;
9562   } else {
9563     unsigned CondOpc;
9564     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9565       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9566       if (CondOpc == ISD::OR) {
9567         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9568         // two branches instead of an explicit OR instruction with a
9569         // separate test.
9570         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9571             isX86LogicalCmp(Cmp)) {
9572           CC = Cond.getOperand(0).getOperand(0);
9573           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9574                               Chain, Dest, CC, Cmp);
9575           CC = Cond.getOperand(1).getOperand(0);
9576           Cond = Cmp;
9577           addTest = false;
9578         }
9579       } else { // ISD::AND
9580         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9581         // two branches instead of an explicit AND instruction with a
9582         // separate test. However, we only do this if this block doesn't
9583         // have a fall-through edge, because this requires an explicit
9584         // jmp when the condition is false.
9585         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9586             isX86LogicalCmp(Cmp) &&
9587             Op.getNode()->hasOneUse()) {
9588           X86::CondCode CCode =
9589             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9590           CCode = X86::GetOppositeBranchCondition(CCode);
9591           CC = DAG.getConstant(CCode, MVT::i8);
9592           SDNode *User = *Op.getNode()->use_begin();
9593           // Look for an unconditional branch following this conditional branch.
9594           // We need this because we need to reverse the successors in order
9595           // to implement FCMP_OEQ.
9596           if (User->getOpcode() == ISD::BR) {
9597             SDValue FalseBB = User->getOperand(1);
9598             SDNode *NewBR =
9599               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9600             assert(NewBR == User);
9601             (void)NewBR;
9602             Dest = FalseBB;
9603
9604             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9605                                 Chain, Dest, CC, Cmp);
9606             X86::CondCode CCode =
9607               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9608             CCode = X86::GetOppositeBranchCondition(CCode);
9609             CC = DAG.getConstant(CCode, MVT::i8);
9610             Cond = Cmp;
9611             addTest = false;
9612           }
9613         }
9614       }
9615     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9616       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9617       // It should be transformed during dag combiner except when the condition
9618       // is set by a arithmetics with overflow node.
9619       X86::CondCode CCode =
9620         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9621       CCode = X86::GetOppositeBranchCondition(CCode);
9622       CC = DAG.getConstant(CCode, MVT::i8);
9623       Cond = Cond.getOperand(0).getOperand(1);
9624       addTest = false;
9625     } else if (Cond.getOpcode() == ISD::SETCC &&
9626                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9627       // For FCMP_OEQ, we can emit
9628       // two branches instead of an explicit AND instruction with a
9629       // separate test. However, we only do this if this block doesn't
9630       // have a fall-through edge, because this requires an explicit
9631       // jmp when the condition is false.
9632       if (Op.getNode()->hasOneUse()) {
9633         SDNode *User = *Op.getNode()->use_begin();
9634         // Look for an unconditional branch following this conditional branch.
9635         // We need this because we need to reverse the successors in order
9636         // to implement FCMP_OEQ.
9637         if (User->getOpcode() == ISD::BR) {
9638           SDValue FalseBB = User->getOperand(1);
9639           SDNode *NewBR =
9640             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9641           assert(NewBR == User);
9642           (void)NewBR;
9643           Dest = FalseBB;
9644
9645           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9646                                     Cond.getOperand(0), Cond.getOperand(1));
9647           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9648           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9649           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9650                               Chain, Dest, CC, Cmp);
9651           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9652           Cond = Cmp;
9653           addTest = false;
9654         }
9655       }
9656     } else if (Cond.getOpcode() == ISD::SETCC &&
9657                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9658       // For FCMP_UNE, we can emit
9659       // two branches instead of an explicit AND instruction with a
9660       // separate test. However, we only do this if this block doesn't
9661       // have a fall-through edge, because this requires an explicit
9662       // jmp when the condition is false.
9663       if (Op.getNode()->hasOneUse()) {
9664         SDNode *User = *Op.getNode()->use_begin();
9665         // Look for an unconditional branch following this conditional branch.
9666         // We need this because we need to reverse the successors in order
9667         // to implement FCMP_UNE.
9668         if (User->getOpcode() == ISD::BR) {
9669           SDValue FalseBB = User->getOperand(1);
9670           SDNode *NewBR =
9671             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9672           assert(NewBR == User);
9673           (void)NewBR;
9674
9675           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9676                                     Cond.getOperand(0), Cond.getOperand(1));
9677           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9678           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9679           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9680                               Chain, Dest, CC, Cmp);
9681           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9682           Cond = Cmp;
9683           addTest = false;
9684           Dest = FalseBB;
9685         }
9686       }
9687     }
9688   }
9689
9690   if (addTest) {
9691     // Look pass the truncate if the high bits are known zero.
9692     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9693         Cond = Cond.getOperand(0);
9694
9695     // We know the result of AND is compared against zero. Try to match
9696     // it to BT.
9697     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9698       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9699       if (NewSetCC.getNode()) {
9700         CC = NewSetCC.getOperand(0);
9701         Cond = NewSetCC.getOperand(1);
9702         addTest = false;
9703       }
9704     }
9705   }
9706
9707   if (addTest) {
9708     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9709     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9710   }
9711   Cond = ConvertCmpIfNecessary(Cond, DAG);
9712   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9713                      Chain, Dest, CC, Cond);
9714 }
9715
9716
9717 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9718 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9719 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9720 // that the guard pages used by the OS virtual memory manager are allocated in
9721 // correct sequence.
9722 SDValue
9723 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9724                                            SelectionDAG &DAG) const {
9725   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9726           getTargetMachine().Options.EnableSegmentedStacks) &&
9727          "This should be used only on Windows targets or when segmented stacks "
9728          "are being used");
9729   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9730   DebugLoc dl = Op.getDebugLoc();
9731
9732   // Get the inputs.
9733   SDValue Chain = Op.getOperand(0);
9734   SDValue Size  = Op.getOperand(1);
9735   // FIXME: Ensure alignment here
9736
9737   bool Is64Bit = Subtarget->is64Bit();
9738   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9739
9740   if (getTargetMachine().Options.EnableSegmentedStacks) {
9741     MachineFunction &MF = DAG.getMachineFunction();
9742     MachineRegisterInfo &MRI = MF.getRegInfo();
9743
9744     if (Is64Bit) {
9745       // The 64 bit implementation of segmented stacks needs to clobber both r10
9746       // r11. This makes it impossible to use it along with nested parameters.
9747       const Function *F = MF.getFunction();
9748
9749       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9750            I != E; ++I)
9751         if (I->hasNestAttr())
9752           report_fatal_error("Cannot use segmented stacks with functions that "
9753                              "have nested arguments.");
9754     }
9755
9756     const TargetRegisterClass *AddrRegClass =
9757       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9758     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9759     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9760     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9761                                 DAG.getRegister(Vreg, SPTy));
9762     SDValue Ops1[2] = { Value, Chain };
9763     return DAG.getMergeValues(Ops1, 2, dl);
9764   } else {
9765     SDValue Flag;
9766     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9767
9768     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9769     Flag = Chain.getValue(1);
9770     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9771
9772     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9773     Flag = Chain.getValue(1);
9774
9775     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9776
9777     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9778     return DAG.getMergeValues(Ops1, 2, dl);
9779   }
9780 }
9781
9782 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9783   MachineFunction &MF = DAG.getMachineFunction();
9784   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9785
9786   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9787   DebugLoc DL = Op.getDebugLoc();
9788
9789   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9790     // vastart just stores the address of the VarArgsFrameIndex slot into the
9791     // memory location argument.
9792     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9793                                    getPointerTy());
9794     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9795                         MachinePointerInfo(SV), false, false, 0);
9796   }
9797
9798   // __va_list_tag:
9799   //   gp_offset         (0 - 6 * 8)
9800   //   fp_offset         (48 - 48 + 8 * 16)
9801   //   overflow_arg_area (point to parameters coming in memory).
9802   //   reg_save_area
9803   SmallVector<SDValue, 8> MemOps;
9804   SDValue FIN = Op.getOperand(1);
9805   // Store gp_offset
9806   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9807                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9808                                                MVT::i32),
9809                                FIN, MachinePointerInfo(SV), false, false, 0);
9810   MemOps.push_back(Store);
9811
9812   // Store fp_offset
9813   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9814                     FIN, DAG.getIntPtrConstant(4));
9815   Store = DAG.getStore(Op.getOperand(0), DL,
9816                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9817                                        MVT::i32),
9818                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9819   MemOps.push_back(Store);
9820
9821   // Store ptr to overflow_arg_area
9822   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9823                     FIN, DAG.getIntPtrConstant(4));
9824   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9825                                     getPointerTy());
9826   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9827                        MachinePointerInfo(SV, 8),
9828                        false, false, 0);
9829   MemOps.push_back(Store);
9830
9831   // Store ptr to reg_save_area.
9832   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9833                     FIN, DAG.getIntPtrConstant(8));
9834   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9835                                     getPointerTy());
9836   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9837                        MachinePointerInfo(SV, 16), false, false, 0);
9838   MemOps.push_back(Store);
9839   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9840                      &MemOps[0], MemOps.size());
9841 }
9842
9843 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9844   assert(Subtarget->is64Bit() &&
9845          "LowerVAARG only handles 64-bit va_arg!");
9846   assert((Subtarget->isTargetLinux() ||
9847           Subtarget->isTargetDarwin()) &&
9848           "Unhandled target in LowerVAARG");
9849   assert(Op.getNode()->getNumOperands() == 4);
9850   SDValue Chain = Op.getOperand(0);
9851   SDValue SrcPtr = Op.getOperand(1);
9852   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9853   unsigned Align = Op.getConstantOperandVal(3);
9854   DebugLoc dl = Op.getDebugLoc();
9855
9856   EVT ArgVT = Op.getNode()->getValueType(0);
9857   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9858   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9859   uint8_t ArgMode;
9860
9861   // Decide which area this value should be read from.
9862   // TODO: Implement the AMD64 ABI in its entirety. This simple
9863   // selection mechanism works only for the basic types.
9864   if (ArgVT == MVT::f80) {
9865     llvm_unreachable("va_arg for f80 not yet implemented");
9866   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9867     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9868   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9869     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9870   } else {
9871     llvm_unreachable("Unhandled argument type in LowerVAARG");
9872   }
9873
9874   if (ArgMode == 2) {
9875     // Sanity Check: Make sure using fp_offset makes sense.
9876     assert(!getTargetMachine().Options.UseSoftFloat &&
9877            !(DAG.getMachineFunction()
9878                 .getFunction()->getFnAttributes()
9879                 .hasAttribute(Attributes::NoImplicitFloat)) &&
9880            Subtarget->hasSSE1());
9881   }
9882
9883   // Insert VAARG_64 node into the DAG
9884   // VAARG_64 returns two values: Variable Argument Address, Chain
9885   SmallVector<SDValue, 11> InstOps;
9886   InstOps.push_back(Chain);
9887   InstOps.push_back(SrcPtr);
9888   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9889   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9890   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9891   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9892   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9893                                           VTs, &InstOps[0], InstOps.size(),
9894                                           MVT::i64,
9895                                           MachinePointerInfo(SV),
9896                                           /*Align=*/0,
9897                                           /*Volatile=*/false,
9898                                           /*ReadMem=*/true,
9899                                           /*WriteMem=*/true);
9900   Chain = VAARG.getValue(1);
9901
9902   // Load the next argument and return it
9903   return DAG.getLoad(ArgVT, dl,
9904                      Chain,
9905                      VAARG,
9906                      MachinePointerInfo(),
9907                      false, false, false, 0);
9908 }
9909
9910 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9911                            SelectionDAG &DAG) {
9912   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9913   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9914   SDValue Chain = Op.getOperand(0);
9915   SDValue DstPtr = Op.getOperand(1);
9916   SDValue SrcPtr = Op.getOperand(2);
9917   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9918   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9919   DebugLoc DL = Op.getDebugLoc();
9920
9921   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9922                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9923                        false,
9924                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9925 }
9926
9927 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9928 // may or may not be a constant. Takes immediate version of shift as input.
9929 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9930                                    SDValue SrcOp, SDValue ShAmt,
9931                                    SelectionDAG &DAG) {
9932   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9933
9934   if (isa<ConstantSDNode>(ShAmt)) {
9935     // Constant may be a TargetConstant. Use a regular constant.
9936     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9937     switch (Opc) {
9938       default: llvm_unreachable("Unknown target vector shift node");
9939       case X86ISD::VSHLI:
9940       case X86ISD::VSRLI:
9941       case X86ISD::VSRAI:
9942         return DAG.getNode(Opc, dl, VT, SrcOp,
9943                            DAG.getConstant(ShiftAmt, MVT::i32));
9944     }
9945   }
9946
9947   // Change opcode to non-immediate version
9948   switch (Opc) {
9949     default: llvm_unreachable("Unknown target vector shift node");
9950     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9951     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9952     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9953   }
9954
9955   // Need to build a vector containing shift amount
9956   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9957   SDValue ShOps[4];
9958   ShOps[0] = ShAmt;
9959   ShOps[1] = DAG.getConstant(0, MVT::i32);
9960   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9961   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9962
9963   // The return type has to be a 128-bit type with the same element
9964   // type as the input type.
9965   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9966   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9967
9968   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9969   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9970 }
9971
9972 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9973   DebugLoc dl = Op.getDebugLoc();
9974   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9975   switch (IntNo) {
9976   default: return SDValue();    // Don't custom lower most intrinsics.
9977   // Comparison intrinsics.
9978   case Intrinsic::x86_sse_comieq_ss:
9979   case Intrinsic::x86_sse_comilt_ss:
9980   case Intrinsic::x86_sse_comile_ss:
9981   case Intrinsic::x86_sse_comigt_ss:
9982   case Intrinsic::x86_sse_comige_ss:
9983   case Intrinsic::x86_sse_comineq_ss:
9984   case Intrinsic::x86_sse_ucomieq_ss:
9985   case Intrinsic::x86_sse_ucomilt_ss:
9986   case Intrinsic::x86_sse_ucomile_ss:
9987   case Intrinsic::x86_sse_ucomigt_ss:
9988   case Intrinsic::x86_sse_ucomige_ss:
9989   case Intrinsic::x86_sse_ucomineq_ss:
9990   case Intrinsic::x86_sse2_comieq_sd:
9991   case Intrinsic::x86_sse2_comilt_sd:
9992   case Intrinsic::x86_sse2_comile_sd:
9993   case Intrinsic::x86_sse2_comigt_sd:
9994   case Intrinsic::x86_sse2_comige_sd:
9995   case Intrinsic::x86_sse2_comineq_sd:
9996   case Intrinsic::x86_sse2_ucomieq_sd:
9997   case Intrinsic::x86_sse2_ucomilt_sd:
9998   case Intrinsic::x86_sse2_ucomile_sd:
9999   case Intrinsic::x86_sse2_ucomigt_sd:
10000   case Intrinsic::x86_sse2_ucomige_sd:
10001   case Intrinsic::x86_sse2_ucomineq_sd: {
10002     unsigned Opc;
10003     ISD::CondCode CC;
10004     switch (IntNo) {
10005     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10006     case Intrinsic::x86_sse_comieq_ss:
10007     case Intrinsic::x86_sse2_comieq_sd:
10008       Opc = X86ISD::COMI;
10009       CC = ISD::SETEQ;
10010       break;
10011     case Intrinsic::x86_sse_comilt_ss:
10012     case Intrinsic::x86_sse2_comilt_sd:
10013       Opc = X86ISD::COMI;
10014       CC = ISD::SETLT;
10015       break;
10016     case Intrinsic::x86_sse_comile_ss:
10017     case Intrinsic::x86_sse2_comile_sd:
10018       Opc = X86ISD::COMI;
10019       CC = ISD::SETLE;
10020       break;
10021     case Intrinsic::x86_sse_comigt_ss:
10022     case Intrinsic::x86_sse2_comigt_sd:
10023       Opc = X86ISD::COMI;
10024       CC = ISD::SETGT;
10025       break;
10026     case Intrinsic::x86_sse_comige_ss:
10027     case Intrinsic::x86_sse2_comige_sd:
10028       Opc = X86ISD::COMI;
10029       CC = ISD::SETGE;
10030       break;
10031     case Intrinsic::x86_sse_comineq_ss:
10032     case Intrinsic::x86_sse2_comineq_sd:
10033       Opc = X86ISD::COMI;
10034       CC = ISD::SETNE;
10035       break;
10036     case Intrinsic::x86_sse_ucomieq_ss:
10037     case Intrinsic::x86_sse2_ucomieq_sd:
10038       Opc = X86ISD::UCOMI;
10039       CC = ISD::SETEQ;
10040       break;
10041     case Intrinsic::x86_sse_ucomilt_ss:
10042     case Intrinsic::x86_sse2_ucomilt_sd:
10043       Opc = X86ISD::UCOMI;
10044       CC = ISD::SETLT;
10045       break;
10046     case Intrinsic::x86_sse_ucomile_ss:
10047     case Intrinsic::x86_sse2_ucomile_sd:
10048       Opc = X86ISD::UCOMI;
10049       CC = ISD::SETLE;
10050       break;
10051     case Intrinsic::x86_sse_ucomigt_ss:
10052     case Intrinsic::x86_sse2_ucomigt_sd:
10053       Opc = X86ISD::UCOMI;
10054       CC = ISD::SETGT;
10055       break;
10056     case Intrinsic::x86_sse_ucomige_ss:
10057     case Intrinsic::x86_sse2_ucomige_sd:
10058       Opc = X86ISD::UCOMI;
10059       CC = ISD::SETGE;
10060       break;
10061     case Intrinsic::x86_sse_ucomineq_ss:
10062     case Intrinsic::x86_sse2_ucomineq_sd:
10063       Opc = X86ISD::UCOMI;
10064       CC = ISD::SETNE;
10065       break;
10066     }
10067
10068     SDValue LHS = Op.getOperand(1);
10069     SDValue RHS = Op.getOperand(2);
10070     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10071     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10072     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10073     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10074                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10075     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10076   }
10077
10078   // Arithmetic intrinsics.
10079   case Intrinsic::x86_sse2_pmulu_dq:
10080   case Intrinsic::x86_avx2_pmulu_dq:
10081     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10082                        Op.getOperand(1), Op.getOperand(2));
10083
10084   // SSE3/AVX horizontal add/sub intrinsics
10085   case Intrinsic::x86_sse3_hadd_ps:
10086   case Intrinsic::x86_sse3_hadd_pd:
10087   case Intrinsic::x86_avx_hadd_ps_256:
10088   case Intrinsic::x86_avx_hadd_pd_256:
10089   case Intrinsic::x86_sse3_hsub_ps:
10090   case Intrinsic::x86_sse3_hsub_pd:
10091   case Intrinsic::x86_avx_hsub_ps_256:
10092   case Intrinsic::x86_avx_hsub_pd_256:
10093   case Intrinsic::x86_ssse3_phadd_w_128:
10094   case Intrinsic::x86_ssse3_phadd_d_128:
10095   case Intrinsic::x86_avx2_phadd_w:
10096   case Intrinsic::x86_avx2_phadd_d:
10097   case Intrinsic::x86_ssse3_phsub_w_128:
10098   case Intrinsic::x86_ssse3_phsub_d_128:
10099   case Intrinsic::x86_avx2_phsub_w:
10100   case Intrinsic::x86_avx2_phsub_d: {
10101     unsigned Opcode;
10102     switch (IntNo) {
10103     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10104     case Intrinsic::x86_sse3_hadd_ps:
10105     case Intrinsic::x86_sse3_hadd_pd:
10106     case Intrinsic::x86_avx_hadd_ps_256:
10107     case Intrinsic::x86_avx_hadd_pd_256:
10108       Opcode = X86ISD::FHADD;
10109       break;
10110     case Intrinsic::x86_sse3_hsub_ps:
10111     case Intrinsic::x86_sse3_hsub_pd:
10112     case Intrinsic::x86_avx_hsub_ps_256:
10113     case Intrinsic::x86_avx_hsub_pd_256:
10114       Opcode = X86ISD::FHSUB;
10115       break;
10116     case Intrinsic::x86_ssse3_phadd_w_128:
10117     case Intrinsic::x86_ssse3_phadd_d_128:
10118     case Intrinsic::x86_avx2_phadd_w:
10119     case Intrinsic::x86_avx2_phadd_d:
10120       Opcode = X86ISD::HADD;
10121       break;
10122     case Intrinsic::x86_ssse3_phsub_w_128:
10123     case Intrinsic::x86_ssse3_phsub_d_128:
10124     case Intrinsic::x86_avx2_phsub_w:
10125     case Intrinsic::x86_avx2_phsub_d:
10126       Opcode = X86ISD::HSUB;
10127       break;
10128     }
10129     return DAG.getNode(Opcode, dl, Op.getValueType(),
10130                        Op.getOperand(1), Op.getOperand(2));
10131   }
10132
10133   // AVX2 variable shift intrinsics
10134   case Intrinsic::x86_avx2_psllv_d:
10135   case Intrinsic::x86_avx2_psllv_q:
10136   case Intrinsic::x86_avx2_psllv_d_256:
10137   case Intrinsic::x86_avx2_psllv_q_256:
10138   case Intrinsic::x86_avx2_psrlv_d:
10139   case Intrinsic::x86_avx2_psrlv_q:
10140   case Intrinsic::x86_avx2_psrlv_d_256:
10141   case Intrinsic::x86_avx2_psrlv_q_256:
10142   case Intrinsic::x86_avx2_psrav_d:
10143   case Intrinsic::x86_avx2_psrav_d_256: {
10144     unsigned Opcode;
10145     switch (IntNo) {
10146     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10147     case Intrinsic::x86_avx2_psllv_d:
10148     case Intrinsic::x86_avx2_psllv_q:
10149     case Intrinsic::x86_avx2_psllv_d_256:
10150     case Intrinsic::x86_avx2_psllv_q_256:
10151       Opcode = ISD::SHL;
10152       break;
10153     case Intrinsic::x86_avx2_psrlv_d:
10154     case Intrinsic::x86_avx2_psrlv_q:
10155     case Intrinsic::x86_avx2_psrlv_d_256:
10156     case Intrinsic::x86_avx2_psrlv_q_256:
10157       Opcode = ISD::SRL;
10158       break;
10159     case Intrinsic::x86_avx2_psrav_d:
10160     case Intrinsic::x86_avx2_psrav_d_256:
10161       Opcode = ISD::SRA;
10162       break;
10163     }
10164     return DAG.getNode(Opcode, dl, Op.getValueType(),
10165                        Op.getOperand(1), Op.getOperand(2));
10166   }
10167
10168   case Intrinsic::x86_ssse3_pshuf_b_128:
10169   case Intrinsic::x86_avx2_pshuf_b:
10170     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10171                        Op.getOperand(1), Op.getOperand(2));
10172
10173   case Intrinsic::x86_ssse3_psign_b_128:
10174   case Intrinsic::x86_ssse3_psign_w_128:
10175   case Intrinsic::x86_ssse3_psign_d_128:
10176   case Intrinsic::x86_avx2_psign_b:
10177   case Intrinsic::x86_avx2_psign_w:
10178   case Intrinsic::x86_avx2_psign_d:
10179     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10180                        Op.getOperand(1), Op.getOperand(2));
10181
10182   case Intrinsic::x86_sse41_insertps:
10183     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10184                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10185
10186   case Intrinsic::x86_avx_vperm2f128_ps_256:
10187   case Intrinsic::x86_avx_vperm2f128_pd_256:
10188   case Intrinsic::x86_avx_vperm2f128_si_256:
10189   case Intrinsic::x86_avx2_vperm2i128:
10190     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10191                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10192
10193   case Intrinsic::x86_avx2_permd:
10194   case Intrinsic::x86_avx2_permps:
10195     // Operands intentionally swapped. Mask is last operand to intrinsic,
10196     // but second operand for node/intruction.
10197     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10198                        Op.getOperand(2), Op.getOperand(1));
10199
10200   // ptest and testp intrinsics. The intrinsic these come from are designed to
10201   // return an integer value, not just an instruction so lower it to the ptest
10202   // or testp pattern and a setcc for the result.
10203   case Intrinsic::x86_sse41_ptestz:
10204   case Intrinsic::x86_sse41_ptestc:
10205   case Intrinsic::x86_sse41_ptestnzc:
10206   case Intrinsic::x86_avx_ptestz_256:
10207   case Intrinsic::x86_avx_ptestc_256:
10208   case Intrinsic::x86_avx_ptestnzc_256:
10209   case Intrinsic::x86_avx_vtestz_ps:
10210   case Intrinsic::x86_avx_vtestc_ps:
10211   case Intrinsic::x86_avx_vtestnzc_ps:
10212   case Intrinsic::x86_avx_vtestz_pd:
10213   case Intrinsic::x86_avx_vtestc_pd:
10214   case Intrinsic::x86_avx_vtestnzc_pd:
10215   case Intrinsic::x86_avx_vtestz_ps_256:
10216   case Intrinsic::x86_avx_vtestc_ps_256:
10217   case Intrinsic::x86_avx_vtestnzc_ps_256:
10218   case Intrinsic::x86_avx_vtestz_pd_256:
10219   case Intrinsic::x86_avx_vtestc_pd_256:
10220   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10221     bool IsTestPacked = false;
10222     unsigned X86CC;
10223     switch (IntNo) {
10224     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10225     case Intrinsic::x86_avx_vtestz_ps:
10226     case Intrinsic::x86_avx_vtestz_pd:
10227     case Intrinsic::x86_avx_vtestz_ps_256:
10228     case Intrinsic::x86_avx_vtestz_pd_256:
10229       IsTestPacked = true; // Fallthrough
10230     case Intrinsic::x86_sse41_ptestz:
10231     case Intrinsic::x86_avx_ptestz_256:
10232       // ZF = 1
10233       X86CC = X86::COND_E;
10234       break;
10235     case Intrinsic::x86_avx_vtestc_ps:
10236     case Intrinsic::x86_avx_vtestc_pd:
10237     case Intrinsic::x86_avx_vtestc_ps_256:
10238     case Intrinsic::x86_avx_vtestc_pd_256:
10239       IsTestPacked = true; // Fallthrough
10240     case Intrinsic::x86_sse41_ptestc:
10241     case Intrinsic::x86_avx_ptestc_256:
10242       // CF = 1
10243       X86CC = X86::COND_B;
10244       break;
10245     case Intrinsic::x86_avx_vtestnzc_ps:
10246     case Intrinsic::x86_avx_vtestnzc_pd:
10247     case Intrinsic::x86_avx_vtestnzc_ps_256:
10248     case Intrinsic::x86_avx_vtestnzc_pd_256:
10249       IsTestPacked = true; // Fallthrough
10250     case Intrinsic::x86_sse41_ptestnzc:
10251     case Intrinsic::x86_avx_ptestnzc_256:
10252       // ZF and CF = 0
10253       X86CC = X86::COND_A;
10254       break;
10255     }
10256
10257     SDValue LHS = Op.getOperand(1);
10258     SDValue RHS = Op.getOperand(2);
10259     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10260     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10261     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10262     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10263     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10264   }
10265
10266   // SSE/AVX shift intrinsics
10267   case Intrinsic::x86_sse2_psll_w:
10268   case Intrinsic::x86_sse2_psll_d:
10269   case Intrinsic::x86_sse2_psll_q:
10270   case Intrinsic::x86_avx2_psll_w:
10271   case Intrinsic::x86_avx2_psll_d:
10272   case Intrinsic::x86_avx2_psll_q:
10273   case Intrinsic::x86_sse2_psrl_w:
10274   case Intrinsic::x86_sse2_psrl_d:
10275   case Intrinsic::x86_sse2_psrl_q:
10276   case Intrinsic::x86_avx2_psrl_w:
10277   case Intrinsic::x86_avx2_psrl_d:
10278   case Intrinsic::x86_avx2_psrl_q:
10279   case Intrinsic::x86_sse2_psra_w:
10280   case Intrinsic::x86_sse2_psra_d:
10281   case Intrinsic::x86_avx2_psra_w:
10282   case Intrinsic::x86_avx2_psra_d: {
10283     unsigned Opcode;
10284     switch (IntNo) {
10285     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10286     case Intrinsic::x86_sse2_psll_w:
10287     case Intrinsic::x86_sse2_psll_d:
10288     case Intrinsic::x86_sse2_psll_q:
10289     case Intrinsic::x86_avx2_psll_w:
10290     case Intrinsic::x86_avx2_psll_d:
10291     case Intrinsic::x86_avx2_psll_q:
10292       Opcode = X86ISD::VSHL;
10293       break;
10294     case Intrinsic::x86_sse2_psrl_w:
10295     case Intrinsic::x86_sse2_psrl_d:
10296     case Intrinsic::x86_sse2_psrl_q:
10297     case Intrinsic::x86_avx2_psrl_w:
10298     case Intrinsic::x86_avx2_psrl_d:
10299     case Intrinsic::x86_avx2_psrl_q:
10300       Opcode = X86ISD::VSRL;
10301       break;
10302     case Intrinsic::x86_sse2_psra_w:
10303     case Intrinsic::x86_sse2_psra_d:
10304     case Intrinsic::x86_avx2_psra_w:
10305     case Intrinsic::x86_avx2_psra_d:
10306       Opcode = X86ISD::VSRA;
10307       break;
10308     }
10309     return DAG.getNode(Opcode, dl, Op.getValueType(),
10310                        Op.getOperand(1), Op.getOperand(2));
10311   }
10312
10313   // SSE/AVX immediate shift intrinsics
10314   case Intrinsic::x86_sse2_pslli_w:
10315   case Intrinsic::x86_sse2_pslli_d:
10316   case Intrinsic::x86_sse2_pslli_q:
10317   case Intrinsic::x86_avx2_pslli_w:
10318   case Intrinsic::x86_avx2_pslli_d:
10319   case Intrinsic::x86_avx2_pslli_q:
10320   case Intrinsic::x86_sse2_psrli_w:
10321   case Intrinsic::x86_sse2_psrli_d:
10322   case Intrinsic::x86_sse2_psrli_q:
10323   case Intrinsic::x86_avx2_psrli_w:
10324   case Intrinsic::x86_avx2_psrli_d:
10325   case Intrinsic::x86_avx2_psrli_q:
10326   case Intrinsic::x86_sse2_psrai_w:
10327   case Intrinsic::x86_sse2_psrai_d:
10328   case Intrinsic::x86_avx2_psrai_w:
10329   case Intrinsic::x86_avx2_psrai_d: {
10330     unsigned Opcode;
10331     switch (IntNo) {
10332     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10333     case Intrinsic::x86_sse2_pslli_w:
10334     case Intrinsic::x86_sse2_pslli_d:
10335     case Intrinsic::x86_sse2_pslli_q:
10336     case Intrinsic::x86_avx2_pslli_w:
10337     case Intrinsic::x86_avx2_pslli_d:
10338     case Intrinsic::x86_avx2_pslli_q:
10339       Opcode = X86ISD::VSHLI;
10340       break;
10341     case Intrinsic::x86_sse2_psrli_w:
10342     case Intrinsic::x86_sse2_psrli_d:
10343     case Intrinsic::x86_sse2_psrli_q:
10344     case Intrinsic::x86_avx2_psrli_w:
10345     case Intrinsic::x86_avx2_psrli_d:
10346     case Intrinsic::x86_avx2_psrli_q:
10347       Opcode = X86ISD::VSRLI;
10348       break;
10349     case Intrinsic::x86_sse2_psrai_w:
10350     case Intrinsic::x86_sse2_psrai_d:
10351     case Intrinsic::x86_avx2_psrai_w:
10352     case Intrinsic::x86_avx2_psrai_d:
10353       Opcode = X86ISD::VSRAI;
10354       break;
10355     }
10356     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10357                                Op.getOperand(1), Op.getOperand(2), DAG);
10358   }
10359
10360   case Intrinsic::x86_sse42_pcmpistria128:
10361   case Intrinsic::x86_sse42_pcmpestria128:
10362   case Intrinsic::x86_sse42_pcmpistric128:
10363   case Intrinsic::x86_sse42_pcmpestric128:
10364   case Intrinsic::x86_sse42_pcmpistrio128:
10365   case Intrinsic::x86_sse42_pcmpestrio128:
10366   case Intrinsic::x86_sse42_pcmpistris128:
10367   case Intrinsic::x86_sse42_pcmpestris128:
10368   case Intrinsic::x86_sse42_pcmpistriz128:
10369   case Intrinsic::x86_sse42_pcmpestriz128: {
10370     unsigned Opcode;
10371     unsigned X86CC;
10372     switch (IntNo) {
10373     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10374     case Intrinsic::x86_sse42_pcmpistria128:
10375       Opcode = X86ISD::PCMPISTRI;
10376       X86CC = X86::COND_A;
10377       break;
10378     case Intrinsic::x86_sse42_pcmpestria128:
10379       Opcode = X86ISD::PCMPESTRI;
10380       X86CC = X86::COND_A;
10381       break;
10382     case Intrinsic::x86_sse42_pcmpistric128:
10383       Opcode = X86ISD::PCMPISTRI;
10384       X86CC = X86::COND_B;
10385       break;
10386     case Intrinsic::x86_sse42_pcmpestric128:
10387       Opcode = X86ISD::PCMPESTRI;
10388       X86CC = X86::COND_B;
10389       break;
10390     case Intrinsic::x86_sse42_pcmpistrio128:
10391       Opcode = X86ISD::PCMPISTRI;
10392       X86CC = X86::COND_O;
10393       break;
10394     case Intrinsic::x86_sse42_pcmpestrio128:
10395       Opcode = X86ISD::PCMPESTRI;
10396       X86CC = X86::COND_O;
10397       break;
10398     case Intrinsic::x86_sse42_pcmpistris128:
10399       Opcode = X86ISD::PCMPISTRI;
10400       X86CC = X86::COND_S;
10401       break;
10402     case Intrinsic::x86_sse42_pcmpestris128:
10403       Opcode = X86ISD::PCMPESTRI;
10404       X86CC = X86::COND_S;
10405       break;
10406     case Intrinsic::x86_sse42_pcmpistriz128:
10407       Opcode = X86ISD::PCMPISTRI;
10408       X86CC = X86::COND_E;
10409       break;
10410     case Intrinsic::x86_sse42_pcmpestriz128:
10411       Opcode = X86ISD::PCMPESTRI;
10412       X86CC = X86::COND_E;
10413       break;
10414     }
10415     SmallVector<SDValue, 5> NewOps;
10416     NewOps.append(Op->op_begin()+1, Op->op_end());
10417     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10418     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10419     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10420                                 DAG.getConstant(X86CC, MVT::i8),
10421                                 SDValue(PCMP.getNode(), 1));
10422     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10423   }
10424
10425   case Intrinsic::x86_sse42_pcmpistri128:
10426   case Intrinsic::x86_sse42_pcmpestri128: {
10427     unsigned Opcode;
10428     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10429       Opcode = X86ISD::PCMPISTRI;
10430     else
10431       Opcode = X86ISD::PCMPESTRI;
10432
10433     SmallVector<SDValue, 5> NewOps;
10434     NewOps.append(Op->op_begin()+1, Op->op_end());
10435     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10436     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10437   }
10438   case Intrinsic::x86_fma_vfmadd_ps:
10439   case Intrinsic::x86_fma_vfmadd_pd:
10440   case Intrinsic::x86_fma_vfmsub_ps:
10441   case Intrinsic::x86_fma_vfmsub_pd:
10442   case Intrinsic::x86_fma_vfnmadd_ps:
10443   case Intrinsic::x86_fma_vfnmadd_pd:
10444   case Intrinsic::x86_fma_vfnmsub_ps:
10445   case Intrinsic::x86_fma_vfnmsub_pd:
10446   case Intrinsic::x86_fma_vfmaddsub_ps:
10447   case Intrinsic::x86_fma_vfmaddsub_pd:
10448   case Intrinsic::x86_fma_vfmsubadd_ps:
10449   case Intrinsic::x86_fma_vfmsubadd_pd:
10450   case Intrinsic::x86_fma_vfmadd_ps_256:
10451   case Intrinsic::x86_fma_vfmadd_pd_256:
10452   case Intrinsic::x86_fma_vfmsub_ps_256:
10453   case Intrinsic::x86_fma_vfmsub_pd_256:
10454   case Intrinsic::x86_fma_vfnmadd_ps_256:
10455   case Intrinsic::x86_fma_vfnmadd_pd_256:
10456   case Intrinsic::x86_fma_vfnmsub_ps_256:
10457   case Intrinsic::x86_fma_vfnmsub_pd_256:
10458   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10459   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10460   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10461   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10462     unsigned Opc;
10463     switch (IntNo) {
10464     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10465     case Intrinsic::x86_fma_vfmadd_ps:
10466     case Intrinsic::x86_fma_vfmadd_pd:
10467     case Intrinsic::x86_fma_vfmadd_ps_256:
10468     case Intrinsic::x86_fma_vfmadd_pd_256:
10469       Opc = X86ISD::FMADD;
10470       break;
10471     case Intrinsic::x86_fma_vfmsub_ps:
10472     case Intrinsic::x86_fma_vfmsub_pd:
10473     case Intrinsic::x86_fma_vfmsub_ps_256:
10474     case Intrinsic::x86_fma_vfmsub_pd_256:
10475       Opc = X86ISD::FMSUB;
10476       break;
10477     case Intrinsic::x86_fma_vfnmadd_ps:
10478     case Intrinsic::x86_fma_vfnmadd_pd:
10479     case Intrinsic::x86_fma_vfnmadd_ps_256:
10480     case Intrinsic::x86_fma_vfnmadd_pd_256:
10481       Opc = X86ISD::FNMADD;
10482       break;
10483     case Intrinsic::x86_fma_vfnmsub_ps:
10484     case Intrinsic::x86_fma_vfnmsub_pd:
10485     case Intrinsic::x86_fma_vfnmsub_ps_256:
10486     case Intrinsic::x86_fma_vfnmsub_pd_256:
10487       Opc = X86ISD::FNMSUB;
10488       break;
10489     case Intrinsic::x86_fma_vfmaddsub_ps:
10490     case Intrinsic::x86_fma_vfmaddsub_pd:
10491     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10492     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10493       Opc = X86ISD::FMADDSUB;
10494       break;
10495     case Intrinsic::x86_fma_vfmsubadd_ps:
10496     case Intrinsic::x86_fma_vfmsubadd_pd:
10497     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10498     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10499       Opc = X86ISD::FMSUBADD;
10500       break;
10501     }
10502
10503     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10504                        Op.getOperand(2), Op.getOperand(3));
10505   }
10506   }
10507 }
10508
10509 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10510   DebugLoc dl = Op.getDebugLoc();
10511   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10512   switch (IntNo) {
10513   default: return SDValue();    // Don't custom lower most intrinsics.
10514
10515   // RDRAND intrinsics.
10516   case Intrinsic::x86_rdrand_16:
10517   case Intrinsic::x86_rdrand_32:
10518   case Intrinsic::x86_rdrand_64: {
10519     // Emit the node with the right value type.
10520     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10521     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10522
10523     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10524     // return the value from Rand, which is always 0, casted to i32.
10525     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10526                       DAG.getConstant(1, Op->getValueType(1)),
10527                       DAG.getConstant(X86::COND_B, MVT::i32),
10528                       SDValue(Result.getNode(), 1) };
10529     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10530                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10531                                   Ops, 4);
10532
10533     // Return { result, isValid, chain }.
10534     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10535                        SDValue(Result.getNode(), 2));
10536   }
10537   }
10538 }
10539
10540 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10541                                            SelectionDAG &DAG) const {
10542   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10543   MFI->setReturnAddressIsTaken(true);
10544
10545   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10546   DebugLoc dl = Op.getDebugLoc();
10547   EVT PtrVT = getPointerTy();
10548
10549   if (Depth > 0) {
10550     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10551     SDValue Offset =
10552       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10553     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10554                        DAG.getNode(ISD::ADD, dl, PtrVT,
10555                                    FrameAddr, Offset),
10556                        MachinePointerInfo(), false, false, false, 0);
10557   }
10558
10559   // Just load the return address.
10560   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10561   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10562                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10563 }
10564
10565 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10566   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10567   MFI->setFrameAddressIsTaken(true);
10568
10569   EVT VT = Op.getValueType();
10570   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10571   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10572   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10573   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10574   while (Depth--)
10575     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10576                             MachinePointerInfo(),
10577                             false, false, false, 0);
10578   return FrameAddr;
10579 }
10580
10581 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10582                                                      SelectionDAG &DAG) const {
10583   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10584 }
10585
10586 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10587   SDValue Chain     = Op.getOperand(0);
10588   SDValue Offset    = Op.getOperand(1);
10589   SDValue Handler   = Op.getOperand(2);
10590   DebugLoc dl       = Op.getDebugLoc();
10591
10592   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10593                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10594                                      getPointerTy());
10595   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10596
10597   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10598                                   DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10599   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10600   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10601                        false, false, 0);
10602   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10603
10604   return DAG.getNode(X86ISD::EH_RETURN, dl,
10605                      MVT::Other,
10606                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10607 }
10608
10609 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10610                                                SelectionDAG &DAG) const {
10611   DebugLoc DL = Op.getDebugLoc();
10612   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10613                      DAG.getVTList(MVT::i32, MVT::Other),
10614                      Op.getOperand(0), Op.getOperand(1));
10615 }
10616
10617 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10618                                                 SelectionDAG &DAG) const {
10619   DebugLoc DL = Op.getDebugLoc();
10620   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10621                      Op.getOperand(0), Op.getOperand(1));
10622 }
10623
10624 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10625   return Op.getOperand(0);
10626 }
10627
10628 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10629                                                 SelectionDAG &DAG) const {
10630   SDValue Root = Op.getOperand(0);
10631   SDValue Trmp = Op.getOperand(1); // trampoline
10632   SDValue FPtr = Op.getOperand(2); // nested function
10633   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10634   DebugLoc dl  = Op.getDebugLoc();
10635
10636   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10637   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10638
10639   if (Subtarget->is64Bit()) {
10640     SDValue OutChains[6];
10641
10642     // Large code-model.
10643     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10644     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10645
10646     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10647     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10648
10649     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10650
10651     // Load the pointer to the nested function into R11.
10652     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10653     SDValue Addr = Trmp;
10654     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10655                                 Addr, MachinePointerInfo(TrmpAddr),
10656                                 false, false, 0);
10657
10658     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10659                        DAG.getConstant(2, MVT::i64));
10660     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10661                                 MachinePointerInfo(TrmpAddr, 2),
10662                                 false, false, 2);
10663
10664     // Load the 'nest' parameter value into R10.
10665     // R10 is specified in X86CallingConv.td
10666     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10667     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10668                        DAG.getConstant(10, MVT::i64));
10669     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10670                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10671                                 false, false, 0);
10672
10673     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10674                        DAG.getConstant(12, MVT::i64));
10675     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10676                                 MachinePointerInfo(TrmpAddr, 12),
10677                                 false, false, 2);
10678
10679     // Jump to the nested function.
10680     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10681     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10682                        DAG.getConstant(20, MVT::i64));
10683     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10684                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10685                                 false, false, 0);
10686
10687     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10688     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10689                        DAG.getConstant(22, MVT::i64));
10690     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10691                                 MachinePointerInfo(TrmpAddr, 22),
10692                                 false, false, 0);
10693
10694     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10695   } else {
10696     const Function *Func =
10697       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10698     CallingConv::ID CC = Func->getCallingConv();
10699     unsigned NestReg;
10700
10701     switch (CC) {
10702     default:
10703       llvm_unreachable("Unsupported calling convention");
10704     case CallingConv::C:
10705     case CallingConv::X86_StdCall: {
10706       // Pass 'nest' parameter in ECX.
10707       // Must be kept in sync with X86CallingConv.td
10708       NestReg = X86::ECX;
10709
10710       // Check that ECX wasn't needed by an 'inreg' parameter.
10711       FunctionType *FTy = Func->getFunctionType();
10712       const AttrListPtr &Attrs = Func->getAttributes();
10713
10714       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10715         unsigned InRegCount = 0;
10716         unsigned Idx = 1;
10717
10718         for (FunctionType::param_iterator I = FTy->param_begin(),
10719              E = FTy->param_end(); I != E; ++I, ++Idx)
10720           if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10721             // FIXME: should only count parameters that are lowered to integers.
10722             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10723
10724         if (InRegCount > 2) {
10725           report_fatal_error("Nest register in use - reduce number of inreg"
10726                              " parameters!");
10727         }
10728       }
10729       break;
10730     }
10731     case CallingConv::X86_FastCall:
10732     case CallingConv::X86_ThisCall:
10733     case CallingConv::Fast:
10734       // Pass 'nest' parameter in EAX.
10735       // Must be kept in sync with X86CallingConv.td
10736       NestReg = X86::EAX;
10737       break;
10738     }
10739
10740     SDValue OutChains[4];
10741     SDValue Addr, Disp;
10742
10743     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10744                        DAG.getConstant(10, MVT::i32));
10745     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10746
10747     // This is storing the opcode for MOV32ri.
10748     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10749     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10750     OutChains[0] = DAG.getStore(Root, dl,
10751                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10752                                 Trmp, MachinePointerInfo(TrmpAddr),
10753                                 false, false, 0);
10754
10755     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10756                        DAG.getConstant(1, MVT::i32));
10757     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10758                                 MachinePointerInfo(TrmpAddr, 1),
10759                                 false, false, 1);
10760
10761     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10762     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10763                        DAG.getConstant(5, MVT::i32));
10764     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10765                                 MachinePointerInfo(TrmpAddr, 5),
10766                                 false, false, 1);
10767
10768     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10769                        DAG.getConstant(6, MVT::i32));
10770     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10771                                 MachinePointerInfo(TrmpAddr, 6),
10772                                 false, false, 1);
10773
10774     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10775   }
10776 }
10777
10778 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10779                                             SelectionDAG &DAG) const {
10780   /*
10781    The rounding mode is in bits 11:10 of FPSR, and has the following
10782    settings:
10783      00 Round to nearest
10784      01 Round to -inf
10785      10 Round to +inf
10786      11 Round to 0
10787
10788   FLT_ROUNDS, on the other hand, expects the following:
10789     -1 Undefined
10790      0 Round to 0
10791      1 Round to nearest
10792      2 Round to +inf
10793      3 Round to -inf
10794
10795   To perform the conversion, we do:
10796     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10797   */
10798
10799   MachineFunction &MF = DAG.getMachineFunction();
10800   const TargetMachine &TM = MF.getTarget();
10801   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10802   unsigned StackAlignment = TFI.getStackAlignment();
10803   EVT VT = Op.getValueType();
10804   DebugLoc DL = Op.getDebugLoc();
10805
10806   // Save FP Control Word to stack slot
10807   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10808   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10809
10810
10811   MachineMemOperand *MMO =
10812    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10813                            MachineMemOperand::MOStore, 2, 2);
10814
10815   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10816   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10817                                           DAG.getVTList(MVT::Other),
10818                                           Ops, 2, MVT::i16, MMO);
10819
10820   // Load FP Control Word from stack slot
10821   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10822                             MachinePointerInfo(), false, false, false, 0);
10823
10824   // Transform as necessary
10825   SDValue CWD1 =
10826     DAG.getNode(ISD::SRL, DL, MVT::i16,
10827                 DAG.getNode(ISD::AND, DL, MVT::i16,
10828                             CWD, DAG.getConstant(0x800, MVT::i16)),
10829                 DAG.getConstant(11, MVT::i8));
10830   SDValue CWD2 =
10831     DAG.getNode(ISD::SRL, DL, MVT::i16,
10832                 DAG.getNode(ISD::AND, DL, MVT::i16,
10833                             CWD, DAG.getConstant(0x400, MVT::i16)),
10834                 DAG.getConstant(9, MVT::i8));
10835
10836   SDValue RetVal =
10837     DAG.getNode(ISD::AND, DL, MVT::i16,
10838                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10839                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10840                             DAG.getConstant(1, MVT::i16)),
10841                 DAG.getConstant(3, MVT::i16));
10842
10843
10844   return DAG.getNode((VT.getSizeInBits() < 16 ?
10845                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10846 }
10847
10848 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10849   EVT VT = Op.getValueType();
10850   EVT OpVT = VT;
10851   unsigned NumBits = VT.getSizeInBits();
10852   DebugLoc dl = Op.getDebugLoc();
10853
10854   Op = Op.getOperand(0);
10855   if (VT == MVT::i8) {
10856     // Zero extend to i32 since there is not an i8 bsr.
10857     OpVT = MVT::i32;
10858     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10859   }
10860
10861   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10862   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10863   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10864
10865   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10866   SDValue Ops[] = {
10867     Op,
10868     DAG.getConstant(NumBits+NumBits-1, OpVT),
10869     DAG.getConstant(X86::COND_E, MVT::i8),
10870     Op.getValue(1)
10871   };
10872   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10873
10874   // Finally xor with NumBits-1.
10875   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10876
10877   if (VT == MVT::i8)
10878     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10879   return Op;
10880 }
10881
10882 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10883   EVT VT = Op.getValueType();
10884   EVT OpVT = VT;
10885   unsigned NumBits = VT.getSizeInBits();
10886   DebugLoc dl = Op.getDebugLoc();
10887
10888   Op = Op.getOperand(0);
10889   if (VT == MVT::i8) {
10890     // Zero extend to i32 since there is not an i8 bsr.
10891     OpVT = MVT::i32;
10892     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10893   }
10894
10895   // Issue a bsr (scan bits in reverse).
10896   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10897   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10898
10899   // And xor with NumBits-1.
10900   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10901
10902   if (VT == MVT::i8)
10903     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10904   return Op;
10905 }
10906
10907 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10908   EVT VT = Op.getValueType();
10909   unsigned NumBits = VT.getSizeInBits();
10910   DebugLoc dl = Op.getDebugLoc();
10911   Op = Op.getOperand(0);
10912
10913   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10914   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10915   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10916
10917   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10918   SDValue Ops[] = {
10919     Op,
10920     DAG.getConstant(NumBits, VT),
10921     DAG.getConstant(X86::COND_E, MVT::i8),
10922     Op.getValue(1)
10923   };
10924   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10925 }
10926
10927 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10928 // ones, and then concatenate the result back.
10929 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10930   EVT VT = Op.getValueType();
10931
10932   assert(VT.is256BitVector() && VT.isInteger() &&
10933          "Unsupported value type for operation");
10934
10935   unsigned NumElems = VT.getVectorNumElements();
10936   DebugLoc dl = Op.getDebugLoc();
10937
10938   // Extract the LHS vectors
10939   SDValue LHS = Op.getOperand(0);
10940   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10941   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10942
10943   // Extract the RHS vectors
10944   SDValue RHS = Op.getOperand(1);
10945   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10946   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10947
10948   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10949   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10950
10951   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10952                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10953                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10954 }
10955
10956 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10957   assert(Op.getValueType().is256BitVector() &&
10958          Op.getValueType().isInteger() &&
10959          "Only handle AVX 256-bit vector integer operation");
10960   return Lower256IntArith(Op, DAG);
10961 }
10962
10963 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10964   assert(Op.getValueType().is256BitVector() &&
10965          Op.getValueType().isInteger() &&
10966          "Only handle AVX 256-bit vector integer operation");
10967   return Lower256IntArith(Op, DAG);
10968 }
10969
10970 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10971                         SelectionDAG &DAG) {
10972   EVT VT = Op.getValueType();
10973
10974   // Decompose 256-bit ops into smaller 128-bit ops.
10975   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10976     return Lower256IntArith(Op, DAG);
10977
10978   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10979          "Only know how to lower V2I64/V4I64 multiply");
10980
10981   DebugLoc dl = Op.getDebugLoc();
10982
10983   //  Ahi = psrlqi(a, 32);
10984   //  Bhi = psrlqi(b, 32);
10985   //
10986   //  AloBlo = pmuludq(a, b);
10987   //  AloBhi = pmuludq(a, Bhi);
10988   //  AhiBlo = pmuludq(Ahi, b);
10989
10990   //  AloBhi = psllqi(AloBhi, 32);
10991   //  AhiBlo = psllqi(AhiBlo, 32);
10992   //  return AloBlo + AloBhi + AhiBlo;
10993
10994   SDValue A = Op.getOperand(0);
10995   SDValue B = Op.getOperand(1);
10996
10997   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10998
10999   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11000   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11001
11002   // Bit cast to 32-bit vectors for MULUDQ
11003   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11004   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11005   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11006   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11007   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11008
11009   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11010   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11011   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11012
11013   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11014   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11015
11016   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11017   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11018 }
11019
11020 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11021
11022   EVT VT = Op.getValueType();
11023   DebugLoc dl = Op.getDebugLoc();
11024   SDValue R = Op.getOperand(0);
11025   SDValue Amt = Op.getOperand(1);
11026   LLVMContext *Context = DAG.getContext();
11027
11028   if (!Subtarget->hasSSE2())
11029     return SDValue();
11030
11031   // Optimize shl/srl/sra with constant shift amount.
11032   if (isSplatVector(Amt.getNode())) {
11033     SDValue SclrAmt = Amt->getOperand(0);
11034     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11035       uint64_t ShiftAmt = C->getZExtValue();
11036
11037       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11038           (Subtarget->hasAVX2() &&
11039            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11040         if (Op.getOpcode() == ISD::SHL)
11041           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11042                              DAG.getConstant(ShiftAmt, MVT::i32));
11043         if (Op.getOpcode() == ISD::SRL)
11044           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11045                              DAG.getConstant(ShiftAmt, MVT::i32));
11046         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11047           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11048                              DAG.getConstant(ShiftAmt, MVT::i32));
11049       }
11050
11051       if (VT == MVT::v16i8) {
11052         if (Op.getOpcode() == ISD::SHL) {
11053           // Make a large shift.
11054           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11055                                     DAG.getConstant(ShiftAmt, MVT::i32));
11056           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11057           // Zero out the rightmost bits.
11058           SmallVector<SDValue, 16> V(16,
11059                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11060                                                      MVT::i8));
11061           return DAG.getNode(ISD::AND, dl, VT, SHL,
11062                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11063         }
11064         if (Op.getOpcode() == ISD::SRL) {
11065           // Make a large shift.
11066           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11067                                     DAG.getConstant(ShiftAmt, MVT::i32));
11068           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11069           // Zero out the leftmost bits.
11070           SmallVector<SDValue, 16> V(16,
11071                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11072                                                      MVT::i8));
11073           return DAG.getNode(ISD::AND, dl, VT, SRL,
11074                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11075         }
11076         if (Op.getOpcode() == ISD::SRA) {
11077           if (ShiftAmt == 7) {
11078             // R s>> 7  ===  R s< 0
11079             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11080             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11081           }
11082
11083           // R s>> a === ((R u>> a) ^ m) - m
11084           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11085           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11086                                                          MVT::i8));
11087           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11088           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11089           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11090           return Res;
11091         }
11092         llvm_unreachable("Unknown shift opcode.");
11093       }
11094
11095       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
11096         if (Op.getOpcode() == ISD::SHL) {
11097           // Make a large shift.
11098           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11099                                     DAG.getConstant(ShiftAmt, MVT::i32));
11100           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11101           // Zero out the rightmost bits.
11102           SmallVector<SDValue, 32> V(32,
11103                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11104                                                      MVT::i8));
11105           return DAG.getNode(ISD::AND, dl, VT, SHL,
11106                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11107         }
11108         if (Op.getOpcode() == ISD::SRL) {
11109           // Make a large shift.
11110           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11111                                     DAG.getConstant(ShiftAmt, MVT::i32));
11112           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11113           // Zero out the leftmost bits.
11114           SmallVector<SDValue, 32> V(32,
11115                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11116                                                      MVT::i8));
11117           return DAG.getNode(ISD::AND, dl, VT, SRL,
11118                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11119         }
11120         if (Op.getOpcode() == ISD::SRA) {
11121           if (ShiftAmt == 7) {
11122             // R s>> 7  ===  R s< 0
11123             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11124             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11125           }
11126
11127           // R s>> a === ((R u>> a) ^ m) - m
11128           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11129           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11130                                                          MVT::i8));
11131           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11132           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11133           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11134           return Res;
11135         }
11136         llvm_unreachable("Unknown shift opcode.");
11137       }
11138     }
11139   }
11140
11141   // Lower SHL with variable shift amount.
11142   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11143     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11144                      DAG.getConstant(23, MVT::i32));
11145
11146     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11147     Constant *C = ConstantDataVector::get(*Context, CV);
11148     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11149     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11150                                  MachinePointerInfo::getConstantPool(),
11151                                  false, false, false, 16);
11152
11153     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11154     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11155     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11156     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11157   }
11158   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11159     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11160
11161     // a = a << 5;
11162     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11163                      DAG.getConstant(5, MVT::i32));
11164     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11165
11166     // Turn 'a' into a mask suitable for VSELECT
11167     SDValue VSelM = DAG.getConstant(0x80, VT);
11168     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11169     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11170
11171     SDValue CM1 = DAG.getConstant(0x0f, VT);
11172     SDValue CM2 = DAG.getConstant(0x3f, VT);
11173
11174     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11175     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11176     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11177                             DAG.getConstant(4, MVT::i32), DAG);
11178     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11179     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11180
11181     // a += a
11182     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11183     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11184     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11185
11186     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11187     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11188     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11189                             DAG.getConstant(2, MVT::i32), DAG);
11190     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11191     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11192
11193     // a += a
11194     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11195     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11196     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11197
11198     // return VSELECT(r, r+r, a);
11199     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11200                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11201     return R;
11202   }
11203
11204   // Decompose 256-bit shifts into smaller 128-bit shifts.
11205   if (VT.is256BitVector()) {
11206     unsigned NumElems = VT.getVectorNumElements();
11207     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11208     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11209
11210     // Extract the two vectors
11211     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11212     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11213
11214     // Recreate the shift amount vectors
11215     SDValue Amt1, Amt2;
11216     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11217       // Constant shift amount
11218       SmallVector<SDValue, 4> Amt1Csts;
11219       SmallVector<SDValue, 4> Amt2Csts;
11220       for (unsigned i = 0; i != NumElems/2; ++i)
11221         Amt1Csts.push_back(Amt->getOperand(i));
11222       for (unsigned i = NumElems/2; i != NumElems; ++i)
11223         Amt2Csts.push_back(Amt->getOperand(i));
11224
11225       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11226                                  &Amt1Csts[0], NumElems/2);
11227       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11228                                  &Amt2Csts[0], NumElems/2);
11229     } else {
11230       // Variable shift amount
11231       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11232       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11233     }
11234
11235     // Issue new vector shifts for the smaller types
11236     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11237     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11238
11239     // Concatenate the result back
11240     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11241   }
11242
11243   return SDValue();
11244 }
11245
11246 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11247   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11248   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11249   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11250   // has only one use.
11251   SDNode *N = Op.getNode();
11252   SDValue LHS = N->getOperand(0);
11253   SDValue RHS = N->getOperand(1);
11254   unsigned BaseOp = 0;
11255   unsigned Cond = 0;
11256   DebugLoc DL = Op.getDebugLoc();
11257   switch (Op.getOpcode()) {
11258   default: llvm_unreachable("Unknown ovf instruction!");
11259   case ISD::SADDO:
11260     // A subtract of one will be selected as a INC. Note that INC doesn't
11261     // set CF, so we can't do this for UADDO.
11262     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11263       if (C->isOne()) {
11264         BaseOp = X86ISD::INC;
11265         Cond = X86::COND_O;
11266         break;
11267       }
11268     BaseOp = X86ISD::ADD;
11269     Cond = X86::COND_O;
11270     break;
11271   case ISD::UADDO:
11272     BaseOp = X86ISD::ADD;
11273     Cond = X86::COND_B;
11274     break;
11275   case ISD::SSUBO:
11276     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11277     // set CF, so we can't do this for USUBO.
11278     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11279       if (C->isOne()) {
11280         BaseOp = X86ISD::DEC;
11281         Cond = X86::COND_O;
11282         break;
11283       }
11284     BaseOp = X86ISD::SUB;
11285     Cond = X86::COND_O;
11286     break;
11287   case ISD::USUBO:
11288     BaseOp = X86ISD::SUB;
11289     Cond = X86::COND_B;
11290     break;
11291   case ISD::SMULO:
11292     BaseOp = X86ISD::SMUL;
11293     Cond = X86::COND_O;
11294     break;
11295   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11296     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11297                                  MVT::i32);
11298     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11299
11300     SDValue SetCC =
11301       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11302                   DAG.getConstant(X86::COND_O, MVT::i32),
11303                   SDValue(Sum.getNode(), 2));
11304
11305     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11306   }
11307   }
11308
11309   // Also sets EFLAGS.
11310   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11311   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11312
11313   SDValue SetCC =
11314     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11315                 DAG.getConstant(Cond, MVT::i32),
11316                 SDValue(Sum.getNode(), 1));
11317
11318   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11319 }
11320
11321 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11322                                                   SelectionDAG &DAG) const {
11323   DebugLoc dl = Op.getDebugLoc();
11324   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11325   EVT VT = Op.getValueType();
11326
11327   if (!Subtarget->hasSSE2() || !VT.isVector())
11328     return SDValue();
11329
11330   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11331                       ExtraVT.getScalarType().getSizeInBits();
11332   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11333
11334   switch (VT.getSimpleVT().SimpleTy) {
11335     default: return SDValue();
11336     case MVT::v8i32:
11337     case MVT::v16i16:
11338       if (!Subtarget->hasAVX())
11339         return SDValue();
11340       if (!Subtarget->hasAVX2()) {
11341         // needs to be split
11342         unsigned NumElems = VT.getVectorNumElements();
11343
11344         // Extract the LHS vectors
11345         SDValue LHS = Op.getOperand(0);
11346         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11347         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11348
11349         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11350         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11351
11352         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11353         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11354         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11355                                    ExtraNumElems/2);
11356         SDValue Extra = DAG.getValueType(ExtraVT);
11357
11358         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11359         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11360
11361         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11362       }
11363       // fall through
11364     case MVT::v4i32:
11365     case MVT::v8i16: {
11366       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11367                                          Op.getOperand(0), ShAmt, DAG);
11368       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11369     }
11370   }
11371 }
11372
11373
11374 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11375                               SelectionDAG &DAG) {
11376   DebugLoc dl = Op.getDebugLoc();
11377
11378   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11379   // There isn't any reason to disable it if the target processor supports it.
11380   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11381     SDValue Chain = Op.getOperand(0);
11382     SDValue Zero = DAG.getConstant(0, MVT::i32);
11383     SDValue Ops[] = {
11384       DAG.getRegister(X86::ESP, MVT::i32), // Base
11385       DAG.getTargetConstant(1, MVT::i8),   // Scale
11386       DAG.getRegister(0, MVT::i32),        // Index
11387       DAG.getTargetConstant(0, MVT::i32),  // Disp
11388       DAG.getRegister(0, MVT::i32),        // Segment.
11389       Zero,
11390       Chain
11391     };
11392     SDNode *Res =
11393       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11394                           array_lengthof(Ops));
11395     return SDValue(Res, 0);
11396   }
11397
11398   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11399   if (!isDev)
11400     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11401
11402   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11403   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11404   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11405   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11406
11407   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11408   if (!Op1 && !Op2 && !Op3 && Op4)
11409     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11410
11411   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11412   if (Op1 && !Op2 && !Op3 && !Op4)
11413     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11414
11415   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11416   //           (MFENCE)>;
11417   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11418 }
11419
11420 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11421                                  SelectionDAG &DAG) {
11422   DebugLoc dl = Op.getDebugLoc();
11423   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11424     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11425   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11426     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11427
11428   // The only fence that needs an instruction is a sequentially-consistent
11429   // cross-thread fence.
11430   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11431     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11432     // no-sse2). There isn't any reason to disable it if the target processor
11433     // supports it.
11434     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11435       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11436
11437     SDValue Chain = Op.getOperand(0);
11438     SDValue Zero = DAG.getConstant(0, MVT::i32);
11439     SDValue Ops[] = {
11440       DAG.getRegister(X86::ESP, MVT::i32), // Base
11441       DAG.getTargetConstant(1, MVT::i8),   // Scale
11442       DAG.getRegister(0, MVT::i32),        // Index
11443       DAG.getTargetConstant(0, MVT::i32),  // Disp
11444       DAG.getRegister(0, MVT::i32),        // Segment.
11445       Zero,
11446       Chain
11447     };
11448     SDNode *Res =
11449       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11450                          array_lengthof(Ops));
11451     return SDValue(Res, 0);
11452   }
11453
11454   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11455   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11456 }
11457
11458
11459 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11460                              SelectionDAG &DAG) {
11461   EVT T = Op.getValueType();
11462   DebugLoc DL = Op.getDebugLoc();
11463   unsigned Reg = 0;
11464   unsigned size = 0;
11465   switch(T.getSimpleVT().SimpleTy) {
11466   default: llvm_unreachable("Invalid value type!");
11467   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11468   case MVT::i16: Reg = X86::AX;  size = 2; break;
11469   case MVT::i32: Reg = X86::EAX; size = 4; break;
11470   case MVT::i64:
11471     assert(Subtarget->is64Bit() && "Node not type legal!");
11472     Reg = X86::RAX; size = 8;
11473     break;
11474   }
11475   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11476                                     Op.getOperand(2), SDValue());
11477   SDValue Ops[] = { cpIn.getValue(0),
11478                     Op.getOperand(1),
11479                     Op.getOperand(3),
11480                     DAG.getTargetConstant(size, MVT::i8),
11481                     cpIn.getValue(1) };
11482   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11483   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11484   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11485                                            Ops, 5, T, MMO);
11486   SDValue cpOut =
11487     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11488   return cpOut;
11489 }
11490
11491 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11492                                      SelectionDAG &DAG) {
11493   assert(Subtarget->is64Bit() && "Result not type legalized?");
11494   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11495   SDValue TheChain = Op.getOperand(0);
11496   DebugLoc dl = Op.getDebugLoc();
11497   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11498   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11499   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11500                                    rax.getValue(2));
11501   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11502                             DAG.getConstant(32, MVT::i8));
11503   SDValue Ops[] = {
11504     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11505     rdx.getValue(1)
11506   };
11507   return DAG.getMergeValues(Ops, 2, dl);
11508 }
11509
11510 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11511   EVT SrcVT = Op.getOperand(0).getValueType();
11512   EVT DstVT = Op.getValueType();
11513   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11514          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11515   assert((DstVT == MVT::i64 ||
11516           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11517          "Unexpected custom BITCAST");
11518   // i64 <=> MMX conversions are Legal.
11519   if (SrcVT==MVT::i64 && DstVT.isVector())
11520     return Op;
11521   if (DstVT==MVT::i64 && SrcVT.isVector())
11522     return Op;
11523   // MMX <=> MMX conversions are Legal.
11524   if (SrcVT.isVector() && DstVT.isVector())
11525     return Op;
11526   // All other conversions need to be expanded.
11527   return SDValue();
11528 }
11529
11530 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11531   SDNode *Node = Op.getNode();
11532   DebugLoc dl = Node->getDebugLoc();
11533   EVT T = Node->getValueType(0);
11534   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11535                               DAG.getConstant(0, T), Node->getOperand(2));
11536   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11537                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11538                        Node->getOperand(0),
11539                        Node->getOperand(1), negOp,
11540                        cast<AtomicSDNode>(Node)->getSrcValue(),
11541                        cast<AtomicSDNode>(Node)->getAlignment(),
11542                        cast<AtomicSDNode>(Node)->getOrdering(),
11543                        cast<AtomicSDNode>(Node)->getSynchScope());
11544 }
11545
11546 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11547   SDNode *Node = Op.getNode();
11548   DebugLoc dl = Node->getDebugLoc();
11549   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11550
11551   // Convert seq_cst store -> xchg
11552   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11553   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11554   //        (The only way to get a 16-byte store is cmpxchg16b)
11555   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11556   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11557       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11558     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11559                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11560                                  Node->getOperand(0),
11561                                  Node->getOperand(1), Node->getOperand(2),
11562                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11563                                  cast<AtomicSDNode>(Node)->getOrdering(),
11564                                  cast<AtomicSDNode>(Node)->getSynchScope());
11565     return Swap.getValue(1);
11566   }
11567   // Other atomic stores have a simple pattern.
11568   return Op;
11569 }
11570
11571 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11572   EVT VT = Op.getNode()->getValueType(0);
11573
11574   // Let legalize expand this if it isn't a legal type yet.
11575   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11576     return SDValue();
11577
11578   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11579
11580   unsigned Opc;
11581   bool ExtraOp = false;
11582   switch (Op.getOpcode()) {
11583   default: llvm_unreachable("Invalid code");
11584   case ISD::ADDC: Opc = X86ISD::ADD; break;
11585   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11586   case ISD::SUBC: Opc = X86ISD::SUB; break;
11587   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11588   }
11589
11590   if (!ExtraOp)
11591     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11592                        Op.getOperand(1));
11593   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11594                      Op.getOperand(1), Op.getOperand(2));
11595 }
11596
11597 /// LowerOperation - Provide custom lowering hooks for some operations.
11598 ///
11599 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11600   switch (Op.getOpcode()) {
11601   default: llvm_unreachable("Should not custom lower this!");
11602   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11603   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11604   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11605   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11606   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11607   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11608   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11609   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11610   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11611   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11612   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11613   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11614   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11615   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11616   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11617   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11618   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11619   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11620   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11621   case ISD::SHL_PARTS:
11622   case ISD::SRA_PARTS:
11623   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11624   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11625   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11626   case ISD::TRUNCATE:           return lowerTRUNCATE(Op, DAG);
11627   case ISD::ZERO_EXTEND:        return lowerZERO_EXTEND(Op, DAG);
11628   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11629   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11630   case ISD::FP_EXTEND:          return lowerFP_EXTEND(Op, DAG);
11631   case ISD::FABS:               return LowerFABS(Op, DAG);
11632   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11633   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11634   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11635   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11636   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11637   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11638   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11639   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11640   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11641   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11642   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11643   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11644   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11645   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11646   case ISD::FRAME_TO_ARGS_OFFSET:
11647                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11648   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11649   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11650   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11651   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11652   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11653   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11654   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11655   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11656   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11657   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11658   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11659   case ISD::SRA:
11660   case ISD::SRL:
11661   case ISD::SHL:                return LowerShift(Op, DAG);
11662   case ISD::SADDO:
11663   case ISD::UADDO:
11664   case ISD::SSUBO:
11665   case ISD::USUBO:
11666   case ISD::SMULO:
11667   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11668   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11669   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11670   case ISD::ADDC:
11671   case ISD::ADDE:
11672   case ISD::SUBC:
11673   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11674   case ISD::ADD:                return LowerADD(Op, DAG);
11675   case ISD::SUB:                return LowerSUB(Op, DAG);
11676   }
11677 }
11678
11679 static void ReplaceATOMIC_LOAD(SDNode *Node,
11680                                   SmallVectorImpl<SDValue> &Results,
11681                                   SelectionDAG &DAG) {
11682   DebugLoc dl = Node->getDebugLoc();
11683   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11684
11685   // Convert wide load -> cmpxchg8b/cmpxchg16b
11686   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11687   //        (The only way to get a 16-byte load is cmpxchg16b)
11688   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11689   SDValue Zero = DAG.getConstant(0, VT);
11690   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11691                                Node->getOperand(0),
11692                                Node->getOperand(1), Zero, Zero,
11693                                cast<AtomicSDNode>(Node)->getMemOperand(),
11694                                cast<AtomicSDNode>(Node)->getOrdering(),
11695                                cast<AtomicSDNode>(Node)->getSynchScope());
11696   Results.push_back(Swap.getValue(0));
11697   Results.push_back(Swap.getValue(1));
11698 }
11699
11700 static void
11701 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11702                         SelectionDAG &DAG, unsigned NewOp) {
11703   DebugLoc dl = Node->getDebugLoc();
11704   assert (Node->getValueType(0) == MVT::i64 &&
11705           "Only know how to expand i64 atomics");
11706
11707   SDValue Chain = Node->getOperand(0);
11708   SDValue In1 = Node->getOperand(1);
11709   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11710                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11711   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11712                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11713   SDValue Ops[] = { Chain, In1, In2L, In2H };
11714   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11715   SDValue Result =
11716     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11717                             cast<MemSDNode>(Node)->getMemOperand());
11718   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11719   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11720   Results.push_back(Result.getValue(2));
11721 }
11722
11723 /// ReplaceNodeResults - Replace a node with an illegal result type
11724 /// with a new node built out of custom code.
11725 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11726                                            SmallVectorImpl<SDValue>&Results,
11727                                            SelectionDAG &DAG) const {
11728   DebugLoc dl = N->getDebugLoc();
11729   switch (N->getOpcode()) {
11730   default:
11731     llvm_unreachable("Do not know how to custom type legalize this operation!");
11732   case ISD::SIGN_EXTEND_INREG:
11733   case ISD::ADDC:
11734   case ISD::ADDE:
11735   case ISD::SUBC:
11736   case ISD::SUBE:
11737     // We don't want to expand or promote these.
11738     return;
11739   case ISD::FP_TO_SINT:
11740   case ISD::FP_TO_UINT: {
11741     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11742
11743     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11744       return;
11745
11746     std::pair<SDValue,SDValue> Vals =
11747         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11748     SDValue FIST = Vals.first, StackSlot = Vals.second;
11749     if (FIST.getNode() != 0) {
11750       EVT VT = N->getValueType(0);
11751       // Return a load from the stack slot.
11752       if (StackSlot.getNode() != 0)
11753         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11754                                       MachinePointerInfo(),
11755                                       false, false, false, 0));
11756       else
11757         Results.push_back(FIST);
11758     }
11759     return;
11760   }
11761   case ISD::UINT_TO_FP: {
11762     if (N->getOperand(0).getValueType() != MVT::v2i32 &&
11763         N->getValueType(0) != MVT::v2f32)
11764       return;
11765     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
11766                                  N->getOperand(0));
11767     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11768                                      MVT::f64);
11769     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
11770     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
11771                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
11772     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
11773     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
11774     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
11775     return;
11776   }
11777   case ISD::FP_ROUND: {
11778     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11779     Results.push_back(V);
11780     return;
11781   }
11782   case ISD::READCYCLECOUNTER: {
11783     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11784     SDValue TheChain = N->getOperand(0);
11785     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11786     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11787                                      rd.getValue(1));
11788     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11789                                      eax.getValue(2));
11790     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11791     SDValue Ops[] = { eax, edx };
11792     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11793     Results.push_back(edx.getValue(1));
11794     return;
11795   }
11796   case ISD::ATOMIC_CMP_SWAP: {
11797     EVT T = N->getValueType(0);
11798     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11799     bool Regs64bit = T == MVT::i128;
11800     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11801     SDValue cpInL, cpInH;
11802     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11803                         DAG.getConstant(0, HalfT));
11804     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11805                         DAG.getConstant(1, HalfT));
11806     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11807                              Regs64bit ? X86::RAX : X86::EAX,
11808                              cpInL, SDValue());
11809     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11810                              Regs64bit ? X86::RDX : X86::EDX,
11811                              cpInH, cpInL.getValue(1));
11812     SDValue swapInL, swapInH;
11813     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11814                           DAG.getConstant(0, HalfT));
11815     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11816                           DAG.getConstant(1, HalfT));
11817     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11818                                Regs64bit ? X86::RBX : X86::EBX,
11819                                swapInL, cpInH.getValue(1));
11820     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11821                                Regs64bit ? X86::RCX : X86::ECX,
11822                                swapInH, swapInL.getValue(1));
11823     SDValue Ops[] = { swapInH.getValue(0),
11824                       N->getOperand(1),
11825                       swapInH.getValue(1) };
11826     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11827     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11828     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11829                                   X86ISD::LCMPXCHG8_DAG;
11830     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11831                                              Ops, 3, T, MMO);
11832     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11833                                         Regs64bit ? X86::RAX : X86::EAX,
11834                                         HalfT, Result.getValue(1));
11835     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11836                                         Regs64bit ? X86::RDX : X86::EDX,
11837                                         HalfT, cpOutL.getValue(2));
11838     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11839     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11840     Results.push_back(cpOutH.getValue(1));
11841     return;
11842   }
11843   case ISD::ATOMIC_LOAD_ADD:
11844   case ISD::ATOMIC_LOAD_AND:
11845   case ISD::ATOMIC_LOAD_NAND:
11846   case ISD::ATOMIC_LOAD_OR:
11847   case ISD::ATOMIC_LOAD_SUB:
11848   case ISD::ATOMIC_LOAD_XOR:
11849   case ISD::ATOMIC_LOAD_MAX:
11850   case ISD::ATOMIC_LOAD_MIN:
11851   case ISD::ATOMIC_LOAD_UMAX:
11852   case ISD::ATOMIC_LOAD_UMIN:
11853   case ISD::ATOMIC_SWAP: {
11854     unsigned Opc;
11855     switch (N->getOpcode()) {
11856     default: llvm_unreachable("Unexpected opcode");
11857     case ISD::ATOMIC_LOAD_ADD:
11858       Opc = X86ISD::ATOMADD64_DAG;
11859       break;
11860     case ISD::ATOMIC_LOAD_AND:
11861       Opc = X86ISD::ATOMAND64_DAG;
11862       break;
11863     case ISD::ATOMIC_LOAD_NAND:
11864       Opc = X86ISD::ATOMNAND64_DAG;
11865       break;
11866     case ISD::ATOMIC_LOAD_OR:
11867       Opc = X86ISD::ATOMOR64_DAG;
11868       break;
11869     case ISD::ATOMIC_LOAD_SUB:
11870       Opc = X86ISD::ATOMSUB64_DAG;
11871       break;
11872     case ISD::ATOMIC_LOAD_XOR:
11873       Opc = X86ISD::ATOMXOR64_DAG;
11874       break;
11875     case ISD::ATOMIC_LOAD_MAX:
11876       Opc = X86ISD::ATOMMAX64_DAG;
11877       break;
11878     case ISD::ATOMIC_LOAD_MIN:
11879       Opc = X86ISD::ATOMMIN64_DAG;
11880       break;
11881     case ISD::ATOMIC_LOAD_UMAX:
11882       Opc = X86ISD::ATOMUMAX64_DAG;
11883       break;
11884     case ISD::ATOMIC_LOAD_UMIN:
11885       Opc = X86ISD::ATOMUMIN64_DAG;
11886       break;
11887     case ISD::ATOMIC_SWAP:
11888       Opc = X86ISD::ATOMSWAP64_DAG;
11889       break;
11890     }
11891     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11892     return;
11893   }
11894   case ISD::ATOMIC_LOAD:
11895     ReplaceATOMIC_LOAD(N, Results, DAG);
11896   }
11897 }
11898
11899 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11900   switch (Opcode) {
11901   default: return NULL;
11902   case X86ISD::BSF:                return "X86ISD::BSF";
11903   case X86ISD::BSR:                return "X86ISD::BSR";
11904   case X86ISD::SHLD:               return "X86ISD::SHLD";
11905   case X86ISD::SHRD:               return "X86ISD::SHRD";
11906   case X86ISD::FAND:               return "X86ISD::FAND";
11907   case X86ISD::FOR:                return "X86ISD::FOR";
11908   case X86ISD::FXOR:               return "X86ISD::FXOR";
11909   case X86ISD::FSRL:               return "X86ISD::FSRL";
11910   case X86ISD::FILD:               return "X86ISD::FILD";
11911   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11912   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11913   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11914   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11915   case X86ISD::FLD:                return "X86ISD::FLD";
11916   case X86ISD::FST:                return "X86ISD::FST";
11917   case X86ISD::CALL:               return "X86ISD::CALL";
11918   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11919   case X86ISD::BT:                 return "X86ISD::BT";
11920   case X86ISD::CMP:                return "X86ISD::CMP";
11921   case X86ISD::COMI:               return "X86ISD::COMI";
11922   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11923   case X86ISD::SETCC:              return "X86ISD::SETCC";
11924   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11925   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11926   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11927   case X86ISD::CMOV:               return "X86ISD::CMOV";
11928   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11929   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11930   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11931   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11932   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11933   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11934   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11935   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11936   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11937   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11938   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11939   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11940   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11941   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11942   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11943   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11944   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11945   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11946   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11947   case X86ISD::HADD:               return "X86ISD::HADD";
11948   case X86ISD::HSUB:               return "X86ISD::HSUB";
11949   case X86ISD::FHADD:              return "X86ISD::FHADD";
11950   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11951   case X86ISD::FMAX:               return "X86ISD::FMAX";
11952   case X86ISD::FMIN:               return "X86ISD::FMIN";
11953   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11954   case X86ISD::FMINC:              return "X86ISD::FMINC";
11955   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11956   case X86ISD::FRCP:               return "X86ISD::FRCP";
11957   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11958   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11959   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11960   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
11961   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
11962   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11963   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11964   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11965   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11966   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11967   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11968   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11969   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11970   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11971   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11972   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11973   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11974   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11975   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11976   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11977   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
11978   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
11979   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11980   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
11981   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11982   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11983   case X86ISD::VSHL:               return "X86ISD::VSHL";
11984   case X86ISD::VSRL:               return "X86ISD::VSRL";
11985   case X86ISD::VSRA:               return "X86ISD::VSRA";
11986   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11987   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11988   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11989   case X86ISD::CMPP:               return "X86ISD::CMPP";
11990   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11991   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11992   case X86ISD::ADD:                return "X86ISD::ADD";
11993   case X86ISD::SUB:                return "X86ISD::SUB";
11994   case X86ISD::ADC:                return "X86ISD::ADC";
11995   case X86ISD::SBB:                return "X86ISD::SBB";
11996   case X86ISD::SMUL:               return "X86ISD::SMUL";
11997   case X86ISD::UMUL:               return "X86ISD::UMUL";
11998   case X86ISD::INC:                return "X86ISD::INC";
11999   case X86ISD::DEC:                return "X86ISD::DEC";
12000   case X86ISD::OR:                 return "X86ISD::OR";
12001   case X86ISD::XOR:                return "X86ISD::XOR";
12002   case X86ISD::AND:                return "X86ISD::AND";
12003   case X86ISD::ANDN:               return "X86ISD::ANDN";
12004   case X86ISD::BLSI:               return "X86ISD::BLSI";
12005   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12006   case X86ISD::BLSR:               return "X86ISD::BLSR";
12007   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12008   case X86ISD::PTEST:              return "X86ISD::PTEST";
12009   case X86ISD::TESTP:              return "X86ISD::TESTP";
12010   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
12011   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12012   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12013   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12014   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12015   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12016   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12017   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12018   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12019   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12020   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12021   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12022   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12023   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12024   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12025   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12026   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12027   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12028   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12029   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12030   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12031   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12032   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12033   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12034   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12035   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12036   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12037   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12038   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12039   case X86ISD::SAHF:               return "X86ISD::SAHF";
12040   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12041   case X86ISD::FMADD:              return "X86ISD::FMADD";
12042   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12043   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12044   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12045   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12046   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12047   }
12048 }
12049
12050 // isLegalAddressingMode - Return true if the addressing mode represented
12051 // by AM is legal for this target, for a load/store of the specified type.
12052 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12053                                               Type *Ty) const {
12054   // X86 supports extremely general addressing modes.
12055   CodeModel::Model M = getTargetMachine().getCodeModel();
12056   Reloc::Model R = getTargetMachine().getRelocationModel();
12057
12058   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12059   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12060     return false;
12061
12062   if (AM.BaseGV) {
12063     unsigned GVFlags =
12064       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12065
12066     // If a reference to this global requires an extra load, we can't fold it.
12067     if (isGlobalStubReference(GVFlags))
12068       return false;
12069
12070     // If BaseGV requires a register for the PIC base, we cannot also have a
12071     // BaseReg specified.
12072     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12073       return false;
12074
12075     // If lower 4G is not available, then we must use rip-relative addressing.
12076     if ((M != CodeModel::Small || R != Reloc::Static) &&
12077         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12078       return false;
12079   }
12080
12081   switch (AM.Scale) {
12082   case 0:
12083   case 1:
12084   case 2:
12085   case 4:
12086   case 8:
12087     // These scales always work.
12088     break;
12089   case 3:
12090   case 5:
12091   case 9:
12092     // These scales are formed with basereg+scalereg.  Only accept if there is
12093     // no basereg yet.
12094     if (AM.HasBaseReg)
12095       return false;
12096     break;
12097   default:  // Other stuff never works.
12098     return false;
12099   }
12100
12101   return true;
12102 }
12103
12104
12105 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12106   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12107     return false;
12108   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12109   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12110   if (NumBits1 <= NumBits2)
12111     return false;
12112   return true;
12113 }
12114
12115 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12116   return Imm == (int32_t)Imm;
12117 }
12118
12119 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12120   // Can also use sub to handle negated immediates.
12121   return Imm == (int32_t)Imm;
12122 }
12123
12124 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12125   if (!VT1.isInteger() || !VT2.isInteger())
12126     return false;
12127   unsigned NumBits1 = VT1.getSizeInBits();
12128   unsigned NumBits2 = VT2.getSizeInBits();
12129   if (NumBits1 <= NumBits2)
12130     return false;
12131   return true;
12132 }
12133
12134 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12135   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12136   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12137 }
12138
12139 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12140   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12141   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12142 }
12143
12144 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12145   // i16 instructions are longer (0x66 prefix) and potentially slower.
12146   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12147 }
12148
12149 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12150 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12151 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12152 /// are assumed to be legal.
12153 bool
12154 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12155                                       EVT VT) const {
12156   // Very little shuffling can be done for 64-bit vectors right now.
12157   if (VT.getSizeInBits() == 64)
12158     return false;
12159
12160   // FIXME: pshufb, blends, shifts.
12161   return (VT.getVectorNumElements() == 2 ||
12162           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12163           isMOVLMask(M, VT) ||
12164           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
12165           isPSHUFDMask(M, VT) ||
12166           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
12167           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
12168           isPALIGNRMask(M, VT, Subtarget) ||
12169           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
12170           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
12171           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
12172           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
12173 }
12174
12175 bool
12176 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12177                                           EVT VT) const {
12178   unsigned NumElts = VT.getVectorNumElements();
12179   // FIXME: This collection of masks seems suspect.
12180   if (NumElts == 2)
12181     return true;
12182   if (NumElts == 4 && VT.is128BitVector()) {
12183     return (isMOVLMask(Mask, VT)  ||
12184             isCommutedMOVLMask(Mask, VT, true) ||
12185             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
12186             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
12187   }
12188   return false;
12189 }
12190
12191 //===----------------------------------------------------------------------===//
12192 //                           X86 Scheduler Hooks
12193 //===----------------------------------------------------------------------===//
12194
12195 // private utility function
12196
12197 // Get CMPXCHG opcode for the specified data type.
12198 static unsigned getCmpXChgOpcode(EVT VT) {
12199   switch (VT.getSimpleVT().SimpleTy) {
12200   case MVT::i8:  return X86::LCMPXCHG8;
12201   case MVT::i16: return X86::LCMPXCHG16;
12202   case MVT::i32: return X86::LCMPXCHG32;
12203   case MVT::i64: return X86::LCMPXCHG64;
12204   default:
12205     break;
12206   }
12207   llvm_unreachable("Invalid operand size!");
12208 }
12209
12210 // Get LOAD opcode for the specified data type.
12211 static unsigned getLoadOpcode(EVT VT) {
12212   switch (VT.getSimpleVT().SimpleTy) {
12213   case MVT::i8:  return X86::MOV8rm;
12214   case MVT::i16: return X86::MOV16rm;
12215   case MVT::i32: return X86::MOV32rm;
12216   case MVT::i64: return X86::MOV64rm;
12217   default:
12218     break;
12219   }
12220   llvm_unreachable("Invalid operand size!");
12221 }
12222
12223 // Get opcode of the non-atomic one from the specified atomic instruction.
12224 static unsigned getNonAtomicOpcode(unsigned Opc) {
12225   switch (Opc) {
12226   case X86::ATOMAND8:  return X86::AND8rr;
12227   case X86::ATOMAND16: return X86::AND16rr;
12228   case X86::ATOMAND32: return X86::AND32rr;
12229   case X86::ATOMAND64: return X86::AND64rr;
12230   case X86::ATOMOR8:   return X86::OR8rr;
12231   case X86::ATOMOR16:  return X86::OR16rr;
12232   case X86::ATOMOR32:  return X86::OR32rr;
12233   case X86::ATOMOR64:  return X86::OR64rr;
12234   case X86::ATOMXOR8:  return X86::XOR8rr;
12235   case X86::ATOMXOR16: return X86::XOR16rr;
12236   case X86::ATOMXOR32: return X86::XOR32rr;
12237   case X86::ATOMXOR64: return X86::XOR64rr;
12238   }
12239   llvm_unreachable("Unhandled atomic-load-op opcode!");
12240 }
12241
12242 // Get opcode of the non-atomic one from the specified atomic instruction with
12243 // extra opcode.
12244 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12245                                                unsigned &ExtraOpc) {
12246   switch (Opc) {
12247   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12248   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12249   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12250   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12251   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12252   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12253   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12254   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12255   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12256   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12257   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12258   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12259   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12260   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12261   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12262   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12263   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12264   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12265   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12266   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12267   }
12268   llvm_unreachable("Unhandled atomic-load-op opcode!");
12269 }
12270
12271 // Get opcode of the non-atomic one from the specified atomic instruction for
12272 // 64-bit data type on 32-bit target.
12273 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12274   switch (Opc) {
12275   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12276   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12277   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12278   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12279   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12280   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12281   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12282   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12283   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12284   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12285   }
12286   llvm_unreachable("Unhandled atomic-load-op opcode!");
12287 }
12288
12289 // Get opcode of the non-atomic one from the specified atomic instruction for
12290 // 64-bit data type on 32-bit target with extra opcode.
12291 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12292                                                    unsigned &HiOpc,
12293                                                    unsigned &ExtraOpc) {
12294   switch (Opc) {
12295   case X86::ATOMNAND6432:
12296     ExtraOpc = X86::NOT32r;
12297     HiOpc = X86::AND32rr;
12298     return X86::AND32rr;
12299   }
12300   llvm_unreachable("Unhandled atomic-load-op opcode!");
12301 }
12302
12303 // Get pseudo CMOV opcode from the specified data type.
12304 static unsigned getPseudoCMOVOpc(EVT VT) {
12305   switch (VT.getSimpleVT().SimpleTy) {
12306   case MVT::i8:  return X86::CMOV_GR8;
12307   case MVT::i16: return X86::CMOV_GR16;
12308   case MVT::i32: return X86::CMOV_GR32;
12309   default:
12310     break;
12311   }
12312   llvm_unreachable("Unknown CMOV opcode!");
12313 }
12314
12315 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12316 // They will be translated into a spin-loop or compare-exchange loop from
12317 //
12318 //    ...
12319 //    dst = atomic-fetch-op MI.addr, MI.val
12320 //    ...
12321 //
12322 // to
12323 //
12324 //    ...
12325 //    EAX = LOAD MI.addr
12326 // loop:
12327 //    t1 = OP MI.val, EAX
12328 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12329 //    JNE loop
12330 // sink:
12331 //    dst = EAX
12332 //    ...
12333 MachineBasicBlock *
12334 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12335                                        MachineBasicBlock *MBB) const {
12336   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12337   DebugLoc DL = MI->getDebugLoc();
12338
12339   MachineFunction *MF = MBB->getParent();
12340   MachineRegisterInfo &MRI = MF->getRegInfo();
12341
12342   const BasicBlock *BB = MBB->getBasicBlock();
12343   MachineFunction::iterator I = MBB;
12344   ++I;
12345
12346   assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12347          "Unexpected number of operands");
12348
12349   assert(MI->hasOneMemOperand() &&
12350          "Expected atomic-load-op to have one memoperand");
12351
12352   // Memory Reference
12353   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12354   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12355
12356   unsigned DstReg, SrcReg;
12357   unsigned MemOpndSlot;
12358
12359   unsigned CurOp = 0;
12360
12361   DstReg = MI->getOperand(CurOp++).getReg();
12362   MemOpndSlot = CurOp;
12363   CurOp += X86::AddrNumOperands;
12364   SrcReg = MI->getOperand(CurOp++).getReg();
12365
12366   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12367   MVT::SimpleValueType VT = *RC->vt_begin();
12368   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12369
12370   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12371   unsigned LOADOpc = getLoadOpcode(VT);
12372
12373   // For the atomic load-arith operator, we generate
12374   //
12375   //  thisMBB:
12376   //    EAX = LOAD [MI.addr]
12377   //  mainMBB:
12378   //    t1 = OP MI.val, EAX
12379   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12380   //    JNE mainMBB
12381   //  sinkMBB:
12382
12383   MachineBasicBlock *thisMBB = MBB;
12384   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12385   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12386   MF->insert(I, mainMBB);
12387   MF->insert(I, sinkMBB);
12388
12389   MachineInstrBuilder MIB;
12390
12391   // Transfer the remainder of BB and its successor edges to sinkMBB.
12392   sinkMBB->splice(sinkMBB->begin(), MBB,
12393                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12394   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12395
12396   // thisMBB:
12397   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12398   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12399     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12400   MIB.setMemRefs(MMOBegin, MMOEnd);
12401
12402   thisMBB->addSuccessor(mainMBB);
12403
12404   // mainMBB:
12405   MachineBasicBlock *origMainMBB = mainMBB;
12406   mainMBB->addLiveIn(AccPhyReg);
12407
12408   // Copy AccPhyReg as it is used more than once.
12409   unsigned AccReg = MRI.createVirtualRegister(RC);
12410   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12411     .addReg(AccPhyReg);
12412
12413   unsigned t1 = MRI.createVirtualRegister(RC);
12414   unsigned Opc = MI->getOpcode();
12415   switch (Opc) {
12416   default:
12417     llvm_unreachable("Unhandled atomic-load-op opcode!");
12418   case X86::ATOMAND8:
12419   case X86::ATOMAND16:
12420   case X86::ATOMAND32:
12421   case X86::ATOMAND64:
12422   case X86::ATOMOR8:
12423   case X86::ATOMOR16:
12424   case X86::ATOMOR32:
12425   case X86::ATOMOR64:
12426   case X86::ATOMXOR8:
12427   case X86::ATOMXOR16:
12428   case X86::ATOMXOR32:
12429   case X86::ATOMXOR64: {
12430     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12431     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12432       .addReg(AccReg);
12433     break;
12434   }
12435   case X86::ATOMNAND8:
12436   case X86::ATOMNAND16:
12437   case X86::ATOMNAND32:
12438   case X86::ATOMNAND64: {
12439     unsigned t2 = MRI.createVirtualRegister(RC);
12440     unsigned NOTOpc;
12441     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12442     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12443       .addReg(AccReg);
12444     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12445     break;
12446   }
12447   case X86::ATOMMAX8:
12448   case X86::ATOMMAX16:
12449   case X86::ATOMMAX32:
12450   case X86::ATOMMAX64:
12451   case X86::ATOMMIN8:
12452   case X86::ATOMMIN16:
12453   case X86::ATOMMIN32:
12454   case X86::ATOMMIN64:
12455   case X86::ATOMUMAX8:
12456   case X86::ATOMUMAX16:
12457   case X86::ATOMUMAX32:
12458   case X86::ATOMUMAX64:
12459   case X86::ATOMUMIN8:
12460   case X86::ATOMUMIN16:
12461   case X86::ATOMUMIN32:
12462   case X86::ATOMUMIN64: {
12463     unsigned CMPOpc;
12464     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12465
12466     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12467       .addReg(SrcReg)
12468       .addReg(AccReg);
12469
12470     if (Subtarget->hasCMov()) {
12471       if (VT != MVT::i8) {
12472         // Native support
12473         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12474           .addReg(SrcReg)
12475           .addReg(AccReg);
12476       } else {
12477         // Promote i8 to i32 to use CMOV32
12478         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12479         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12480         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12481         unsigned t2 = MRI.createVirtualRegister(RC32);
12482
12483         unsigned Undef = MRI.createVirtualRegister(RC32);
12484         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12485
12486         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12487           .addReg(Undef)
12488           .addReg(SrcReg)
12489           .addImm(X86::sub_8bit);
12490         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12491           .addReg(Undef)
12492           .addReg(AccReg)
12493           .addImm(X86::sub_8bit);
12494
12495         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12496           .addReg(SrcReg32)
12497           .addReg(AccReg32);
12498
12499         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12500           .addReg(t2, 0, X86::sub_8bit);
12501       }
12502     } else {
12503       // Use pseudo select and lower them.
12504       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12505              "Invalid atomic-load-op transformation!");
12506       unsigned SelOpc = getPseudoCMOVOpc(VT);
12507       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12508       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12509       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12510               .addReg(SrcReg).addReg(AccReg)
12511               .addImm(CC);
12512       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12513     }
12514     break;
12515   }
12516   }
12517
12518   // Copy AccPhyReg back from virtual register.
12519   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12520     .addReg(AccReg);
12521
12522   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12523   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12524     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12525   MIB.addReg(t1);
12526   MIB.setMemRefs(MMOBegin, MMOEnd);
12527
12528   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12529
12530   mainMBB->addSuccessor(origMainMBB);
12531   mainMBB->addSuccessor(sinkMBB);
12532
12533   // sinkMBB:
12534   sinkMBB->addLiveIn(AccPhyReg);
12535
12536   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12537           TII->get(TargetOpcode::COPY), DstReg)
12538     .addReg(AccPhyReg);
12539
12540   MI->eraseFromParent();
12541   return sinkMBB;
12542 }
12543
12544 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12545 // instructions. They will be translated into a spin-loop or compare-exchange
12546 // loop from
12547 //
12548 //    ...
12549 //    dst = atomic-fetch-op MI.addr, MI.val
12550 //    ...
12551 //
12552 // to
12553 //
12554 //    ...
12555 //    EAX = LOAD [MI.addr + 0]
12556 //    EDX = LOAD [MI.addr + 4]
12557 // loop:
12558 //    EBX = OP MI.val.lo, EAX
12559 //    ECX = OP MI.val.hi, EDX
12560 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12561 //    JNE loop
12562 // sink:
12563 //    dst = EDX:EAX
12564 //    ...
12565 MachineBasicBlock *
12566 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12567                                            MachineBasicBlock *MBB) const {
12568   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12569   DebugLoc DL = MI->getDebugLoc();
12570
12571   MachineFunction *MF = MBB->getParent();
12572   MachineRegisterInfo &MRI = MF->getRegInfo();
12573
12574   const BasicBlock *BB = MBB->getBasicBlock();
12575   MachineFunction::iterator I = MBB;
12576   ++I;
12577
12578   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12579          "Unexpected number of operands");
12580
12581   assert(MI->hasOneMemOperand() &&
12582          "Expected atomic-load-op32 to have one memoperand");
12583
12584   // Memory Reference
12585   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12586   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12587
12588   unsigned DstLoReg, DstHiReg;
12589   unsigned SrcLoReg, SrcHiReg;
12590   unsigned MemOpndSlot;
12591
12592   unsigned CurOp = 0;
12593
12594   DstLoReg = MI->getOperand(CurOp++).getReg();
12595   DstHiReg = MI->getOperand(CurOp++).getReg();
12596   MemOpndSlot = CurOp;
12597   CurOp += X86::AddrNumOperands;
12598   SrcLoReg = MI->getOperand(CurOp++).getReg();
12599   SrcHiReg = MI->getOperand(CurOp++).getReg();
12600
12601   const TargetRegisterClass *RC = &X86::GR32RegClass;
12602   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12603
12604   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12605   unsigned LOADOpc = X86::MOV32rm;
12606
12607   // For the atomic load-arith operator, we generate
12608   //
12609   //  thisMBB:
12610   //    EAX = LOAD [MI.addr + 0]
12611   //    EDX = LOAD [MI.addr + 4]
12612   //  mainMBB:
12613   //    EBX = OP MI.vallo, EAX
12614   //    ECX = OP MI.valhi, EDX
12615   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12616   //    JNE mainMBB
12617   //  sinkMBB:
12618
12619   MachineBasicBlock *thisMBB = MBB;
12620   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12621   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12622   MF->insert(I, mainMBB);
12623   MF->insert(I, sinkMBB);
12624
12625   MachineInstrBuilder MIB;
12626
12627   // Transfer the remainder of BB and its successor edges to sinkMBB.
12628   sinkMBB->splice(sinkMBB->begin(), MBB,
12629                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12630   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12631
12632   // thisMBB:
12633   // Lo
12634   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12635   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12636     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12637   MIB.setMemRefs(MMOBegin, MMOEnd);
12638   // Hi
12639   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12640   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12641     if (i == X86::AddrDisp)
12642       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12643     else
12644       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12645   }
12646   MIB.setMemRefs(MMOBegin, MMOEnd);
12647
12648   thisMBB->addSuccessor(mainMBB);
12649
12650   // mainMBB:
12651   MachineBasicBlock *origMainMBB = mainMBB;
12652   mainMBB->addLiveIn(X86::EAX);
12653   mainMBB->addLiveIn(X86::EDX);
12654
12655   // Copy EDX:EAX as they are used more than once.
12656   unsigned LoReg = MRI.createVirtualRegister(RC);
12657   unsigned HiReg = MRI.createVirtualRegister(RC);
12658   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12659   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12660
12661   unsigned t1L = MRI.createVirtualRegister(RC);
12662   unsigned t1H = MRI.createVirtualRegister(RC);
12663
12664   unsigned Opc = MI->getOpcode();
12665   switch (Opc) {
12666   default:
12667     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12668   case X86::ATOMAND6432:
12669   case X86::ATOMOR6432:
12670   case X86::ATOMXOR6432:
12671   case X86::ATOMADD6432:
12672   case X86::ATOMSUB6432: {
12673     unsigned HiOpc;
12674     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12675     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12676     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12677     break;
12678   }
12679   case X86::ATOMNAND6432: {
12680     unsigned HiOpc, NOTOpc;
12681     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12682     unsigned t2L = MRI.createVirtualRegister(RC);
12683     unsigned t2H = MRI.createVirtualRegister(RC);
12684     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12685     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12686     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12687     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12688     break;
12689   }
12690   case X86::ATOMMAX6432:
12691   case X86::ATOMMIN6432:
12692   case X86::ATOMUMAX6432:
12693   case X86::ATOMUMIN6432: {
12694     unsigned HiOpc;
12695     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12696     unsigned cL = MRI.createVirtualRegister(RC8);
12697     unsigned cH = MRI.createVirtualRegister(RC8);
12698     unsigned cL32 = MRI.createVirtualRegister(RC);
12699     unsigned cH32 = MRI.createVirtualRegister(RC);
12700     unsigned cc = MRI.createVirtualRegister(RC);
12701     // cl := cmp src_lo, lo
12702     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12703       .addReg(SrcLoReg).addReg(LoReg);
12704     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12705     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12706     // ch := cmp src_hi, hi
12707     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12708       .addReg(SrcHiReg).addReg(HiReg);
12709     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12710     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12711     // cc := if (src_hi == hi) ? cl : ch;
12712     if (Subtarget->hasCMov()) {
12713       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12714         .addReg(cH32).addReg(cL32);
12715     } else {
12716       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12717               .addReg(cH32).addReg(cL32)
12718               .addImm(X86::COND_E);
12719       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12720     }
12721     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12722     if (Subtarget->hasCMov()) {
12723       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12724         .addReg(SrcLoReg).addReg(LoReg);
12725       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12726         .addReg(SrcHiReg).addReg(HiReg);
12727     } else {
12728       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12729               .addReg(SrcLoReg).addReg(LoReg)
12730               .addImm(X86::COND_NE);
12731       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12732       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12733               .addReg(SrcHiReg).addReg(HiReg)
12734               .addImm(X86::COND_NE);
12735       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12736     }
12737     break;
12738   }
12739   case X86::ATOMSWAP6432: {
12740     unsigned HiOpc;
12741     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12742     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12743     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12744     break;
12745   }
12746   }
12747
12748   // Copy EDX:EAX back from HiReg:LoReg
12749   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12750   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12751   // Copy ECX:EBX from t1H:t1L
12752   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12753   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12754
12755   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12756   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12757     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12758   MIB.setMemRefs(MMOBegin, MMOEnd);
12759
12760   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12761
12762   mainMBB->addSuccessor(origMainMBB);
12763   mainMBB->addSuccessor(sinkMBB);
12764
12765   // sinkMBB:
12766   sinkMBB->addLiveIn(X86::EAX);
12767   sinkMBB->addLiveIn(X86::EDX);
12768
12769   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12770           TII->get(TargetOpcode::COPY), DstLoReg)
12771     .addReg(X86::EAX);
12772   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12773           TII->get(TargetOpcode::COPY), DstHiReg)
12774     .addReg(X86::EDX);
12775
12776   MI->eraseFromParent();
12777   return sinkMBB;
12778 }
12779
12780 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12781 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12782 // in the .td file.
12783 MachineBasicBlock *
12784 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12785                             unsigned numArgs, bool memArg) const {
12786   assert(Subtarget->hasSSE42() &&
12787          "Target must have SSE4.2 or AVX features enabled");
12788
12789   DebugLoc dl = MI->getDebugLoc();
12790   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12791   unsigned Opc;
12792   if (!Subtarget->hasAVX()) {
12793     if (memArg)
12794       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12795     else
12796       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12797   } else {
12798     if (memArg)
12799       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12800     else
12801       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12802   }
12803
12804   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12805   for (unsigned i = 0; i < numArgs; ++i) {
12806     MachineOperand &Op = MI->getOperand(i+1);
12807     if (!(Op.isReg() && Op.isImplicit()))
12808       MIB.addOperand(Op);
12809   }
12810   BuildMI(*BB, MI, dl,
12811     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12812     .addReg(X86::XMM0);
12813
12814   MI->eraseFromParent();
12815   return BB;
12816 }
12817
12818 MachineBasicBlock *
12819 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12820   DebugLoc dl = MI->getDebugLoc();
12821   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12822
12823   // Address into RAX/EAX, other two args into ECX, EDX.
12824   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12825   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12826   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12827   for (int i = 0; i < X86::AddrNumOperands; ++i)
12828     MIB.addOperand(MI->getOperand(i));
12829
12830   unsigned ValOps = X86::AddrNumOperands;
12831   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12832     .addReg(MI->getOperand(ValOps).getReg());
12833   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12834     .addReg(MI->getOperand(ValOps+1).getReg());
12835
12836   // The instruction doesn't actually take any operands though.
12837   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12838
12839   MI->eraseFromParent(); // The pseudo is gone now.
12840   return BB;
12841 }
12842
12843 MachineBasicBlock *
12844 X86TargetLowering::EmitVAARG64WithCustomInserter(
12845                    MachineInstr *MI,
12846                    MachineBasicBlock *MBB) const {
12847   // Emit va_arg instruction on X86-64.
12848
12849   // Operands to this pseudo-instruction:
12850   // 0  ) Output        : destination address (reg)
12851   // 1-5) Input         : va_list address (addr, i64mem)
12852   // 6  ) ArgSize       : Size (in bytes) of vararg type
12853   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12854   // 8  ) Align         : Alignment of type
12855   // 9  ) EFLAGS (implicit-def)
12856
12857   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12858   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12859
12860   unsigned DestReg = MI->getOperand(0).getReg();
12861   MachineOperand &Base = MI->getOperand(1);
12862   MachineOperand &Scale = MI->getOperand(2);
12863   MachineOperand &Index = MI->getOperand(3);
12864   MachineOperand &Disp = MI->getOperand(4);
12865   MachineOperand &Segment = MI->getOperand(5);
12866   unsigned ArgSize = MI->getOperand(6).getImm();
12867   unsigned ArgMode = MI->getOperand(7).getImm();
12868   unsigned Align = MI->getOperand(8).getImm();
12869
12870   // Memory Reference
12871   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12872   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12873   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12874
12875   // Machine Information
12876   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12877   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12878   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12879   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12880   DebugLoc DL = MI->getDebugLoc();
12881
12882   // struct va_list {
12883   //   i32   gp_offset
12884   //   i32   fp_offset
12885   //   i64   overflow_area (address)
12886   //   i64   reg_save_area (address)
12887   // }
12888   // sizeof(va_list) = 24
12889   // alignment(va_list) = 8
12890
12891   unsigned TotalNumIntRegs = 6;
12892   unsigned TotalNumXMMRegs = 8;
12893   bool UseGPOffset = (ArgMode == 1);
12894   bool UseFPOffset = (ArgMode == 2);
12895   unsigned MaxOffset = TotalNumIntRegs * 8 +
12896                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12897
12898   /* Align ArgSize to a multiple of 8 */
12899   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12900   bool NeedsAlign = (Align > 8);
12901
12902   MachineBasicBlock *thisMBB = MBB;
12903   MachineBasicBlock *overflowMBB;
12904   MachineBasicBlock *offsetMBB;
12905   MachineBasicBlock *endMBB;
12906
12907   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12908   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12909   unsigned OffsetReg = 0;
12910
12911   if (!UseGPOffset && !UseFPOffset) {
12912     // If we only pull from the overflow region, we don't create a branch.
12913     // We don't need to alter control flow.
12914     OffsetDestReg = 0; // unused
12915     OverflowDestReg = DestReg;
12916
12917     offsetMBB = NULL;
12918     overflowMBB = thisMBB;
12919     endMBB = thisMBB;
12920   } else {
12921     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12922     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12923     // If not, pull from overflow_area. (branch to overflowMBB)
12924     //
12925     //       thisMBB
12926     //         |     .
12927     //         |        .
12928     //     offsetMBB   overflowMBB
12929     //         |        .
12930     //         |     .
12931     //        endMBB
12932
12933     // Registers for the PHI in endMBB
12934     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12935     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12936
12937     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12938     MachineFunction *MF = MBB->getParent();
12939     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12940     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12941     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12942
12943     MachineFunction::iterator MBBIter = MBB;
12944     ++MBBIter;
12945
12946     // Insert the new basic blocks
12947     MF->insert(MBBIter, offsetMBB);
12948     MF->insert(MBBIter, overflowMBB);
12949     MF->insert(MBBIter, endMBB);
12950
12951     // Transfer the remainder of MBB and its successor edges to endMBB.
12952     endMBB->splice(endMBB->begin(), thisMBB,
12953                     llvm::next(MachineBasicBlock::iterator(MI)),
12954                     thisMBB->end());
12955     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12956
12957     // Make offsetMBB and overflowMBB successors of thisMBB
12958     thisMBB->addSuccessor(offsetMBB);
12959     thisMBB->addSuccessor(overflowMBB);
12960
12961     // endMBB is a successor of both offsetMBB and overflowMBB
12962     offsetMBB->addSuccessor(endMBB);
12963     overflowMBB->addSuccessor(endMBB);
12964
12965     // Load the offset value into a register
12966     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12967     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12968       .addOperand(Base)
12969       .addOperand(Scale)
12970       .addOperand(Index)
12971       .addDisp(Disp, UseFPOffset ? 4 : 0)
12972       .addOperand(Segment)
12973       .setMemRefs(MMOBegin, MMOEnd);
12974
12975     // Check if there is enough room left to pull this argument.
12976     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12977       .addReg(OffsetReg)
12978       .addImm(MaxOffset + 8 - ArgSizeA8);
12979
12980     // Branch to "overflowMBB" if offset >= max
12981     // Fall through to "offsetMBB" otherwise
12982     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12983       .addMBB(overflowMBB);
12984   }
12985
12986   // In offsetMBB, emit code to use the reg_save_area.
12987   if (offsetMBB) {
12988     assert(OffsetReg != 0);
12989
12990     // Read the reg_save_area address.
12991     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12992     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12993       .addOperand(Base)
12994       .addOperand(Scale)
12995       .addOperand(Index)
12996       .addDisp(Disp, 16)
12997       .addOperand(Segment)
12998       .setMemRefs(MMOBegin, MMOEnd);
12999
13000     // Zero-extend the offset
13001     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13002       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13003         .addImm(0)
13004         .addReg(OffsetReg)
13005         .addImm(X86::sub_32bit);
13006
13007     // Add the offset to the reg_save_area to get the final address.
13008     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13009       .addReg(OffsetReg64)
13010       .addReg(RegSaveReg);
13011
13012     // Compute the offset for the next argument
13013     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13014     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13015       .addReg(OffsetReg)
13016       .addImm(UseFPOffset ? 16 : 8);
13017
13018     // Store it back into the va_list.
13019     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13020       .addOperand(Base)
13021       .addOperand(Scale)
13022       .addOperand(Index)
13023       .addDisp(Disp, UseFPOffset ? 4 : 0)
13024       .addOperand(Segment)
13025       .addReg(NextOffsetReg)
13026       .setMemRefs(MMOBegin, MMOEnd);
13027
13028     // Jump to endMBB
13029     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13030       .addMBB(endMBB);
13031   }
13032
13033   //
13034   // Emit code to use overflow area
13035   //
13036
13037   // Load the overflow_area address into a register.
13038   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13039   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13040     .addOperand(Base)
13041     .addOperand(Scale)
13042     .addOperand(Index)
13043     .addDisp(Disp, 8)
13044     .addOperand(Segment)
13045     .setMemRefs(MMOBegin, MMOEnd);
13046
13047   // If we need to align it, do so. Otherwise, just copy the address
13048   // to OverflowDestReg.
13049   if (NeedsAlign) {
13050     // Align the overflow address
13051     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13052     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13053
13054     // aligned_addr = (addr + (align-1)) & ~(align-1)
13055     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13056       .addReg(OverflowAddrReg)
13057       .addImm(Align-1);
13058
13059     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13060       .addReg(TmpReg)
13061       .addImm(~(uint64_t)(Align-1));
13062   } else {
13063     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13064       .addReg(OverflowAddrReg);
13065   }
13066
13067   // Compute the next overflow address after this argument.
13068   // (the overflow address should be kept 8-byte aligned)
13069   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13070   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13071     .addReg(OverflowDestReg)
13072     .addImm(ArgSizeA8);
13073
13074   // Store the new overflow address.
13075   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13076     .addOperand(Base)
13077     .addOperand(Scale)
13078     .addOperand(Index)
13079     .addDisp(Disp, 8)
13080     .addOperand(Segment)
13081     .addReg(NextAddrReg)
13082     .setMemRefs(MMOBegin, MMOEnd);
13083
13084   // If we branched, emit the PHI to the front of endMBB.
13085   if (offsetMBB) {
13086     BuildMI(*endMBB, endMBB->begin(), DL,
13087             TII->get(X86::PHI), DestReg)
13088       .addReg(OffsetDestReg).addMBB(offsetMBB)
13089       .addReg(OverflowDestReg).addMBB(overflowMBB);
13090   }
13091
13092   // Erase the pseudo instruction
13093   MI->eraseFromParent();
13094
13095   return endMBB;
13096 }
13097
13098 MachineBasicBlock *
13099 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13100                                                  MachineInstr *MI,
13101                                                  MachineBasicBlock *MBB) const {
13102   // Emit code to save XMM registers to the stack. The ABI says that the
13103   // number of registers to save is given in %al, so it's theoretically
13104   // possible to do an indirect jump trick to avoid saving all of them,
13105   // however this code takes a simpler approach and just executes all
13106   // of the stores if %al is non-zero. It's less code, and it's probably
13107   // easier on the hardware branch predictor, and stores aren't all that
13108   // expensive anyway.
13109
13110   // Create the new basic blocks. One block contains all the XMM stores,
13111   // and one block is the final destination regardless of whether any
13112   // stores were performed.
13113   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13114   MachineFunction *F = MBB->getParent();
13115   MachineFunction::iterator MBBIter = MBB;
13116   ++MBBIter;
13117   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13118   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13119   F->insert(MBBIter, XMMSaveMBB);
13120   F->insert(MBBIter, EndMBB);
13121
13122   // Transfer the remainder of MBB and its successor edges to EndMBB.
13123   EndMBB->splice(EndMBB->begin(), MBB,
13124                  llvm::next(MachineBasicBlock::iterator(MI)),
13125                  MBB->end());
13126   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13127
13128   // The original block will now fall through to the XMM save block.
13129   MBB->addSuccessor(XMMSaveMBB);
13130   // The XMMSaveMBB will fall through to the end block.
13131   XMMSaveMBB->addSuccessor(EndMBB);
13132
13133   // Now add the instructions.
13134   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13135   DebugLoc DL = MI->getDebugLoc();
13136
13137   unsigned CountReg = MI->getOperand(0).getReg();
13138   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13139   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13140
13141   if (!Subtarget->isTargetWin64()) {
13142     // If %al is 0, branch around the XMM save block.
13143     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13144     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13145     MBB->addSuccessor(EndMBB);
13146   }
13147
13148   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13149   // In the XMM save block, save all the XMM argument registers.
13150   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13151     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13152     MachineMemOperand *MMO =
13153       F->getMachineMemOperand(
13154           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13155         MachineMemOperand::MOStore,
13156         /*Size=*/16, /*Align=*/16);
13157     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13158       .addFrameIndex(RegSaveFrameIndex)
13159       .addImm(/*Scale=*/1)
13160       .addReg(/*IndexReg=*/0)
13161       .addImm(/*Disp=*/Offset)
13162       .addReg(/*Segment=*/0)
13163       .addReg(MI->getOperand(i).getReg())
13164       .addMemOperand(MMO);
13165   }
13166
13167   MI->eraseFromParent();   // The pseudo instruction is gone now.
13168
13169   return EndMBB;
13170 }
13171
13172 // The EFLAGS operand of SelectItr might be missing a kill marker
13173 // because there were multiple uses of EFLAGS, and ISel didn't know
13174 // which to mark. Figure out whether SelectItr should have had a
13175 // kill marker, and set it if it should. Returns the correct kill
13176 // marker value.
13177 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13178                                      MachineBasicBlock* BB,
13179                                      const TargetRegisterInfo* TRI) {
13180   // Scan forward through BB for a use/def of EFLAGS.
13181   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13182   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13183     const MachineInstr& mi = *miI;
13184     if (mi.readsRegister(X86::EFLAGS))
13185       return false;
13186     if (mi.definesRegister(X86::EFLAGS))
13187       break; // Should have kill-flag - update below.
13188   }
13189
13190   // If we hit the end of the block, check whether EFLAGS is live into a
13191   // successor.
13192   if (miI == BB->end()) {
13193     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13194                                           sEnd = BB->succ_end();
13195          sItr != sEnd; ++sItr) {
13196       MachineBasicBlock* succ = *sItr;
13197       if (succ->isLiveIn(X86::EFLAGS))
13198         return false;
13199     }
13200   }
13201
13202   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13203   // out. SelectMI should have a kill flag on EFLAGS.
13204   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13205   return true;
13206 }
13207
13208 MachineBasicBlock *
13209 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13210                                      MachineBasicBlock *BB) const {
13211   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13212   DebugLoc DL = MI->getDebugLoc();
13213
13214   // To "insert" a SELECT_CC instruction, we actually have to insert the
13215   // diamond control-flow pattern.  The incoming instruction knows the
13216   // destination vreg to set, the condition code register to branch on, the
13217   // true/false values to select between, and a branch opcode to use.
13218   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13219   MachineFunction::iterator It = BB;
13220   ++It;
13221
13222   //  thisMBB:
13223   //  ...
13224   //   TrueVal = ...
13225   //   cmpTY ccX, r1, r2
13226   //   bCC copy1MBB
13227   //   fallthrough --> copy0MBB
13228   MachineBasicBlock *thisMBB = BB;
13229   MachineFunction *F = BB->getParent();
13230   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13231   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13232   F->insert(It, copy0MBB);
13233   F->insert(It, sinkMBB);
13234
13235   // If the EFLAGS register isn't dead in the terminator, then claim that it's
13236   // live into the sink and copy blocks.
13237   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13238   if (!MI->killsRegister(X86::EFLAGS) &&
13239       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13240     copy0MBB->addLiveIn(X86::EFLAGS);
13241     sinkMBB->addLiveIn(X86::EFLAGS);
13242   }
13243
13244   // Transfer the remainder of BB and its successor edges to sinkMBB.
13245   sinkMBB->splice(sinkMBB->begin(), BB,
13246                   llvm::next(MachineBasicBlock::iterator(MI)),
13247                   BB->end());
13248   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13249
13250   // Add the true and fallthrough blocks as its successors.
13251   BB->addSuccessor(copy0MBB);
13252   BB->addSuccessor(sinkMBB);
13253
13254   // Create the conditional branch instruction.
13255   unsigned Opc =
13256     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13257   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13258
13259   //  copy0MBB:
13260   //   %FalseValue = ...
13261   //   # fallthrough to sinkMBB
13262   copy0MBB->addSuccessor(sinkMBB);
13263
13264   //  sinkMBB:
13265   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13266   //  ...
13267   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13268           TII->get(X86::PHI), MI->getOperand(0).getReg())
13269     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13270     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13271
13272   MI->eraseFromParent();   // The pseudo instruction is gone now.
13273   return sinkMBB;
13274 }
13275
13276 MachineBasicBlock *
13277 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13278                                         bool Is64Bit) const {
13279   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13280   DebugLoc DL = MI->getDebugLoc();
13281   MachineFunction *MF = BB->getParent();
13282   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13283
13284   assert(getTargetMachine().Options.EnableSegmentedStacks);
13285
13286   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13287   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13288
13289   // BB:
13290   //  ... [Till the alloca]
13291   // If stacklet is not large enough, jump to mallocMBB
13292   //
13293   // bumpMBB:
13294   //  Allocate by subtracting from RSP
13295   //  Jump to continueMBB
13296   //
13297   // mallocMBB:
13298   //  Allocate by call to runtime
13299   //
13300   // continueMBB:
13301   //  ...
13302   //  [rest of original BB]
13303   //
13304
13305   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13306   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13307   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13308
13309   MachineRegisterInfo &MRI = MF->getRegInfo();
13310   const TargetRegisterClass *AddrRegClass =
13311     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13312
13313   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13314     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13315     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13316     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13317     sizeVReg = MI->getOperand(1).getReg(),
13318     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13319
13320   MachineFunction::iterator MBBIter = BB;
13321   ++MBBIter;
13322
13323   MF->insert(MBBIter, bumpMBB);
13324   MF->insert(MBBIter, mallocMBB);
13325   MF->insert(MBBIter, continueMBB);
13326
13327   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13328                       (MachineBasicBlock::iterator(MI)), BB->end());
13329   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13330
13331   // Add code to the main basic block to check if the stack limit has been hit,
13332   // and if so, jump to mallocMBB otherwise to bumpMBB.
13333   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13334   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13335     .addReg(tmpSPVReg).addReg(sizeVReg);
13336   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13337     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13338     .addReg(SPLimitVReg);
13339   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13340
13341   // bumpMBB simply decreases the stack pointer, since we know the current
13342   // stacklet has enough space.
13343   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13344     .addReg(SPLimitVReg);
13345   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13346     .addReg(SPLimitVReg);
13347   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13348
13349   // Calls into a routine in libgcc to allocate more space from the heap.
13350   const uint32_t *RegMask =
13351     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13352   if (Is64Bit) {
13353     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13354       .addReg(sizeVReg);
13355     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13356       .addExternalSymbol("__morestack_allocate_stack_space")
13357       .addRegMask(RegMask)
13358       .addReg(X86::RDI, RegState::Implicit)
13359       .addReg(X86::RAX, RegState::ImplicitDefine);
13360   } else {
13361     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13362       .addImm(12);
13363     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13364     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13365       .addExternalSymbol("__morestack_allocate_stack_space")
13366       .addRegMask(RegMask)
13367       .addReg(X86::EAX, RegState::ImplicitDefine);
13368   }
13369
13370   if (!Is64Bit)
13371     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13372       .addImm(16);
13373
13374   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13375     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13376   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13377
13378   // Set up the CFG correctly.
13379   BB->addSuccessor(bumpMBB);
13380   BB->addSuccessor(mallocMBB);
13381   mallocMBB->addSuccessor(continueMBB);
13382   bumpMBB->addSuccessor(continueMBB);
13383
13384   // Take care of the PHI nodes.
13385   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13386           MI->getOperand(0).getReg())
13387     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13388     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13389
13390   // Delete the original pseudo instruction.
13391   MI->eraseFromParent();
13392
13393   // And we're done.
13394   return continueMBB;
13395 }
13396
13397 MachineBasicBlock *
13398 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13399                                           MachineBasicBlock *BB) const {
13400   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13401   DebugLoc DL = MI->getDebugLoc();
13402
13403   assert(!Subtarget->isTargetEnvMacho());
13404
13405   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13406   // non-trivial part is impdef of ESP.
13407
13408   if (Subtarget->isTargetWin64()) {
13409     if (Subtarget->isTargetCygMing()) {
13410       // ___chkstk(Mingw64):
13411       // Clobbers R10, R11, RAX and EFLAGS.
13412       // Updates RSP.
13413       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13414         .addExternalSymbol("___chkstk")
13415         .addReg(X86::RAX, RegState::Implicit)
13416         .addReg(X86::RSP, RegState::Implicit)
13417         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13418         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13419         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13420     } else {
13421       // __chkstk(MSVCRT): does not update stack pointer.
13422       // Clobbers R10, R11 and EFLAGS.
13423       // FIXME: RAX(allocated size) might be reused and not killed.
13424       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13425         .addExternalSymbol("__chkstk")
13426         .addReg(X86::RAX, RegState::Implicit)
13427         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13428       // RAX has the offset to subtracted from RSP.
13429       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13430         .addReg(X86::RSP)
13431         .addReg(X86::RAX);
13432     }
13433   } else {
13434     const char *StackProbeSymbol =
13435       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13436
13437     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13438       .addExternalSymbol(StackProbeSymbol)
13439       .addReg(X86::EAX, RegState::Implicit)
13440       .addReg(X86::ESP, RegState::Implicit)
13441       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13442       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13443       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13444   }
13445
13446   MI->eraseFromParent();   // The pseudo instruction is gone now.
13447   return BB;
13448 }
13449
13450 MachineBasicBlock *
13451 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13452                                       MachineBasicBlock *BB) const {
13453   // This is pretty easy.  We're taking the value that we received from
13454   // our load from the relocation, sticking it in either RDI (x86-64)
13455   // or EAX and doing an indirect call.  The return value will then
13456   // be in the normal return register.
13457   const X86InstrInfo *TII
13458     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13459   DebugLoc DL = MI->getDebugLoc();
13460   MachineFunction *F = BB->getParent();
13461
13462   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13463   assert(MI->getOperand(3).isGlobal() && "This should be a global");
13464
13465   // Get a register mask for the lowered call.
13466   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13467   // proper register mask.
13468   const uint32_t *RegMask =
13469     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13470   if (Subtarget->is64Bit()) {
13471     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13472                                       TII->get(X86::MOV64rm), X86::RDI)
13473     .addReg(X86::RIP)
13474     .addImm(0).addReg(0)
13475     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13476                       MI->getOperand(3).getTargetFlags())
13477     .addReg(0);
13478     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13479     addDirectMem(MIB, X86::RDI);
13480     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13481   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13482     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13483                                       TII->get(X86::MOV32rm), X86::EAX)
13484     .addReg(0)
13485     .addImm(0).addReg(0)
13486     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13487                       MI->getOperand(3).getTargetFlags())
13488     .addReg(0);
13489     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13490     addDirectMem(MIB, X86::EAX);
13491     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13492   } else {
13493     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13494                                       TII->get(X86::MOV32rm), X86::EAX)
13495     .addReg(TII->getGlobalBaseReg(F))
13496     .addImm(0).addReg(0)
13497     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13498                       MI->getOperand(3).getTargetFlags())
13499     .addReg(0);
13500     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13501     addDirectMem(MIB, X86::EAX);
13502     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13503   }
13504
13505   MI->eraseFromParent(); // The pseudo instruction is gone now.
13506   return BB;
13507 }
13508
13509 MachineBasicBlock *
13510 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13511                                     MachineBasicBlock *MBB) const {
13512   DebugLoc DL = MI->getDebugLoc();
13513   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13514
13515   MachineFunction *MF = MBB->getParent();
13516   MachineRegisterInfo &MRI = MF->getRegInfo();
13517
13518   const BasicBlock *BB = MBB->getBasicBlock();
13519   MachineFunction::iterator I = MBB;
13520   ++I;
13521
13522   // Memory Reference
13523   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13524   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13525
13526   unsigned DstReg;
13527   unsigned MemOpndSlot = 0;
13528
13529   unsigned CurOp = 0;
13530
13531   DstReg = MI->getOperand(CurOp++).getReg();
13532   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13533   assert(RC->hasType(MVT::i32) && "Invalid destination!");
13534   unsigned mainDstReg = MRI.createVirtualRegister(RC);
13535   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13536
13537   MemOpndSlot = CurOp;
13538
13539   MVT PVT = getPointerTy();
13540   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13541          "Invalid Pointer Size!");
13542
13543   // For v = setjmp(buf), we generate
13544   //
13545   // thisMBB:
13546   //  buf[LabelOffset] = restoreMBB
13547   //  SjLjSetup restoreMBB
13548   //
13549   // mainMBB:
13550   //  v_main = 0
13551   //
13552   // sinkMBB:
13553   //  v = phi(main, restore)
13554   //
13555   // restoreMBB:
13556   //  v_restore = 1
13557
13558   MachineBasicBlock *thisMBB = MBB;
13559   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13560   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13561   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13562   MF->insert(I, mainMBB);
13563   MF->insert(I, sinkMBB);
13564   MF->push_back(restoreMBB);
13565
13566   MachineInstrBuilder MIB;
13567
13568   // Transfer the remainder of BB and its successor edges to sinkMBB.
13569   sinkMBB->splice(sinkMBB->begin(), MBB,
13570                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13571   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13572
13573   // thisMBB:
13574   unsigned PtrStoreOpc = 0;
13575   unsigned LabelReg = 0;
13576   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13577   Reloc::Model RM = getTargetMachine().getRelocationModel();
13578   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13579                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13580
13581   // Prepare IP either in reg or imm.
13582   if (!UseImmLabel) {
13583     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13584     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13585     LabelReg = MRI.createVirtualRegister(PtrRC);
13586     if (Subtarget->is64Bit()) {
13587       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13588               .addReg(X86::RIP)
13589               .addImm(0)
13590               .addReg(0)
13591               .addMBB(restoreMBB)
13592               .addReg(0);
13593     } else {
13594       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13595       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13596               .addReg(XII->getGlobalBaseReg(MF))
13597               .addImm(0)
13598               .addReg(0)
13599               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13600               .addReg(0);
13601     }
13602   } else
13603     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13604   // Store IP
13605   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13606   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13607     if (i == X86::AddrDisp)
13608       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13609     else
13610       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13611   }
13612   if (!UseImmLabel)
13613     MIB.addReg(LabelReg);
13614   else
13615     MIB.addMBB(restoreMBB);
13616   MIB.setMemRefs(MMOBegin, MMOEnd);
13617   // Setup
13618   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13619           .addMBB(restoreMBB);
13620   MIB.addRegMask(RegInfo->getNoPreservedMask());
13621   thisMBB->addSuccessor(mainMBB);
13622   thisMBB->addSuccessor(restoreMBB);
13623
13624   // mainMBB:
13625   //  EAX = 0
13626   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13627   mainMBB->addSuccessor(sinkMBB);
13628
13629   // sinkMBB:
13630   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13631           TII->get(X86::PHI), DstReg)
13632     .addReg(mainDstReg).addMBB(mainMBB)
13633     .addReg(restoreDstReg).addMBB(restoreMBB);
13634
13635   // restoreMBB:
13636   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13637   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13638   restoreMBB->addSuccessor(sinkMBB);
13639
13640   MI->eraseFromParent();
13641   return sinkMBB;
13642 }
13643
13644 MachineBasicBlock *
13645 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13646                                      MachineBasicBlock *MBB) const {
13647   DebugLoc DL = MI->getDebugLoc();
13648   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13649
13650   MachineFunction *MF = MBB->getParent();
13651   MachineRegisterInfo &MRI = MF->getRegInfo();
13652
13653   // Memory Reference
13654   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13655   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13656
13657   MVT PVT = getPointerTy();
13658   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13659          "Invalid Pointer Size!");
13660
13661   const TargetRegisterClass *RC =
13662     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13663   unsigned Tmp = MRI.createVirtualRegister(RC);
13664   // Since FP is only updated here but NOT referenced, it's treated as GPR.
13665   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13666   unsigned SP = RegInfo->getStackRegister();
13667
13668   MachineInstrBuilder MIB;
13669
13670   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13671   const int64_t SPOffset = 2 * PVT.getStoreSize();
13672
13673   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13674   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13675
13676   // Reload FP
13677   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13678   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13679     MIB.addOperand(MI->getOperand(i));
13680   MIB.setMemRefs(MMOBegin, MMOEnd);
13681   // Reload IP
13682   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13683   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13684     if (i == X86::AddrDisp)
13685       MIB.addDisp(MI->getOperand(i), LabelOffset);
13686     else
13687       MIB.addOperand(MI->getOperand(i));
13688   }
13689   MIB.setMemRefs(MMOBegin, MMOEnd);
13690   // Reload SP
13691   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13692   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13693     if (i == X86::AddrDisp)
13694       MIB.addDisp(MI->getOperand(i), SPOffset);
13695     else
13696       MIB.addOperand(MI->getOperand(i));
13697   }
13698   MIB.setMemRefs(MMOBegin, MMOEnd);
13699   // Jump
13700   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13701
13702   MI->eraseFromParent();
13703   return MBB;
13704 }
13705
13706 MachineBasicBlock *
13707 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13708                                                MachineBasicBlock *BB) const {
13709   switch (MI->getOpcode()) {
13710   default: llvm_unreachable("Unexpected instr type to insert");
13711   case X86::TAILJMPd64:
13712   case X86::TAILJMPr64:
13713   case X86::TAILJMPm64:
13714     llvm_unreachable("TAILJMP64 would not be touched here.");
13715   case X86::TCRETURNdi64:
13716   case X86::TCRETURNri64:
13717   case X86::TCRETURNmi64:
13718     return BB;
13719   case X86::WIN_ALLOCA:
13720     return EmitLoweredWinAlloca(MI, BB);
13721   case X86::SEG_ALLOCA_32:
13722     return EmitLoweredSegAlloca(MI, BB, false);
13723   case X86::SEG_ALLOCA_64:
13724     return EmitLoweredSegAlloca(MI, BB, true);
13725   case X86::TLSCall_32:
13726   case X86::TLSCall_64:
13727     return EmitLoweredTLSCall(MI, BB);
13728   case X86::CMOV_GR8:
13729   case X86::CMOV_FR32:
13730   case X86::CMOV_FR64:
13731   case X86::CMOV_V4F32:
13732   case X86::CMOV_V2F64:
13733   case X86::CMOV_V2I64:
13734   case X86::CMOV_V8F32:
13735   case X86::CMOV_V4F64:
13736   case X86::CMOV_V4I64:
13737   case X86::CMOV_GR16:
13738   case X86::CMOV_GR32:
13739   case X86::CMOV_RFP32:
13740   case X86::CMOV_RFP64:
13741   case X86::CMOV_RFP80:
13742     return EmitLoweredSelect(MI, BB);
13743
13744   case X86::FP32_TO_INT16_IN_MEM:
13745   case X86::FP32_TO_INT32_IN_MEM:
13746   case X86::FP32_TO_INT64_IN_MEM:
13747   case X86::FP64_TO_INT16_IN_MEM:
13748   case X86::FP64_TO_INT32_IN_MEM:
13749   case X86::FP64_TO_INT64_IN_MEM:
13750   case X86::FP80_TO_INT16_IN_MEM:
13751   case X86::FP80_TO_INT32_IN_MEM:
13752   case X86::FP80_TO_INT64_IN_MEM: {
13753     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13754     DebugLoc DL = MI->getDebugLoc();
13755
13756     // Change the floating point control register to use "round towards zero"
13757     // mode when truncating to an integer value.
13758     MachineFunction *F = BB->getParent();
13759     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13760     addFrameReference(BuildMI(*BB, MI, DL,
13761                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
13762
13763     // Load the old value of the high byte of the control word...
13764     unsigned OldCW =
13765       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13766     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13767                       CWFrameIdx);
13768
13769     // Set the high part to be round to zero...
13770     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13771       .addImm(0xC7F);
13772
13773     // Reload the modified control word now...
13774     addFrameReference(BuildMI(*BB, MI, DL,
13775                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13776
13777     // Restore the memory image of control word to original value
13778     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13779       .addReg(OldCW);
13780
13781     // Get the X86 opcode to use.
13782     unsigned Opc;
13783     switch (MI->getOpcode()) {
13784     default: llvm_unreachable("illegal opcode!");
13785     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13786     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13787     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13788     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13789     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13790     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13791     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13792     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13793     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13794     }
13795
13796     X86AddressMode AM;
13797     MachineOperand &Op = MI->getOperand(0);
13798     if (Op.isReg()) {
13799       AM.BaseType = X86AddressMode::RegBase;
13800       AM.Base.Reg = Op.getReg();
13801     } else {
13802       AM.BaseType = X86AddressMode::FrameIndexBase;
13803       AM.Base.FrameIndex = Op.getIndex();
13804     }
13805     Op = MI->getOperand(1);
13806     if (Op.isImm())
13807       AM.Scale = Op.getImm();
13808     Op = MI->getOperand(2);
13809     if (Op.isImm())
13810       AM.IndexReg = Op.getImm();
13811     Op = MI->getOperand(3);
13812     if (Op.isGlobal()) {
13813       AM.GV = Op.getGlobal();
13814     } else {
13815       AM.Disp = Op.getImm();
13816     }
13817     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13818                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13819
13820     // Reload the original control word now.
13821     addFrameReference(BuildMI(*BB, MI, DL,
13822                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13823
13824     MI->eraseFromParent();   // The pseudo instruction is gone now.
13825     return BB;
13826   }
13827     // String/text processing lowering.
13828   case X86::PCMPISTRM128REG:
13829   case X86::VPCMPISTRM128REG:
13830   case X86::PCMPISTRM128MEM:
13831   case X86::VPCMPISTRM128MEM:
13832   case X86::PCMPESTRM128REG:
13833   case X86::VPCMPESTRM128REG:
13834   case X86::PCMPESTRM128MEM:
13835   case X86::VPCMPESTRM128MEM: {
13836     unsigned NumArgs;
13837     bool MemArg;
13838     switch (MI->getOpcode()) {
13839     default: llvm_unreachable("illegal opcode!");
13840     case X86::PCMPISTRM128REG:
13841     case X86::VPCMPISTRM128REG:
13842       NumArgs = 3; MemArg = false; break;
13843     case X86::PCMPISTRM128MEM:
13844     case X86::VPCMPISTRM128MEM:
13845       NumArgs = 3; MemArg = true; break;
13846     case X86::PCMPESTRM128REG:
13847     case X86::VPCMPESTRM128REG:
13848       NumArgs = 5; MemArg = false; break;
13849     case X86::PCMPESTRM128MEM:
13850     case X86::VPCMPESTRM128MEM:
13851       NumArgs = 5; MemArg = true; break;
13852     }
13853     return EmitPCMP(MI, BB, NumArgs, MemArg);
13854   }
13855
13856     // Thread synchronization.
13857   case X86::MONITOR:
13858     return EmitMonitor(MI, BB);
13859
13860     // Atomic Lowering.
13861   case X86::ATOMAND8:
13862   case X86::ATOMAND16:
13863   case X86::ATOMAND32:
13864   case X86::ATOMAND64:
13865     // Fall through
13866   case X86::ATOMOR8:
13867   case X86::ATOMOR16:
13868   case X86::ATOMOR32:
13869   case X86::ATOMOR64:
13870     // Fall through
13871   case X86::ATOMXOR16:
13872   case X86::ATOMXOR8:
13873   case X86::ATOMXOR32:
13874   case X86::ATOMXOR64:
13875     // Fall through
13876   case X86::ATOMNAND8:
13877   case X86::ATOMNAND16:
13878   case X86::ATOMNAND32:
13879   case X86::ATOMNAND64:
13880     // Fall through
13881   case X86::ATOMMAX8:
13882   case X86::ATOMMAX16:
13883   case X86::ATOMMAX32:
13884   case X86::ATOMMAX64:
13885     // Fall through
13886   case X86::ATOMMIN8:
13887   case X86::ATOMMIN16:
13888   case X86::ATOMMIN32:
13889   case X86::ATOMMIN64:
13890     // Fall through
13891   case X86::ATOMUMAX8:
13892   case X86::ATOMUMAX16:
13893   case X86::ATOMUMAX32:
13894   case X86::ATOMUMAX64:
13895     // Fall through
13896   case X86::ATOMUMIN8:
13897   case X86::ATOMUMIN16:
13898   case X86::ATOMUMIN32:
13899   case X86::ATOMUMIN64:
13900     return EmitAtomicLoadArith(MI, BB);
13901
13902   // This group does 64-bit operations on a 32-bit host.
13903   case X86::ATOMAND6432:
13904   case X86::ATOMOR6432:
13905   case X86::ATOMXOR6432:
13906   case X86::ATOMNAND6432:
13907   case X86::ATOMADD6432:
13908   case X86::ATOMSUB6432:
13909   case X86::ATOMMAX6432:
13910   case X86::ATOMMIN6432:
13911   case X86::ATOMUMAX6432:
13912   case X86::ATOMUMIN6432:
13913   case X86::ATOMSWAP6432:
13914     return EmitAtomicLoadArith6432(MI, BB);
13915
13916   case X86::VASTART_SAVE_XMM_REGS:
13917     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13918
13919   case X86::VAARG_64:
13920     return EmitVAARG64WithCustomInserter(MI, BB);
13921
13922   case X86::EH_SjLj_SetJmp32:
13923   case X86::EH_SjLj_SetJmp64:
13924     return emitEHSjLjSetJmp(MI, BB);
13925
13926   case X86::EH_SjLj_LongJmp32:
13927   case X86::EH_SjLj_LongJmp64:
13928     return emitEHSjLjLongJmp(MI, BB);
13929   }
13930 }
13931
13932 //===----------------------------------------------------------------------===//
13933 //                           X86 Optimization Hooks
13934 //===----------------------------------------------------------------------===//
13935
13936 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13937                                                        APInt &KnownZero,
13938                                                        APInt &KnownOne,
13939                                                        const SelectionDAG &DAG,
13940                                                        unsigned Depth) const {
13941   unsigned BitWidth = KnownZero.getBitWidth();
13942   unsigned Opc = Op.getOpcode();
13943   assert((Opc >= ISD::BUILTIN_OP_END ||
13944           Opc == ISD::INTRINSIC_WO_CHAIN ||
13945           Opc == ISD::INTRINSIC_W_CHAIN ||
13946           Opc == ISD::INTRINSIC_VOID) &&
13947          "Should use MaskedValueIsZero if you don't know whether Op"
13948          " is a target node!");
13949
13950   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13951   switch (Opc) {
13952   default: break;
13953   case X86ISD::ADD:
13954   case X86ISD::SUB:
13955   case X86ISD::ADC:
13956   case X86ISD::SBB:
13957   case X86ISD::SMUL:
13958   case X86ISD::UMUL:
13959   case X86ISD::INC:
13960   case X86ISD::DEC:
13961   case X86ISD::OR:
13962   case X86ISD::XOR:
13963   case X86ISD::AND:
13964     // These nodes' second result is a boolean.
13965     if (Op.getResNo() == 0)
13966       break;
13967     // Fallthrough
13968   case X86ISD::SETCC:
13969     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13970     break;
13971   case ISD::INTRINSIC_WO_CHAIN: {
13972     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13973     unsigned NumLoBits = 0;
13974     switch (IntId) {
13975     default: break;
13976     case Intrinsic::x86_sse_movmsk_ps:
13977     case Intrinsic::x86_avx_movmsk_ps_256:
13978     case Intrinsic::x86_sse2_movmsk_pd:
13979     case Intrinsic::x86_avx_movmsk_pd_256:
13980     case Intrinsic::x86_mmx_pmovmskb:
13981     case Intrinsic::x86_sse2_pmovmskb_128:
13982     case Intrinsic::x86_avx2_pmovmskb: {
13983       // High bits of movmskp{s|d}, pmovmskb are known zero.
13984       switch (IntId) {
13985         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13986         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13987         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13988         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13989         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13990         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13991         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13992         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13993       }
13994       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13995       break;
13996     }
13997     }
13998     break;
13999   }
14000   }
14001 }
14002
14003 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14004                                                          unsigned Depth) const {
14005   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14006   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14007     return Op.getValueType().getScalarType().getSizeInBits();
14008
14009   // Fallback case.
14010   return 1;
14011 }
14012
14013 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14014 /// node is a GlobalAddress + offset.
14015 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14016                                        const GlobalValue* &GA,
14017                                        int64_t &Offset) const {
14018   if (N->getOpcode() == X86ISD::Wrapper) {
14019     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14020       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14021       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14022       return true;
14023     }
14024   }
14025   return TargetLowering::isGAPlusOffset(N, GA, Offset);
14026 }
14027
14028 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14029 /// same as extracting the high 128-bit part of 256-bit vector and then
14030 /// inserting the result into the low part of a new 256-bit vector
14031 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14032   EVT VT = SVOp->getValueType(0);
14033   unsigned NumElems = VT.getVectorNumElements();
14034
14035   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14036   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14037     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14038         SVOp->getMaskElt(j) >= 0)
14039       return false;
14040
14041   return true;
14042 }
14043
14044 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14045 /// same as extracting the low 128-bit part of 256-bit vector and then
14046 /// inserting the result into the high part of a new 256-bit vector
14047 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14048   EVT VT = SVOp->getValueType(0);
14049   unsigned NumElems = VT.getVectorNumElements();
14050
14051   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14052   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14053     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14054         SVOp->getMaskElt(j) >= 0)
14055       return false;
14056
14057   return true;
14058 }
14059
14060 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14061 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14062                                         TargetLowering::DAGCombinerInfo &DCI,
14063                                         const X86Subtarget* Subtarget) {
14064   DebugLoc dl = N->getDebugLoc();
14065   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14066   SDValue V1 = SVOp->getOperand(0);
14067   SDValue V2 = SVOp->getOperand(1);
14068   EVT VT = SVOp->getValueType(0);
14069   unsigned NumElems = VT.getVectorNumElements();
14070
14071   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14072       V2.getOpcode() == ISD::CONCAT_VECTORS) {
14073     //
14074     //                   0,0,0,...
14075     //                      |
14076     //    V      UNDEF    BUILD_VECTOR    UNDEF
14077     //     \      /           \           /
14078     //  CONCAT_VECTOR         CONCAT_VECTOR
14079     //         \                  /
14080     //          \                /
14081     //          RESULT: V + zero extended
14082     //
14083     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14084         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14085         V1.getOperand(1).getOpcode() != ISD::UNDEF)
14086       return SDValue();
14087
14088     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14089       return SDValue();
14090
14091     // To match the shuffle mask, the first half of the mask should
14092     // be exactly the first vector, and all the rest a splat with the
14093     // first element of the second one.
14094     for (unsigned i = 0; i != NumElems/2; ++i)
14095       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14096           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14097         return SDValue();
14098
14099     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14100     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14101       if (Ld->hasNUsesOfValue(1, 0)) {
14102         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14103         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14104         SDValue ResNode =
14105           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14106                                   Ld->getMemoryVT(),
14107                                   Ld->getPointerInfo(),
14108                                   Ld->getAlignment(),
14109                                   false/*isVolatile*/, true/*ReadMem*/,
14110                                   false/*WriteMem*/);
14111         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14112       }
14113     }
14114
14115     // Emit a zeroed vector and insert the desired subvector on its
14116     // first half.
14117     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14118     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14119     return DCI.CombineTo(N, InsV);
14120   }
14121
14122   //===--------------------------------------------------------------------===//
14123   // Combine some shuffles into subvector extracts and inserts:
14124   //
14125
14126   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14127   if (isShuffleHigh128VectorInsertLow(SVOp)) {
14128     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14129     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14130     return DCI.CombineTo(N, InsV);
14131   }
14132
14133   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14134   if (isShuffleLow128VectorInsertHigh(SVOp)) {
14135     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14136     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14137     return DCI.CombineTo(N, InsV);
14138   }
14139
14140   return SDValue();
14141 }
14142
14143 /// PerformShuffleCombine - Performs several different shuffle combines.
14144 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14145                                      TargetLowering::DAGCombinerInfo &DCI,
14146                                      const X86Subtarget *Subtarget) {
14147   DebugLoc dl = N->getDebugLoc();
14148   EVT VT = N->getValueType(0);
14149
14150   // Don't create instructions with illegal types after legalize types has run.
14151   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14152   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14153     return SDValue();
14154
14155   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14156   if (Subtarget->hasAVX() && VT.is256BitVector() &&
14157       N->getOpcode() == ISD::VECTOR_SHUFFLE)
14158     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14159
14160   // Only handle 128 wide vector from here on.
14161   if (!VT.is128BitVector())
14162     return SDValue();
14163
14164   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14165   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14166   // consecutive, non-overlapping, and in the right order.
14167   SmallVector<SDValue, 16> Elts;
14168   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14169     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14170
14171   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14172 }
14173
14174
14175 /// PerformTruncateCombine - Converts truncate operation to
14176 /// a sequence of vector shuffle operations.
14177 /// It is possible when we truncate 256-bit vector to 128-bit vector
14178 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14179                                       TargetLowering::DAGCombinerInfo &DCI,
14180                                       const X86Subtarget *Subtarget)  {
14181   if (!DCI.isBeforeLegalizeOps())
14182     return SDValue();
14183
14184   if (!Subtarget->hasAVX())
14185     return SDValue();
14186
14187   EVT VT = N->getValueType(0);
14188   SDValue Op = N->getOperand(0);
14189   EVT OpVT = Op.getValueType();
14190   DebugLoc dl = N->getDebugLoc();
14191
14192   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14193
14194     if (Subtarget->hasAVX2()) {
14195       // AVX2: v4i64 -> v4i32
14196
14197       // VPERMD
14198       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14199
14200       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14201       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14202                                 ShufMask);
14203
14204       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14205                          DAG.getIntPtrConstant(0));
14206     }
14207
14208     // AVX: v4i64 -> v4i32
14209     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14210                                DAG.getIntPtrConstant(0));
14211
14212     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14213                                DAG.getIntPtrConstant(2));
14214
14215     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14216     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14217
14218     // PSHUFD
14219     static const int ShufMask1[] = {0, 2, 0, 0};
14220
14221     SDValue Undef = DAG.getUNDEF(VT);
14222     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14223     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14224
14225     // MOVLHPS
14226     static const int ShufMask2[] = {0, 1, 4, 5};
14227
14228     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14229   }
14230
14231   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14232
14233     if (Subtarget->hasAVX2()) {
14234       // AVX2: v8i32 -> v8i16
14235
14236       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14237
14238       // PSHUFB
14239       SmallVector<SDValue,32> pshufbMask;
14240       for (unsigned i = 0; i < 2; ++i) {
14241         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14242         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14243         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14244         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14245         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14246         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14247         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14248         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14249         for (unsigned j = 0; j < 8; ++j)
14250           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14251       }
14252       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14253                                &pshufbMask[0], 32);
14254       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14255
14256       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14257
14258       static const int ShufMask[] = {0,  2,  -1,  -1};
14259       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
14260                                 &ShufMask[0]);
14261
14262       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14263                        DAG.getIntPtrConstant(0));
14264
14265       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14266     }
14267
14268     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14269                                DAG.getIntPtrConstant(0));
14270
14271     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14272                                DAG.getIntPtrConstant(4));
14273
14274     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14275     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14276
14277     // PSHUFB
14278     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14279                                    -1, -1, -1, -1, -1, -1, -1, -1};
14280
14281     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14282     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14283     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14284
14285     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14286     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14287
14288     // MOVLHPS
14289     static const int ShufMask2[] = {0, 1, 4, 5};
14290
14291     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14292     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14293   }
14294
14295   return SDValue();
14296 }
14297
14298 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14299 /// specific shuffle of a load can be folded into a single element load.
14300 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14301 /// shuffles have been customed lowered so we need to handle those here.
14302 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14303                                          TargetLowering::DAGCombinerInfo &DCI) {
14304   if (DCI.isBeforeLegalizeOps())
14305     return SDValue();
14306
14307   SDValue InVec = N->getOperand(0);
14308   SDValue EltNo = N->getOperand(1);
14309
14310   if (!isa<ConstantSDNode>(EltNo))
14311     return SDValue();
14312
14313   EVT VT = InVec.getValueType();
14314
14315   bool HasShuffleIntoBitcast = false;
14316   if (InVec.getOpcode() == ISD::BITCAST) {
14317     // Don't duplicate a load with other uses.
14318     if (!InVec.hasOneUse())
14319       return SDValue();
14320     EVT BCVT = InVec.getOperand(0).getValueType();
14321     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14322       return SDValue();
14323     InVec = InVec.getOperand(0);
14324     HasShuffleIntoBitcast = true;
14325   }
14326
14327   if (!isTargetShuffle(InVec.getOpcode()))
14328     return SDValue();
14329
14330   // Don't duplicate a load with other uses.
14331   if (!InVec.hasOneUse())
14332     return SDValue();
14333
14334   SmallVector<int, 16> ShuffleMask;
14335   bool UnaryShuffle;
14336   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14337                             UnaryShuffle))
14338     return SDValue();
14339
14340   // Select the input vector, guarding against out of range extract vector.
14341   unsigned NumElems = VT.getVectorNumElements();
14342   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14343   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14344   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14345                                          : InVec.getOperand(1);
14346
14347   // If inputs to shuffle are the same for both ops, then allow 2 uses
14348   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14349
14350   if (LdNode.getOpcode() == ISD::BITCAST) {
14351     // Don't duplicate a load with other uses.
14352     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14353       return SDValue();
14354
14355     AllowedUses = 1; // only allow 1 load use if we have a bitcast
14356     LdNode = LdNode.getOperand(0);
14357   }
14358
14359   if (!ISD::isNormalLoad(LdNode.getNode()))
14360     return SDValue();
14361
14362   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14363
14364   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14365     return SDValue();
14366
14367   if (HasShuffleIntoBitcast) {
14368     // If there's a bitcast before the shuffle, check if the load type and
14369     // alignment is valid.
14370     unsigned Align = LN0->getAlignment();
14371     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14372     unsigned NewAlign = TLI.getDataLayout()->
14373       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14374
14375     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14376       return SDValue();
14377   }
14378
14379   // All checks match so transform back to vector_shuffle so that DAG combiner
14380   // can finish the job
14381   DebugLoc dl = N->getDebugLoc();
14382
14383   // Create shuffle node taking into account the case that its a unary shuffle
14384   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14385   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14386                                  InVec.getOperand(0), Shuffle,
14387                                  &ShuffleMask[0]);
14388   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14389   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14390                      EltNo);
14391 }
14392
14393 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14394 /// generation and convert it from being a bunch of shuffles and extracts
14395 /// to a simple store and scalar loads to extract the elements.
14396 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14397                                          TargetLowering::DAGCombinerInfo &DCI) {
14398   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14399   if (NewOp.getNode())
14400     return NewOp;
14401
14402   SDValue InputVector = N->getOperand(0);
14403
14404   // Only operate on vectors of 4 elements, where the alternative shuffling
14405   // gets to be more expensive.
14406   if (InputVector.getValueType() != MVT::v4i32)
14407     return SDValue();
14408
14409   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14410   // single use which is a sign-extend or zero-extend, and all elements are
14411   // used.
14412   SmallVector<SDNode *, 4> Uses;
14413   unsigned ExtractedElements = 0;
14414   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14415        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14416     if (UI.getUse().getResNo() != InputVector.getResNo())
14417       return SDValue();
14418
14419     SDNode *Extract = *UI;
14420     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14421       return SDValue();
14422
14423     if (Extract->getValueType(0) != MVT::i32)
14424       return SDValue();
14425     if (!Extract->hasOneUse())
14426       return SDValue();
14427     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14428         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14429       return SDValue();
14430     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14431       return SDValue();
14432
14433     // Record which element was extracted.
14434     ExtractedElements |=
14435       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14436
14437     Uses.push_back(Extract);
14438   }
14439
14440   // If not all the elements were used, this may not be worthwhile.
14441   if (ExtractedElements != 15)
14442     return SDValue();
14443
14444   // Ok, we've now decided to do the transformation.
14445   DebugLoc dl = InputVector.getDebugLoc();
14446
14447   // Store the value to a temporary stack slot.
14448   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14449   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14450                             MachinePointerInfo(), false, false, 0);
14451
14452   // Replace each use (extract) with a load of the appropriate element.
14453   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14454        UE = Uses.end(); UI != UE; ++UI) {
14455     SDNode *Extract = *UI;
14456
14457     // cOMpute the element's address.
14458     SDValue Idx = Extract->getOperand(1);
14459     unsigned EltSize =
14460         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14461     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14462     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14463     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14464
14465     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14466                                      StackPtr, OffsetVal);
14467
14468     // Load the scalar.
14469     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14470                                      ScalarAddr, MachinePointerInfo(),
14471                                      false, false, false, 0);
14472
14473     // Replace the exact with the load.
14474     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14475   }
14476
14477   // The replacement was made in place; don't return anything.
14478   return SDValue();
14479 }
14480
14481 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14482 /// nodes.
14483 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14484                                     TargetLowering::DAGCombinerInfo &DCI,
14485                                     const X86Subtarget *Subtarget) {
14486   DebugLoc DL = N->getDebugLoc();
14487   SDValue Cond = N->getOperand(0);
14488   // Get the LHS/RHS of the select.
14489   SDValue LHS = N->getOperand(1);
14490   SDValue RHS = N->getOperand(2);
14491   EVT VT = LHS.getValueType();
14492
14493   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14494   // instructions match the semantics of the common C idiom x<y?x:y but not
14495   // x<=y?x:y, because of how they handle negative zero (which can be
14496   // ignored in unsafe-math mode).
14497   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14498       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14499       (Subtarget->hasSSE2() ||
14500        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14501     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14502
14503     unsigned Opcode = 0;
14504     // Check for x CC y ? x : y.
14505     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14506         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14507       switch (CC) {
14508       default: break;
14509       case ISD::SETULT:
14510         // Converting this to a min would handle NaNs incorrectly, and swapping
14511         // the operands would cause it to handle comparisons between positive
14512         // and negative zero incorrectly.
14513         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14514           if (!DAG.getTarget().Options.UnsafeFPMath &&
14515               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14516             break;
14517           std::swap(LHS, RHS);
14518         }
14519         Opcode = X86ISD::FMIN;
14520         break;
14521       case ISD::SETOLE:
14522         // Converting this to a min would handle comparisons between positive
14523         // and negative zero incorrectly.
14524         if (!DAG.getTarget().Options.UnsafeFPMath &&
14525             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14526           break;
14527         Opcode = X86ISD::FMIN;
14528         break;
14529       case ISD::SETULE:
14530         // Converting this to a min would handle both negative zeros and NaNs
14531         // incorrectly, but we can swap the operands to fix both.
14532         std::swap(LHS, RHS);
14533       case ISD::SETOLT:
14534       case ISD::SETLT:
14535       case ISD::SETLE:
14536         Opcode = X86ISD::FMIN;
14537         break;
14538
14539       case ISD::SETOGE:
14540         // Converting this to a max would handle comparisons between positive
14541         // and negative zero incorrectly.
14542         if (!DAG.getTarget().Options.UnsafeFPMath &&
14543             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14544           break;
14545         Opcode = X86ISD::FMAX;
14546         break;
14547       case ISD::SETUGT:
14548         // Converting this to a max would handle NaNs incorrectly, and swapping
14549         // the operands would cause it to handle comparisons between positive
14550         // and negative zero incorrectly.
14551         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14552           if (!DAG.getTarget().Options.UnsafeFPMath &&
14553               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14554             break;
14555           std::swap(LHS, RHS);
14556         }
14557         Opcode = X86ISD::FMAX;
14558         break;
14559       case ISD::SETUGE:
14560         // Converting this to a max would handle both negative zeros and NaNs
14561         // incorrectly, but we can swap the operands to fix both.
14562         std::swap(LHS, RHS);
14563       case ISD::SETOGT:
14564       case ISD::SETGT:
14565       case ISD::SETGE:
14566         Opcode = X86ISD::FMAX;
14567         break;
14568       }
14569     // Check for x CC y ? y : x -- a min/max with reversed arms.
14570     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14571                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14572       switch (CC) {
14573       default: break;
14574       case ISD::SETOGE:
14575         // Converting this to a min would handle comparisons between positive
14576         // and negative zero incorrectly, and swapping the operands would
14577         // cause it to handle NaNs incorrectly.
14578         if (!DAG.getTarget().Options.UnsafeFPMath &&
14579             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14580           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14581             break;
14582           std::swap(LHS, RHS);
14583         }
14584         Opcode = X86ISD::FMIN;
14585         break;
14586       case ISD::SETUGT:
14587         // Converting this to a min would handle NaNs incorrectly.
14588         if (!DAG.getTarget().Options.UnsafeFPMath &&
14589             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14590           break;
14591         Opcode = X86ISD::FMIN;
14592         break;
14593       case ISD::SETUGE:
14594         // Converting this to a min would handle both negative zeros and NaNs
14595         // incorrectly, but we can swap the operands to fix both.
14596         std::swap(LHS, RHS);
14597       case ISD::SETOGT:
14598       case ISD::SETGT:
14599       case ISD::SETGE:
14600         Opcode = X86ISD::FMIN;
14601         break;
14602
14603       case ISD::SETULT:
14604         // Converting this to a max would handle NaNs incorrectly.
14605         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14606           break;
14607         Opcode = X86ISD::FMAX;
14608         break;
14609       case ISD::SETOLE:
14610         // Converting this to a max would handle comparisons between positive
14611         // and negative zero incorrectly, and swapping the operands would
14612         // cause it to handle NaNs incorrectly.
14613         if (!DAG.getTarget().Options.UnsafeFPMath &&
14614             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14615           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14616             break;
14617           std::swap(LHS, RHS);
14618         }
14619         Opcode = X86ISD::FMAX;
14620         break;
14621       case ISD::SETULE:
14622         // Converting this to a max would handle both negative zeros and NaNs
14623         // incorrectly, but we can swap the operands to fix both.
14624         std::swap(LHS, RHS);
14625       case ISD::SETOLT:
14626       case ISD::SETLT:
14627       case ISD::SETLE:
14628         Opcode = X86ISD::FMAX;
14629         break;
14630       }
14631     }
14632
14633     if (Opcode)
14634       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14635   }
14636
14637   // If this is a select between two integer constants, try to do some
14638   // optimizations.
14639   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14640     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14641       // Don't do this for crazy integer types.
14642       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14643         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14644         // so that TrueC (the true value) is larger than FalseC.
14645         bool NeedsCondInvert = false;
14646
14647         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14648             // Efficiently invertible.
14649             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
14650              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
14651               isa<ConstantSDNode>(Cond.getOperand(1))))) {
14652           NeedsCondInvert = true;
14653           std::swap(TrueC, FalseC);
14654         }
14655
14656         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
14657         if (FalseC->getAPIntValue() == 0 &&
14658             TrueC->getAPIntValue().isPowerOf2()) {
14659           if (NeedsCondInvert) // Invert the condition if needed.
14660             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14661                                DAG.getConstant(1, Cond.getValueType()));
14662
14663           // Zero extend the condition if needed.
14664           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14665
14666           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14667           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14668                              DAG.getConstant(ShAmt, MVT::i8));
14669         }
14670
14671         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14672         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14673           if (NeedsCondInvert) // Invert the condition if needed.
14674             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14675                                DAG.getConstant(1, Cond.getValueType()));
14676
14677           // Zero extend the condition if needed.
14678           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14679                              FalseC->getValueType(0), Cond);
14680           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14681                              SDValue(FalseC, 0));
14682         }
14683
14684         // Optimize cases that will turn into an LEA instruction.  This requires
14685         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14686         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14687           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14688           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14689
14690           bool isFastMultiplier = false;
14691           if (Diff < 10) {
14692             switch ((unsigned char)Diff) {
14693               default: break;
14694               case 1:  // result = add base, cond
14695               case 2:  // result = lea base(    , cond*2)
14696               case 3:  // result = lea base(cond, cond*2)
14697               case 4:  // result = lea base(    , cond*4)
14698               case 5:  // result = lea base(cond, cond*4)
14699               case 8:  // result = lea base(    , cond*8)
14700               case 9:  // result = lea base(cond, cond*8)
14701                 isFastMultiplier = true;
14702                 break;
14703             }
14704           }
14705
14706           if (isFastMultiplier) {
14707             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14708             if (NeedsCondInvert) // Invert the condition if needed.
14709               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14710                                  DAG.getConstant(1, Cond.getValueType()));
14711
14712             // Zero extend the condition if needed.
14713             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14714                                Cond);
14715             // Scale the condition by the difference.
14716             if (Diff != 1)
14717               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14718                                  DAG.getConstant(Diff, Cond.getValueType()));
14719
14720             // Add the base if non-zero.
14721             if (FalseC->getAPIntValue() != 0)
14722               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14723                                  SDValue(FalseC, 0));
14724             return Cond;
14725           }
14726         }
14727       }
14728   }
14729
14730   // Canonicalize max and min:
14731   // (x > y) ? x : y -> (x >= y) ? x : y
14732   // (x < y) ? x : y -> (x <= y) ? x : y
14733   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14734   // the need for an extra compare
14735   // against zero. e.g.
14736   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14737   // subl   %esi, %edi
14738   // testl  %edi, %edi
14739   // movl   $0, %eax
14740   // cmovgl %edi, %eax
14741   // =>
14742   // xorl   %eax, %eax
14743   // subl   %esi, $edi
14744   // cmovsl %eax, %edi
14745   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14746       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14747       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14748     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14749     switch (CC) {
14750     default: break;
14751     case ISD::SETLT:
14752     case ISD::SETGT: {
14753       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14754       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14755                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14756       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14757     }
14758     }
14759   }
14760
14761   // If we know that this node is legal then we know that it is going to be
14762   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14763   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14764   // to simplify previous instructions.
14765   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14766   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14767       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14768     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14769
14770     // Don't optimize vector selects that map to mask-registers.
14771     if (BitWidth == 1)
14772       return SDValue();
14773
14774     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14775     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14776
14777     APInt KnownZero, KnownOne;
14778     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14779                                           DCI.isBeforeLegalizeOps());
14780     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14781         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14782       DCI.CommitTargetLoweringOpt(TLO);
14783   }
14784
14785   return SDValue();
14786 }
14787
14788 // Check whether a boolean test is testing a boolean value generated by
14789 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14790 // code.
14791 //
14792 // Simplify the following patterns:
14793 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14794 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14795 // to (Op EFLAGS Cond)
14796 //
14797 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14798 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14799 // to (Op EFLAGS !Cond)
14800 //
14801 // where Op could be BRCOND or CMOV.
14802 //
14803 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14804   // Quit if not CMP and SUB with its value result used.
14805   if (Cmp.getOpcode() != X86ISD::CMP &&
14806       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14807       return SDValue();
14808
14809   // Quit if not used as a boolean value.
14810   if (CC != X86::COND_E && CC != X86::COND_NE)
14811     return SDValue();
14812
14813   // Check CMP operands. One of them should be 0 or 1 and the other should be
14814   // an SetCC or extended from it.
14815   SDValue Op1 = Cmp.getOperand(0);
14816   SDValue Op2 = Cmp.getOperand(1);
14817
14818   SDValue SetCC;
14819   const ConstantSDNode* C = 0;
14820   bool needOppositeCond = (CC == X86::COND_E);
14821
14822   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14823     SetCC = Op2;
14824   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14825     SetCC = Op1;
14826   else // Quit if all operands are not constants.
14827     return SDValue();
14828
14829   if (C->getZExtValue() == 1)
14830     needOppositeCond = !needOppositeCond;
14831   else if (C->getZExtValue() != 0)
14832     // Quit if the constant is neither 0 or 1.
14833     return SDValue();
14834
14835   // Skip 'zext' node.
14836   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14837     SetCC = SetCC.getOperand(0);
14838
14839   switch (SetCC.getOpcode()) {
14840   case X86ISD::SETCC:
14841     // Set the condition code or opposite one if necessary.
14842     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14843     if (needOppositeCond)
14844       CC = X86::GetOppositeBranchCondition(CC);
14845     return SetCC.getOperand(1);
14846   case X86ISD::CMOV: {
14847     // Check whether false/true value has canonical one, i.e. 0 or 1.
14848     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14849     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14850     // Quit if true value is not a constant.
14851     if (!TVal)
14852       return SDValue();
14853     // Quit if false value is not a constant.
14854     if (!FVal) {
14855       // A special case for rdrand, where 0 is set if false cond is found.
14856       SDValue Op = SetCC.getOperand(0);
14857       if (Op.getOpcode() != X86ISD::RDRAND)
14858         return SDValue();
14859     }
14860     // Quit if false value is not the constant 0 or 1.
14861     bool FValIsFalse = true;
14862     if (FVal && FVal->getZExtValue() != 0) {
14863       if (FVal->getZExtValue() != 1)
14864         return SDValue();
14865       // If FVal is 1, opposite cond is needed.
14866       needOppositeCond = !needOppositeCond;
14867       FValIsFalse = false;
14868     }
14869     // Quit if TVal is not the constant opposite of FVal.
14870     if (FValIsFalse && TVal->getZExtValue() != 1)
14871       return SDValue();
14872     if (!FValIsFalse && TVal->getZExtValue() != 0)
14873       return SDValue();
14874     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14875     if (needOppositeCond)
14876       CC = X86::GetOppositeBranchCondition(CC);
14877     return SetCC.getOperand(3);
14878   }
14879   }
14880
14881   return SDValue();
14882 }
14883
14884 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14885 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14886                                   TargetLowering::DAGCombinerInfo &DCI,
14887                                   const X86Subtarget *Subtarget) {
14888   DebugLoc DL = N->getDebugLoc();
14889
14890   // If the flag operand isn't dead, don't touch this CMOV.
14891   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14892     return SDValue();
14893
14894   SDValue FalseOp = N->getOperand(0);
14895   SDValue TrueOp = N->getOperand(1);
14896   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14897   SDValue Cond = N->getOperand(3);
14898
14899   if (CC == X86::COND_E || CC == X86::COND_NE) {
14900     switch (Cond.getOpcode()) {
14901     default: break;
14902     case X86ISD::BSR:
14903     case X86ISD::BSF:
14904       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14905       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14906         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14907     }
14908   }
14909
14910   SDValue Flags;
14911
14912   Flags = checkBoolTestSetCCCombine(Cond, CC);
14913   if (Flags.getNode() &&
14914       // Extra check as FCMOV only supports a subset of X86 cond.
14915       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14916     SDValue Ops[] = { FalseOp, TrueOp,
14917                       DAG.getConstant(CC, MVT::i8), Flags };
14918     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14919                        Ops, array_lengthof(Ops));
14920   }
14921
14922   // If this is a select between two integer constants, try to do some
14923   // optimizations.  Note that the operands are ordered the opposite of SELECT
14924   // operands.
14925   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14926     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14927       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14928       // larger than FalseC (the false value).
14929       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14930         CC = X86::GetOppositeBranchCondition(CC);
14931         std::swap(TrueC, FalseC);
14932         std::swap(TrueOp, FalseOp);
14933       }
14934
14935       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14936       // This is efficient for any integer data type (including i8/i16) and
14937       // shift amount.
14938       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14939         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14940                            DAG.getConstant(CC, MVT::i8), Cond);
14941
14942         // Zero extend the condition if needed.
14943         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14944
14945         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14946         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14947                            DAG.getConstant(ShAmt, MVT::i8));
14948         if (N->getNumValues() == 2)  // Dead flag value?
14949           return DCI.CombineTo(N, Cond, SDValue());
14950         return Cond;
14951       }
14952
14953       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14954       // for any integer data type, including i8/i16.
14955       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14956         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14957                            DAG.getConstant(CC, MVT::i8), Cond);
14958
14959         // Zero extend the condition if needed.
14960         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14961                            FalseC->getValueType(0), Cond);
14962         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14963                            SDValue(FalseC, 0));
14964
14965         if (N->getNumValues() == 2)  // Dead flag value?
14966           return DCI.CombineTo(N, Cond, SDValue());
14967         return Cond;
14968       }
14969
14970       // Optimize cases that will turn into an LEA instruction.  This requires
14971       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14972       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14973         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14974         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14975
14976         bool isFastMultiplier = false;
14977         if (Diff < 10) {
14978           switch ((unsigned char)Diff) {
14979           default: break;
14980           case 1:  // result = add base, cond
14981           case 2:  // result = lea base(    , cond*2)
14982           case 3:  // result = lea base(cond, cond*2)
14983           case 4:  // result = lea base(    , cond*4)
14984           case 5:  // result = lea base(cond, cond*4)
14985           case 8:  // result = lea base(    , cond*8)
14986           case 9:  // result = lea base(cond, cond*8)
14987             isFastMultiplier = true;
14988             break;
14989           }
14990         }
14991
14992         if (isFastMultiplier) {
14993           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14994           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14995                              DAG.getConstant(CC, MVT::i8), Cond);
14996           // Zero extend the condition if needed.
14997           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14998                              Cond);
14999           // Scale the condition by the difference.
15000           if (Diff != 1)
15001             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15002                                DAG.getConstant(Diff, Cond.getValueType()));
15003
15004           // Add the base if non-zero.
15005           if (FalseC->getAPIntValue() != 0)
15006             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15007                                SDValue(FalseC, 0));
15008           if (N->getNumValues() == 2)  // Dead flag value?
15009             return DCI.CombineTo(N, Cond, SDValue());
15010           return Cond;
15011         }
15012       }
15013     }
15014   }
15015
15016   // Handle these cases:
15017   //   (select (x != c), e, c) -> select (x != c), e, x),
15018   //   (select (x == c), c, e) -> select (x == c), x, e)
15019   // where the c is an integer constant, and the "select" is the combination
15020   // of CMOV and CMP.
15021   //
15022   // The rationale for this change is that the conditional-move from a constant
15023   // needs two instructions, however, conditional-move from a register needs
15024   // only one instruction.
15025   //
15026   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15027   //  some instruction-combining opportunities. This opt needs to be
15028   //  postponed as late as possible.
15029   //
15030   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15031     // the DCI.xxxx conditions are provided to postpone the optimization as
15032     // late as possible.
15033
15034     ConstantSDNode *CmpAgainst = 0;
15035     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15036         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15037         dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15038
15039       if (CC == X86::COND_NE &&
15040           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15041         CC = X86::GetOppositeBranchCondition(CC);
15042         std::swap(TrueOp, FalseOp);
15043       }
15044
15045       if (CC == X86::COND_E &&
15046           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15047         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15048                           DAG.getConstant(CC, MVT::i8), Cond };
15049         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15050                            array_lengthof(Ops));
15051       }
15052     }
15053   }
15054
15055   return SDValue();
15056 }
15057
15058
15059 /// PerformMulCombine - Optimize a single multiply with constant into two
15060 /// in order to implement it with two cheaper instructions, e.g.
15061 /// LEA + SHL, LEA + LEA.
15062 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15063                                  TargetLowering::DAGCombinerInfo &DCI) {
15064   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15065     return SDValue();
15066
15067   EVT VT = N->getValueType(0);
15068   if (VT != MVT::i64)
15069     return SDValue();
15070
15071   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15072   if (!C)
15073     return SDValue();
15074   uint64_t MulAmt = C->getZExtValue();
15075   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15076     return SDValue();
15077
15078   uint64_t MulAmt1 = 0;
15079   uint64_t MulAmt2 = 0;
15080   if ((MulAmt % 9) == 0) {
15081     MulAmt1 = 9;
15082     MulAmt2 = MulAmt / 9;
15083   } else if ((MulAmt % 5) == 0) {
15084     MulAmt1 = 5;
15085     MulAmt2 = MulAmt / 5;
15086   } else if ((MulAmt % 3) == 0) {
15087     MulAmt1 = 3;
15088     MulAmt2 = MulAmt / 3;
15089   }
15090   if (MulAmt2 &&
15091       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15092     DebugLoc DL = N->getDebugLoc();
15093
15094     if (isPowerOf2_64(MulAmt2) &&
15095         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15096       // If second multiplifer is pow2, issue it first. We want the multiply by
15097       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15098       // is an add.
15099       std::swap(MulAmt1, MulAmt2);
15100
15101     SDValue NewMul;
15102     if (isPowerOf2_64(MulAmt1))
15103       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15104                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15105     else
15106       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15107                            DAG.getConstant(MulAmt1, VT));
15108
15109     if (isPowerOf2_64(MulAmt2))
15110       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15111                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15112     else
15113       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15114                            DAG.getConstant(MulAmt2, VT));
15115
15116     // Do not add new nodes to DAG combiner worklist.
15117     DCI.CombineTo(N, NewMul, false);
15118   }
15119   return SDValue();
15120 }
15121
15122 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15123   SDValue N0 = N->getOperand(0);
15124   SDValue N1 = N->getOperand(1);
15125   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15126   EVT VT = N0.getValueType();
15127
15128   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15129   // since the result of setcc_c is all zero's or all ones.
15130   if (VT.isInteger() && !VT.isVector() &&
15131       N1C && N0.getOpcode() == ISD::AND &&
15132       N0.getOperand(1).getOpcode() == ISD::Constant) {
15133     SDValue N00 = N0.getOperand(0);
15134     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15135         ((N00.getOpcode() == ISD::ANY_EXTEND ||
15136           N00.getOpcode() == ISD::ZERO_EXTEND) &&
15137          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15138       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15139       APInt ShAmt = N1C->getAPIntValue();
15140       Mask = Mask.shl(ShAmt);
15141       if (Mask != 0)
15142         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15143                            N00, DAG.getConstant(Mask, VT));
15144     }
15145   }
15146
15147
15148   // Hardware support for vector shifts is sparse which makes us scalarize the
15149   // vector operations in many cases. Also, on sandybridge ADD is faster than
15150   // shl.
15151   // (shl V, 1) -> add V,V
15152   if (isSplatVector(N1.getNode())) {
15153     assert(N0.getValueType().isVector() && "Invalid vector shift type");
15154     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15155     // We shift all of the values by one. In many cases we do not have
15156     // hardware support for this operation. This is better expressed as an ADD
15157     // of two values.
15158     if (N1C && (1 == N1C->getZExtValue())) {
15159       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15160     }
15161   }
15162
15163   return SDValue();
15164 }
15165
15166 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15167 ///                       when possible.
15168 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15169                                    TargetLowering::DAGCombinerInfo &DCI,
15170                                    const X86Subtarget *Subtarget) {
15171   EVT VT = N->getValueType(0);
15172   if (N->getOpcode() == ISD::SHL) {
15173     SDValue V = PerformSHLCombine(N, DAG);
15174     if (V.getNode()) return V;
15175   }
15176
15177   // On X86 with SSE2 support, we can transform this to a vector shift if
15178   // all elements are shifted by the same amount.  We can't do this in legalize
15179   // because the a constant vector is typically transformed to a constant pool
15180   // so we have no knowledge of the shift amount.
15181   if (!Subtarget->hasSSE2())
15182     return SDValue();
15183
15184   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15185       (!Subtarget->hasAVX2() ||
15186        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15187     return SDValue();
15188
15189   SDValue ShAmtOp = N->getOperand(1);
15190   EVT EltVT = VT.getVectorElementType();
15191   DebugLoc DL = N->getDebugLoc();
15192   SDValue BaseShAmt = SDValue();
15193   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15194     unsigned NumElts = VT.getVectorNumElements();
15195     unsigned i = 0;
15196     for (; i != NumElts; ++i) {
15197       SDValue Arg = ShAmtOp.getOperand(i);
15198       if (Arg.getOpcode() == ISD::UNDEF) continue;
15199       BaseShAmt = Arg;
15200       break;
15201     }
15202     // Handle the case where the build_vector is all undef
15203     // FIXME: Should DAG allow this?
15204     if (i == NumElts)
15205       return SDValue();
15206
15207     for (; i != NumElts; ++i) {
15208       SDValue Arg = ShAmtOp.getOperand(i);
15209       if (Arg.getOpcode() == ISD::UNDEF) continue;
15210       if (Arg != BaseShAmt) {
15211         return SDValue();
15212       }
15213     }
15214   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15215              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15216     SDValue InVec = ShAmtOp.getOperand(0);
15217     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15218       unsigned NumElts = InVec.getValueType().getVectorNumElements();
15219       unsigned i = 0;
15220       for (; i != NumElts; ++i) {
15221         SDValue Arg = InVec.getOperand(i);
15222         if (Arg.getOpcode() == ISD::UNDEF) continue;
15223         BaseShAmt = Arg;
15224         break;
15225       }
15226     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15227        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15228          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15229          if (C->getZExtValue() == SplatIdx)
15230            BaseShAmt = InVec.getOperand(1);
15231        }
15232     }
15233     if (BaseShAmt.getNode() == 0) {
15234       // Don't create instructions with illegal types after legalize
15235       // types has run.
15236       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15237           !DCI.isBeforeLegalize())
15238         return SDValue();
15239
15240       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15241                               DAG.getIntPtrConstant(0));
15242     }
15243   } else
15244     return SDValue();
15245
15246   // The shift amount is an i32.
15247   if (EltVT.bitsGT(MVT::i32))
15248     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15249   else if (EltVT.bitsLT(MVT::i32))
15250     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15251
15252   // The shift amount is identical so we can do a vector shift.
15253   SDValue  ValOp = N->getOperand(0);
15254   switch (N->getOpcode()) {
15255   default:
15256     llvm_unreachable("Unknown shift opcode!");
15257   case ISD::SHL:
15258     switch (VT.getSimpleVT().SimpleTy) {
15259     default: return SDValue();
15260     case MVT::v2i64:
15261     case MVT::v4i32:
15262     case MVT::v8i16:
15263     case MVT::v4i64:
15264     case MVT::v8i32:
15265     case MVT::v16i16:
15266       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15267     }
15268   case ISD::SRA:
15269     switch (VT.getSimpleVT().SimpleTy) {
15270     default: return SDValue();
15271     case MVT::v4i32:
15272     case MVT::v8i16:
15273     case MVT::v8i32:
15274     case MVT::v16i16:
15275       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15276     }
15277   case ISD::SRL:
15278     switch (VT.getSimpleVT().SimpleTy) {
15279     default: return SDValue();
15280     case MVT::v2i64:
15281     case MVT::v4i32:
15282     case MVT::v8i16:
15283     case MVT::v4i64:
15284     case MVT::v8i32:
15285     case MVT::v16i16:
15286       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15287     }
15288   }
15289 }
15290
15291
15292 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15293 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15294 // and friends.  Likewise for OR -> CMPNEQSS.
15295 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15296                             TargetLowering::DAGCombinerInfo &DCI,
15297                             const X86Subtarget *Subtarget) {
15298   unsigned opcode;
15299
15300   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15301   // we're requiring SSE2 for both.
15302   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15303     SDValue N0 = N->getOperand(0);
15304     SDValue N1 = N->getOperand(1);
15305     SDValue CMP0 = N0->getOperand(1);
15306     SDValue CMP1 = N1->getOperand(1);
15307     DebugLoc DL = N->getDebugLoc();
15308
15309     // The SETCCs should both refer to the same CMP.
15310     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15311       return SDValue();
15312
15313     SDValue CMP00 = CMP0->getOperand(0);
15314     SDValue CMP01 = CMP0->getOperand(1);
15315     EVT     VT    = CMP00.getValueType();
15316
15317     if (VT == MVT::f32 || VT == MVT::f64) {
15318       bool ExpectingFlags = false;
15319       // Check for any users that want flags:
15320       for (SDNode::use_iterator UI = N->use_begin(),
15321              UE = N->use_end();
15322            !ExpectingFlags && UI != UE; ++UI)
15323         switch (UI->getOpcode()) {
15324         default:
15325         case ISD::BR_CC:
15326         case ISD::BRCOND:
15327         case ISD::SELECT:
15328           ExpectingFlags = true;
15329           break;
15330         case ISD::CopyToReg:
15331         case ISD::SIGN_EXTEND:
15332         case ISD::ZERO_EXTEND:
15333         case ISD::ANY_EXTEND:
15334           break;
15335         }
15336
15337       if (!ExpectingFlags) {
15338         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15339         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15340
15341         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15342           X86::CondCode tmp = cc0;
15343           cc0 = cc1;
15344           cc1 = tmp;
15345         }
15346
15347         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15348             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15349           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15350           X86ISD::NodeType NTOperator = is64BitFP ?
15351             X86ISD::FSETCCsd : X86ISD::FSETCCss;
15352           // FIXME: need symbolic constants for these magic numbers.
15353           // See X86ATTInstPrinter.cpp:printSSECC().
15354           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15355           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15356                                               DAG.getConstant(x86cc, MVT::i8));
15357           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15358                                               OnesOrZeroesF);
15359           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15360                                       DAG.getConstant(1, MVT::i32));
15361           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15362           return OneBitOfTruth;
15363         }
15364       }
15365     }
15366   }
15367   return SDValue();
15368 }
15369
15370 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15371 /// so it can be folded inside ANDNP.
15372 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15373   EVT VT = N->getValueType(0);
15374
15375   // Match direct AllOnes for 128 and 256-bit vectors
15376   if (ISD::isBuildVectorAllOnes(N))
15377     return true;
15378
15379   // Look through a bit convert.
15380   if (N->getOpcode() == ISD::BITCAST)
15381     N = N->getOperand(0).getNode();
15382
15383   // Sometimes the operand may come from a insert_subvector building a 256-bit
15384   // allones vector
15385   if (VT.is256BitVector() &&
15386       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15387     SDValue V1 = N->getOperand(0);
15388     SDValue V2 = N->getOperand(1);
15389
15390     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15391         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15392         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15393         ISD::isBuildVectorAllOnes(V2.getNode()))
15394       return true;
15395   }
15396
15397   return false;
15398 }
15399
15400 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15401                                  TargetLowering::DAGCombinerInfo &DCI,
15402                                  const X86Subtarget *Subtarget) {
15403   if (DCI.isBeforeLegalizeOps())
15404     return SDValue();
15405
15406   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15407   if (R.getNode())
15408     return R;
15409
15410   EVT VT = N->getValueType(0);
15411
15412   // Create ANDN, BLSI, and BLSR instructions
15413   // BLSI is X & (-X)
15414   // BLSR is X & (X-1)
15415   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15416     SDValue N0 = N->getOperand(0);
15417     SDValue N1 = N->getOperand(1);
15418     DebugLoc DL = N->getDebugLoc();
15419
15420     // Check LHS for not
15421     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
15422       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
15423     // Check RHS for not
15424     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
15425       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
15426
15427     // Check LHS for neg
15428     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15429         isZero(N0.getOperand(0)))
15430       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15431
15432     // Check RHS for neg
15433     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15434         isZero(N1.getOperand(0)))
15435       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15436
15437     // Check LHS for X-1
15438     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15439         isAllOnes(N0.getOperand(1)))
15440       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15441
15442     // Check RHS for X-1
15443     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15444         isAllOnes(N1.getOperand(1)))
15445       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15446
15447     return SDValue();
15448   }
15449
15450   // Want to form ANDNP nodes:
15451   // 1) In the hopes of then easily combining them with OR and AND nodes
15452   //    to form PBLEND/PSIGN.
15453   // 2) To match ANDN packed intrinsics
15454   if (VT != MVT::v2i64 && VT != MVT::v4i64)
15455     return SDValue();
15456
15457   SDValue N0 = N->getOperand(0);
15458   SDValue N1 = N->getOperand(1);
15459   DebugLoc DL = N->getDebugLoc();
15460
15461   // Check LHS for vnot
15462   if (N0.getOpcode() == ISD::XOR &&
15463       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15464       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15465     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15466
15467   // Check RHS for vnot
15468   if (N1.getOpcode() == ISD::XOR &&
15469       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15470       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15471     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15472
15473   return SDValue();
15474 }
15475
15476 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15477                                 TargetLowering::DAGCombinerInfo &DCI,
15478                                 const X86Subtarget *Subtarget) {
15479   if (DCI.isBeforeLegalizeOps())
15480     return SDValue();
15481
15482   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15483   if (R.getNode())
15484     return R;
15485
15486   EVT VT = N->getValueType(0);
15487
15488   SDValue N0 = N->getOperand(0);
15489   SDValue N1 = N->getOperand(1);
15490
15491   // look for psign/blend
15492   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15493     if (!Subtarget->hasSSSE3() ||
15494         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15495       return SDValue();
15496
15497     // Canonicalize pandn to RHS
15498     if (N0.getOpcode() == X86ISD::ANDNP)
15499       std::swap(N0, N1);
15500     // or (and (m, y), (pandn m, x))
15501     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15502       SDValue Mask = N1.getOperand(0);
15503       SDValue X    = N1.getOperand(1);
15504       SDValue Y;
15505       if (N0.getOperand(0) == Mask)
15506         Y = N0.getOperand(1);
15507       if (N0.getOperand(1) == Mask)
15508         Y = N0.getOperand(0);
15509
15510       // Check to see if the mask appeared in both the AND and ANDNP and
15511       if (!Y.getNode())
15512         return SDValue();
15513
15514       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15515       // Look through mask bitcast.
15516       if (Mask.getOpcode() == ISD::BITCAST)
15517         Mask = Mask.getOperand(0);
15518       if (X.getOpcode() == ISD::BITCAST)
15519         X = X.getOperand(0);
15520       if (Y.getOpcode() == ISD::BITCAST)
15521         Y = Y.getOperand(0);
15522
15523       EVT MaskVT = Mask.getValueType();
15524
15525       // Validate that the Mask operand is a vector sra node.
15526       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15527       // there is no psrai.b
15528       if (Mask.getOpcode() != X86ISD::VSRAI)
15529         return SDValue();
15530
15531       // Check that the SRA is all signbits.
15532       SDValue SraC = Mask.getOperand(1);
15533       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
15534       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15535       if ((SraAmt + 1) != EltBits)
15536         return SDValue();
15537
15538       DebugLoc DL = N->getDebugLoc();
15539
15540       // Now we know we at least have a plendvb with the mask val.  See if
15541       // we can form a psignb/w/d.
15542       // psign = x.type == y.type == mask.type && y = sub(0, x);
15543       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15544           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15545           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15546         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15547                "Unsupported VT for PSIGN");
15548         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15549         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15550       }
15551       // PBLENDVB only available on SSE 4.1
15552       if (!Subtarget->hasSSE41())
15553         return SDValue();
15554
15555       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15556
15557       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15558       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15559       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15560       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15561       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15562     }
15563   }
15564
15565   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15566     return SDValue();
15567
15568   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15569   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15570     std::swap(N0, N1);
15571   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15572     return SDValue();
15573   if (!N0.hasOneUse() || !N1.hasOneUse())
15574     return SDValue();
15575
15576   SDValue ShAmt0 = N0.getOperand(1);
15577   if (ShAmt0.getValueType() != MVT::i8)
15578     return SDValue();
15579   SDValue ShAmt1 = N1.getOperand(1);
15580   if (ShAmt1.getValueType() != MVT::i8)
15581     return SDValue();
15582   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15583     ShAmt0 = ShAmt0.getOperand(0);
15584   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15585     ShAmt1 = ShAmt1.getOperand(0);
15586
15587   DebugLoc DL = N->getDebugLoc();
15588   unsigned Opc = X86ISD::SHLD;
15589   SDValue Op0 = N0.getOperand(0);
15590   SDValue Op1 = N1.getOperand(0);
15591   if (ShAmt0.getOpcode() == ISD::SUB) {
15592     Opc = X86ISD::SHRD;
15593     std::swap(Op0, Op1);
15594     std::swap(ShAmt0, ShAmt1);
15595   }
15596
15597   unsigned Bits = VT.getSizeInBits();
15598   if (ShAmt1.getOpcode() == ISD::SUB) {
15599     SDValue Sum = ShAmt1.getOperand(0);
15600     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15601       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15602       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15603         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15604       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15605         return DAG.getNode(Opc, DL, VT,
15606                            Op0, Op1,
15607                            DAG.getNode(ISD::TRUNCATE, DL,
15608                                        MVT::i8, ShAmt0));
15609     }
15610   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15611     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15612     if (ShAmt0C &&
15613         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15614       return DAG.getNode(Opc, DL, VT,
15615                          N0.getOperand(0), N1.getOperand(0),
15616                          DAG.getNode(ISD::TRUNCATE, DL,
15617                                        MVT::i8, ShAmt0));
15618   }
15619
15620   return SDValue();
15621 }
15622
15623 // Generate NEG and CMOV for integer abs.
15624 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15625   EVT VT = N->getValueType(0);
15626
15627   // Since X86 does not have CMOV for 8-bit integer, we don't convert
15628   // 8-bit integer abs to NEG and CMOV.
15629   if (VT.isInteger() && VT.getSizeInBits() == 8)
15630     return SDValue();
15631
15632   SDValue N0 = N->getOperand(0);
15633   SDValue N1 = N->getOperand(1);
15634   DebugLoc DL = N->getDebugLoc();
15635
15636   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15637   // and change it to SUB and CMOV.
15638   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15639       N0.getOpcode() == ISD::ADD &&
15640       N0.getOperand(1) == N1 &&
15641       N1.getOpcode() == ISD::SRA &&
15642       N1.getOperand(0) == N0.getOperand(0))
15643     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15644       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15645         // Generate SUB & CMOV.
15646         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15647                                   DAG.getConstant(0, VT), N0.getOperand(0));
15648
15649         SDValue Ops[] = { N0.getOperand(0), Neg,
15650                           DAG.getConstant(X86::COND_GE, MVT::i8),
15651                           SDValue(Neg.getNode(), 1) };
15652         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15653                            Ops, array_lengthof(Ops));
15654       }
15655   return SDValue();
15656 }
15657
15658 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15659 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15660                                  TargetLowering::DAGCombinerInfo &DCI,
15661                                  const X86Subtarget *Subtarget) {
15662   if (DCI.isBeforeLegalizeOps())
15663     return SDValue();
15664
15665   if (Subtarget->hasCMov()) {
15666     SDValue RV = performIntegerAbsCombine(N, DAG);
15667     if (RV.getNode())
15668       return RV;
15669   }
15670
15671   // Try forming BMI if it is available.
15672   if (!Subtarget->hasBMI())
15673     return SDValue();
15674
15675   EVT VT = N->getValueType(0);
15676
15677   if (VT != MVT::i32 && VT != MVT::i64)
15678     return SDValue();
15679
15680   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15681
15682   // Create BLSMSK instructions by finding X ^ (X-1)
15683   SDValue N0 = N->getOperand(0);
15684   SDValue N1 = N->getOperand(1);
15685   DebugLoc DL = N->getDebugLoc();
15686
15687   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15688       isAllOnes(N0.getOperand(1)))
15689     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15690
15691   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15692       isAllOnes(N1.getOperand(1)))
15693     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15694
15695   return SDValue();
15696 }
15697
15698 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15699 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15700                                   TargetLowering::DAGCombinerInfo &DCI,
15701                                   const X86Subtarget *Subtarget) {
15702   LoadSDNode *Ld = cast<LoadSDNode>(N);
15703   EVT RegVT = Ld->getValueType(0);
15704   EVT MemVT = Ld->getMemoryVT();
15705   DebugLoc dl = Ld->getDebugLoc();
15706   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15707
15708   ISD::LoadExtType Ext = Ld->getExtensionType();
15709
15710   // If this is a vector EXT Load then attempt to optimize it using a
15711   // shuffle. We need SSSE3 shuffles.
15712   // TODO: It is possible to support ZExt by zeroing the undef values
15713   // during the shuffle phase or after the shuffle.
15714   if (RegVT.isVector() && RegVT.isInteger() &&
15715       Ext == ISD::EXTLOAD && Subtarget->hasSSSE3()) {
15716     assert(MemVT != RegVT && "Cannot extend to the same type");
15717     assert(MemVT.isVector() && "Must load a vector from memory");
15718
15719     unsigned NumElems = RegVT.getVectorNumElements();
15720     unsigned RegSz = RegVT.getSizeInBits();
15721     unsigned MemSz = MemVT.getSizeInBits();
15722     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15723
15724     // All sizes must be a power of two.
15725     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15726       return SDValue();
15727
15728     // Attempt to load the original value using scalar loads.
15729     // Find the largest scalar type that divides the total loaded size.
15730     MVT SclrLoadTy = MVT::i8;
15731     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15732          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15733       MVT Tp = (MVT::SimpleValueType)tp;
15734       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15735         SclrLoadTy = Tp;
15736       }
15737     }
15738
15739     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15740     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15741         (64 <= MemSz))
15742       SclrLoadTy = MVT::f64;
15743
15744     // Calculate the number of scalar loads that we need to perform
15745     // in order to load our vector from memory.
15746     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15747
15748     // Represent our vector as a sequence of elements which are the
15749     // largest scalar that we can load.
15750     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15751       RegSz/SclrLoadTy.getSizeInBits());
15752
15753     // Represent the data using the same element type that is stored in
15754     // memory. In practice, we ''widen'' MemVT.
15755     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15756                                   RegSz/MemVT.getScalarType().getSizeInBits());
15757
15758     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15759       "Invalid vector type");
15760
15761     // We can't shuffle using an illegal type.
15762     if (!TLI.isTypeLegal(WideVecVT))
15763       return SDValue();
15764
15765     SmallVector<SDValue, 8> Chains;
15766     SDValue Ptr = Ld->getBasePtr();
15767     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15768                                         TLI.getPointerTy());
15769     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15770
15771     for (unsigned i = 0; i < NumLoads; ++i) {
15772       // Perform a single load.
15773       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15774                                        Ptr, Ld->getPointerInfo(),
15775                                        Ld->isVolatile(), Ld->isNonTemporal(),
15776                                        Ld->isInvariant(), Ld->getAlignment());
15777       Chains.push_back(ScalarLoad.getValue(1));
15778       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15779       // another round of DAGCombining.
15780       if (i == 0)
15781         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15782       else
15783         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15784                           ScalarLoad, DAG.getIntPtrConstant(i));
15785
15786       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15787     }
15788
15789     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15790                                Chains.size());
15791
15792     // Bitcast the loaded value to a vector of the original element type, in
15793     // the size of the target vector type.
15794     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15795     unsigned SizeRatio = RegSz/MemSz;
15796
15797     // Redistribute the loaded elements into the different locations.
15798     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15799     for (unsigned i = 0; i != NumElems; ++i)
15800       ShuffleVec[i*SizeRatio] = i;
15801
15802     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15803                                          DAG.getUNDEF(WideVecVT),
15804                                          &ShuffleVec[0]);
15805
15806     // Bitcast to the requested type.
15807     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15808     // Replace the original load with the new sequence
15809     // and return the new chain.
15810     return DCI.CombineTo(N, Shuff, TF, true);
15811   }
15812
15813   return SDValue();
15814 }
15815
15816 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15817 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15818                                    const X86Subtarget *Subtarget) {
15819   StoreSDNode *St = cast<StoreSDNode>(N);
15820   EVT VT = St->getValue().getValueType();
15821   EVT StVT = St->getMemoryVT();
15822   DebugLoc dl = St->getDebugLoc();
15823   SDValue StoredVal = St->getOperand(1);
15824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15825
15826   // If we are saving a concatenation of two XMM registers, perform two stores.
15827   // On Sandy Bridge, 256-bit memory operations are executed by two
15828   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15829   // memory  operation.
15830   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15831       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15832       StoredVal.getNumOperands() == 2) {
15833     SDValue Value0 = StoredVal.getOperand(0);
15834     SDValue Value1 = StoredVal.getOperand(1);
15835
15836     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15837     SDValue Ptr0 = St->getBasePtr();
15838     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15839
15840     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15841                                 St->getPointerInfo(), St->isVolatile(),
15842                                 St->isNonTemporal(), St->getAlignment());
15843     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15844                                 St->getPointerInfo(), St->isVolatile(),
15845                                 St->isNonTemporal(), St->getAlignment());
15846     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15847   }
15848
15849   // Optimize trunc store (of multiple scalars) to shuffle and store.
15850   // First, pack all of the elements in one place. Next, store to memory
15851   // in fewer chunks.
15852   if (St->isTruncatingStore() && VT.isVector()) {
15853     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15854     unsigned NumElems = VT.getVectorNumElements();
15855     assert(StVT != VT && "Cannot truncate to the same type");
15856     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15857     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15858
15859     // From, To sizes and ElemCount must be pow of two
15860     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15861     // We are going to use the original vector elt for storing.
15862     // Accumulated smaller vector elements must be a multiple of the store size.
15863     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15864
15865     unsigned SizeRatio  = FromSz / ToSz;
15866
15867     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15868
15869     // Create a type on which we perform the shuffle
15870     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15871             StVT.getScalarType(), NumElems*SizeRatio);
15872
15873     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15874
15875     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15876     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15877     for (unsigned i = 0; i != NumElems; ++i)
15878       ShuffleVec[i] = i * SizeRatio;
15879
15880     // Can't shuffle using an illegal type.
15881     if (!TLI.isTypeLegal(WideVecVT))
15882       return SDValue();
15883
15884     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15885                                          DAG.getUNDEF(WideVecVT),
15886                                          &ShuffleVec[0]);
15887     // At this point all of the data is stored at the bottom of the
15888     // register. We now need to save it to mem.
15889
15890     // Find the largest store unit
15891     MVT StoreType = MVT::i8;
15892     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15893          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15894       MVT Tp = (MVT::SimpleValueType)tp;
15895       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15896         StoreType = Tp;
15897     }
15898
15899     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15900     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15901         (64 <= NumElems * ToSz))
15902       StoreType = MVT::f64;
15903
15904     // Bitcast the original vector into a vector of store-size units
15905     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15906             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15907     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15908     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15909     SmallVector<SDValue, 8> Chains;
15910     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15911                                         TLI.getPointerTy());
15912     SDValue Ptr = St->getBasePtr();
15913
15914     // Perform one or more big stores into memory.
15915     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15916       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15917                                    StoreType, ShuffWide,
15918                                    DAG.getIntPtrConstant(i));
15919       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15920                                 St->getPointerInfo(), St->isVolatile(),
15921                                 St->isNonTemporal(), St->getAlignment());
15922       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15923       Chains.push_back(Ch);
15924     }
15925
15926     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15927                                Chains.size());
15928   }
15929
15930
15931   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15932   // the FP state in cases where an emms may be missing.
15933   // A preferable solution to the general problem is to figure out the right
15934   // places to insert EMMS.  This qualifies as a quick hack.
15935
15936   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15937   if (VT.getSizeInBits() != 64)
15938     return SDValue();
15939
15940   const Function *F = DAG.getMachineFunction().getFunction();
15941   bool NoImplicitFloatOps = F->getFnAttributes().
15942     hasAttribute(Attributes::NoImplicitFloat);
15943   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15944                      && Subtarget->hasSSE2();
15945   if ((VT.isVector() ||
15946        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15947       isa<LoadSDNode>(St->getValue()) &&
15948       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15949       St->getChain().hasOneUse() && !St->isVolatile()) {
15950     SDNode* LdVal = St->getValue().getNode();
15951     LoadSDNode *Ld = 0;
15952     int TokenFactorIndex = -1;
15953     SmallVector<SDValue, 8> Ops;
15954     SDNode* ChainVal = St->getChain().getNode();
15955     // Must be a store of a load.  We currently handle two cases:  the load
15956     // is a direct child, and it's under an intervening TokenFactor.  It is
15957     // possible to dig deeper under nested TokenFactors.
15958     if (ChainVal == LdVal)
15959       Ld = cast<LoadSDNode>(St->getChain());
15960     else if (St->getValue().hasOneUse() &&
15961              ChainVal->getOpcode() == ISD::TokenFactor) {
15962       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15963         if (ChainVal->getOperand(i).getNode() == LdVal) {
15964           TokenFactorIndex = i;
15965           Ld = cast<LoadSDNode>(St->getValue());
15966         } else
15967           Ops.push_back(ChainVal->getOperand(i));
15968       }
15969     }
15970
15971     if (!Ld || !ISD::isNormalLoad(Ld))
15972       return SDValue();
15973
15974     // If this is not the MMX case, i.e. we are just turning i64 load/store
15975     // into f64 load/store, avoid the transformation if there are multiple
15976     // uses of the loaded value.
15977     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15978       return SDValue();
15979
15980     DebugLoc LdDL = Ld->getDebugLoc();
15981     DebugLoc StDL = N->getDebugLoc();
15982     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15983     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15984     // pair instead.
15985     if (Subtarget->is64Bit() || F64IsLegal) {
15986       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15987       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15988                                   Ld->getPointerInfo(), Ld->isVolatile(),
15989                                   Ld->isNonTemporal(), Ld->isInvariant(),
15990                                   Ld->getAlignment());
15991       SDValue NewChain = NewLd.getValue(1);
15992       if (TokenFactorIndex != -1) {
15993         Ops.push_back(NewChain);
15994         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15995                                Ops.size());
15996       }
15997       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15998                           St->getPointerInfo(),
15999                           St->isVolatile(), St->isNonTemporal(),
16000                           St->getAlignment());
16001     }
16002
16003     // Otherwise, lower to two pairs of 32-bit loads / stores.
16004     SDValue LoAddr = Ld->getBasePtr();
16005     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16006                                  DAG.getConstant(4, MVT::i32));
16007
16008     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16009                                Ld->getPointerInfo(),
16010                                Ld->isVolatile(), Ld->isNonTemporal(),
16011                                Ld->isInvariant(), Ld->getAlignment());
16012     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16013                                Ld->getPointerInfo().getWithOffset(4),
16014                                Ld->isVolatile(), Ld->isNonTemporal(),
16015                                Ld->isInvariant(),
16016                                MinAlign(Ld->getAlignment(), 4));
16017
16018     SDValue NewChain = LoLd.getValue(1);
16019     if (TokenFactorIndex != -1) {
16020       Ops.push_back(LoLd);
16021       Ops.push_back(HiLd);
16022       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16023                              Ops.size());
16024     }
16025
16026     LoAddr = St->getBasePtr();
16027     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16028                          DAG.getConstant(4, MVT::i32));
16029
16030     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16031                                 St->getPointerInfo(),
16032                                 St->isVolatile(), St->isNonTemporal(),
16033                                 St->getAlignment());
16034     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16035                                 St->getPointerInfo().getWithOffset(4),
16036                                 St->isVolatile(),
16037                                 St->isNonTemporal(),
16038                                 MinAlign(St->getAlignment(), 4));
16039     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16040   }
16041   return SDValue();
16042 }
16043
16044 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16045 /// and return the operands for the horizontal operation in LHS and RHS.  A
16046 /// horizontal operation performs the binary operation on successive elements
16047 /// of its first operand, then on successive elements of its second operand,
16048 /// returning the resulting values in a vector.  For example, if
16049 ///   A = < float a0, float a1, float a2, float a3 >
16050 /// and
16051 ///   B = < float b0, float b1, float b2, float b3 >
16052 /// then the result of doing a horizontal operation on A and B is
16053 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16054 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16055 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16056 /// set to A, RHS to B, and the routine returns 'true'.
16057 /// Note that the binary operation should have the property that if one of the
16058 /// operands is UNDEF then the result is UNDEF.
16059 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16060   // Look for the following pattern: if
16061   //   A = < float a0, float a1, float a2, float a3 >
16062   //   B = < float b0, float b1, float b2, float b3 >
16063   // and
16064   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16065   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16066   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16067   // which is A horizontal-op B.
16068
16069   // At least one of the operands should be a vector shuffle.
16070   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16071       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16072     return false;
16073
16074   EVT VT = LHS.getValueType();
16075
16076   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16077          "Unsupported vector type for horizontal add/sub");
16078
16079   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16080   // operate independently on 128-bit lanes.
16081   unsigned NumElts = VT.getVectorNumElements();
16082   unsigned NumLanes = VT.getSizeInBits()/128;
16083   unsigned NumLaneElts = NumElts / NumLanes;
16084   assert((NumLaneElts % 2 == 0) &&
16085          "Vector type should have an even number of elements in each lane");
16086   unsigned HalfLaneElts = NumLaneElts/2;
16087
16088   // View LHS in the form
16089   //   LHS = VECTOR_SHUFFLE A, B, LMask
16090   // If LHS is not a shuffle then pretend it is the shuffle
16091   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16092   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16093   // type VT.
16094   SDValue A, B;
16095   SmallVector<int, 16> LMask(NumElts);
16096   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16097     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16098       A = LHS.getOperand(0);
16099     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16100       B = LHS.getOperand(1);
16101     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16102     std::copy(Mask.begin(), Mask.end(), LMask.begin());
16103   } else {
16104     if (LHS.getOpcode() != ISD::UNDEF)
16105       A = LHS;
16106     for (unsigned i = 0; i != NumElts; ++i)
16107       LMask[i] = i;
16108   }
16109
16110   // Likewise, view RHS in the form
16111   //   RHS = VECTOR_SHUFFLE C, D, RMask
16112   SDValue C, D;
16113   SmallVector<int, 16> RMask(NumElts);
16114   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16115     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16116       C = RHS.getOperand(0);
16117     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16118       D = RHS.getOperand(1);
16119     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16120     std::copy(Mask.begin(), Mask.end(), RMask.begin());
16121   } else {
16122     if (RHS.getOpcode() != ISD::UNDEF)
16123       C = RHS;
16124     for (unsigned i = 0; i != NumElts; ++i)
16125       RMask[i] = i;
16126   }
16127
16128   // Check that the shuffles are both shuffling the same vectors.
16129   if (!(A == C && B == D) && !(A == D && B == C))
16130     return false;
16131
16132   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16133   if (!A.getNode() && !B.getNode())
16134     return false;
16135
16136   // If A and B occur in reverse order in RHS, then "swap" them (which means
16137   // rewriting the mask).
16138   if (A != C)
16139     CommuteVectorShuffleMask(RMask, NumElts);
16140
16141   // At this point LHS and RHS are equivalent to
16142   //   LHS = VECTOR_SHUFFLE A, B, LMask
16143   //   RHS = VECTOR_SHUFFLE A, B, RMask
16144   // Check that the masks correspond to performing a horizontal operation.
16145   for (unsigned i = 0; i != NumElts; ++i) {
16146     int LIdx = LMask[i], RIdx = RMask[i];
16147
16148     // Ignore any UNDEF components.
16149     if (LIdx < 0 || RIdx < 0 ||
16150         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16151         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16152       continue;
16153
16154     // Check that successive elements are being operated on.  If not, this is
16155     // not a horizontal operation.
16156     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16157     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16158     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16159     if (!(LIdx == Index && RIdx == Index + 1) &&
16160         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16161       return false;
16162   }
16163
16164   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16165   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16166   return true;
16167 }
16168
16169 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16170 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16171                                   const X86Subtarget *Subtarget) {
16172   EVT VT = N->getValueType(0);
16173   SDValue LHS = N->getOperand(0);
16174   SDValue RHS = N->getOperand(1);
16175
16176   // Try to synthesize horizontal adds from adds of shuffles.
16177   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16178        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16179       isHorizontalBinOp(LHS, RHS, true))
16180     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16181   return SDValue();
16182 }
16183
16184 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16185 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16186                                   const X86Subtarget *Subtarget) {
16187   EVT VT = N->getValueType(0);
16188   SDValue LHS = N->getOperand(0);
16189   SDValue RHS = N->getOperand(1);
16190
16191   // Try to synthesize horizontal subs from subs of shuffles.
16192   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16193        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16194       isHorizontalBinOp(LHS, RHS, false))
16195     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16196   return SDValue();
16197 }
16198
16199 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16200 /// X86ISD::FXOR nodes.
16201 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16202   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16203   // F[X]OR(0.0, x) -> x
16204   // F[X]OR(x, 0.0) -> x
16205   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16206     if (C->getValueAPF().isPosZero())
16207       return N->getOperand(1);
16208   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16209     if (C->getValueAPF().isPosZero())
16210       return N->getOperand(0);
16211   return SDValue();
16212 }
16213
16214 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16215 /// X86ISD::FMAX nodes.
16216 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16217   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16218
16219   // Only perform optimizations if UnsafeMath is used.
16220   if (!DAG.getTarget().Options.UnsafeFPMath)
16221     return SDValue();
16222
16223   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16224   // into FMINC and FMAXC, which are Commutative operations.
16225   unsigned NewOp = 0;
16226   switch (N->getOpcode()) {
16227     default: llvm_unreachable("unknown opcode");
16228     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
16229     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
16230   }
16231
16232   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16233                      N->getOperand(0), N->getOperand(1));
16234 }
16235
16236
16237 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16238 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16239   // FAND(0.0, x) -> 0.0
16240   // FAND(x, 0.0) -> 0.0
16241   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16242     if (C->getValueAPF().isPosZero())
16243       return N->getOperand(0);
16244   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16245     if (C->getValueAPF().isPosZero())
16246       return N->getOperand(1);
16247   return SDValue();
16248 }
16249
16250 static SDValue PerformBTCombine(SDNode *N,
16251                                 SelectionDAG &DAG,
16252                                 TargetLowering::DAGCombinerInfo &DCI) {
16253   // BT ignores high bits in the bit index operand.
16254   SDValue Op1 = N->getOperand(1);
16255   if (Op1.hasOneUse()) {
16256     unsigned BitWidth = Op1.getValueSizeInBits();
16257     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16258     APInt KnownZero, KnownOne;
16259     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16260                                           !DCI.isBeforeLegalizeOps());
16261     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16262     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16263         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16264       DCI.CommitTargetLoweringOpt(TLO);
16265   }
16266   return SDValue();
16267 }
16268
16269 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16270   SDValue Op = N->getOperand(0);
16271   if (Op.getOpcode() == ISD::BITCAST)
16272     Op = Op.getOperand(0);
16273   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16274   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16275       VT.getVectorElementType().getSizeInBits() ==
16276       OpVT.getVectorElementType().getSizeInBits()) {
16277     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16278   }
16279   return SDValue();
16280 }
16281
16282 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16283                                   TargetLowering::DAGCombinerInfo &DCI,
16284                                   const X86Subtarget *Subtarget) {
16285   if (!DCI.isBeforeLegalizeOps())
16286     return SDValue();
16287
16288   if (!Subtarget->hasAVX())
16289     return SDValue();
16290
16291   EVT VT = N->getValueType(0);
16292   SDValue Op = N->getOperand(0);
16293   EVT OpVT = Op.getValueType();
16294   DebugLoc dl = N->getDebugLoc();
16295
16296   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16297       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16298
16299     if (Subtarget->hasAVX2())
16300       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16301
16302     // Optimize vectors in AVX mode
16303     // Sign extend  v8i16 to v8i32 and
16304     //              v4i32 to v4i64
16305     //
16306     // Divide input vector into two parts
16307     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16308     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16309     // concat the vectors to original VT
16310
16311     unsigned NumElems = OpVT.getVectorNumElements();
16312     SDValue Undef = DAG.getUNDEF(OpVT);
16313
16314     SmallVector<int,8> ShufMask1(NumElems, -1);
16315     for (unsigned i = 0; i != NumElems/2; ++i)
16316       ShufMask1[i] = i;
16317
16318     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16319
16320     SmallVector<int,8> ShufMask2(NumElems, -1);
16321     for (unsigned i = 0; i != NumElems/2; ++i)
16322       ShufMask2[i] = i + NumElems/2;
16323
16324     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16325
16326     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16327                                   VT.getVectorNumElements()/2);
16328
16329     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16330     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16331
16332     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16333   }
16334   return SDValue();
16335 }
16336
16337 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16338                                  const X86Subtarget* Subtarget) {
16339   DebugLoc dl = N->getDebugLoc();
16340   EVT VT = N->getValueType(0);
16341
16342   // Let legalize expand this if it isn't a legal type yet.
16343   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16344     return SDValue();
16345
16346   EVT ScalarVT = VT.getScalarType();
16347   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16348       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16349     return SDValue();
16350
16351   SDValue A = N->getOperand(0);
16352   SDValue B = N->getOperand(1);
16353   SDValue C = N->getOperand(2);
16354
16355   bool NegA = (A.getOpcode() == ISD::FNEG);
16356   bool NegB = (B.getOpcode() == ISD::FNEG);
16357   bool NegC = (C.getOpcode() == ISD::FNEG);
16358
16359   // Negative multiplication when NegA xor NegB
16360   bool NegMul = (NegA != NegB);
16361   if (NegA)
16362     A = A.getOperand(0);
16363   if (NegB)
16364     B = B.getOperand(0);
16365   if (NegC)
16366     C = C.getOperand(0);
16367
16368   unsigned Opcode;
16369   if (!NegMul)
16370     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16371   else
16372     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16373
16374   return DAG.getNode(Opcode, dl, VT, A, B, C);
16375 }
16376
16377 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16378                                   TargetLowering::DAGCombinerInfo &DCI,
16379                                   const X86Subtarget *Subtarget) {
16380   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
16381   //           (and (i32 x86isd::setcc_carry), 1)
16382   // This eliminates the zext. This transformation is necessary because
16383   // ISD::SETCC is always legalized to i8.
16384   DebugLoc dl = N->getDebugLoc();
16385   SDValue N0 = N->getOperand(0);
16386   EVT VT = N->getValueType(0);
16387   EVT OpVT = N0.getValueType();
16388
16389   if (N0.getOpcode() == ISD::AND &&
16390       N0.hasOneUse() &&
16391       N0.getOperand(0).hasOneUse()) {
16392     SDValue N00 = N0.getOperand(0);
16393     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16394       return SDValue();
16395     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16396     if (!C || C->getZExtValue() != 1)
16397       return SDValue();
16398     return DAG.getNode(ISD::AND, dl, VT,
16399                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16400                                    N00.getOperand(0), N00.getOperand(1)),
16401                        DAG.getConstant(1, VT));
16402   }
16403
16404   // Optimize vectors in AVX mode:
16405   //
16406   //   v8i16 -> v8i32
16407   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
16408   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
16409   //   Concat upper and lower parts.
16410   //
16411   //   v4i32 -> v4i64
16412   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
16413   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
16414   //   Concat upper and lower parts.
16415   //
16416   if (!DCI.isBeforeLegalizeOps())
16417     return SDValue();
16418
16419   if (!Subtarget->hasAVX())
16420     return SDValue();
16421
16422   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16423       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
16424
16425     if (Subtarget->hasAVX2())
16426       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16427
16428     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16429     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16430     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16431
16432     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16433                                VT.getVectorNumElements()/2);
16434
16435     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16436     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16437
16438     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16439   }
16440
16441   return SDValue();
16442 }
16443
16444 // Optimize x == -y --> x+y == 0
16445 //          x != -y --> x+y != 0
16446 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16447   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16448   SDValue LHS = N->getOperand(0);
16449   SDValue RHS = N->getOperand(1);
16450
16451   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16452     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16453       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16454         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16455                                    LHS.getValueType(), RHS, LHS.getOperand(1));
16456         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16457                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16458       }
16459   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16460     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16461       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16462         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16463                                    RHS.getValueType(), LHS, RHS.getOperand(1));
16464         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16465                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16466       }
16467   return SDValue();
16468 }
16469
16470 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16471 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16472                                    TargetLowering::DAGCombinerInfo &DCI,
16473                                    const X86Subtarget *Subtarget) {
16474   DebugLoc DL = N->getDebugLoc();
16475   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16476   SDValue EFLAGS = N->getOperand(1);
16477
16478   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16479   // a zext and produces an all-ones bit which is more useful than 0/1 in some
16480   // cases.
16481   if (CC == X86::COND_B)
16482     return DAG.getNode(ISD::AND, DL, MVT::i8,
16483                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16484                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
16485                        DAG.getConstant(1, MVT::i8));
16486
16487   SDValue Flags;
16488
16489   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16490   if (Flags.getNode()) {
16491     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16492     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16493   }
16494
16495   return SDValue();
16496 }
16497
16498 // Optimize branch condition evaluation.
16499 //
16500 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16501                                     TargetLowering::DAGCombinerInfo &DCI,
16502                                     const X86Subtarget *Subtarget) {
16503   DebugLoc DL = N->getDebugLoc();
16504   SDValue Chain = N->getOperand(0);
16505   SDValue Dest = N->getOperand(1);
16506   SDValue EFLAGS = N->getOperand(3);
16507   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16508
16509   SDValue Flags;
16510
16511   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16512   if (Flags.getNode()) {
16513     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16514     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16515                        Flags);
16516   }
16517
16518   return SDValue();
16519 }
16520
16521 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16522                                         const X86TargetLowering *XTLI) {
16523   SDValue Op0 = N->getOperand(0);
16524   EVT InVT = Op0->getValueType(0);
16525
16526   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16527   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16528     DebugLoc dl = N->getDebugLoc();
16529     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16530     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16531     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16532   }
16533
16534   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16535   // a 32-bit target where SSE doesn't support i64->FP operations.
16536   if (Op0.getOpcode() == ISD::LOAD) {
16537     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16538     EVT VT = Ld->getValueType(0);
16539     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16540         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16541         !XTLI->getSubtarget()->is64Bit() &&
16542         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16543       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16544                                           Ld->getChain(), Op0, DAG);
16545       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16546       return FILDChain;
16547     }
16548   }
16549   return SDValue();
16550 }
16551
16552 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16553 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16554                                  X86TargetLowering::DAGCombinerInfo &DCI) {
16555   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16556   // the result is either zero or one (depending on the input carry bit).
16557   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16558   if (X86::isZeroNode(N->getOperand(0)) &&
16559       X86::isZeroNode(N->getOperand(1)) &&
16560       // We don't have a good way to replace an EFLAGS use, so only do this when
16561       // dead right now.
16562       SDValue(N, 1).use_empty()) {
16563     DebugLoc DL = N->getDebugLoc();
16564     EVT VT = N->getValueType(0);
16565     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16566     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16567                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16568                                            DAG.getConstant(X86::COND_B,MVT::i8),
16569                                            N->getOperand(2)),
16570                                DAG.getConstant(1, VT));
16571     return DCI.CombineTo(N, Res1, CarryOut);
16572   }
16573
16574   return SDValue();
16575 }
16576
16577 // fold (add Y, (sete  X, 0)) -> adc  0, Y
16578 //      (add Y, (setne X, 0)) -> sbb -1, Y
16579 //      (sub (sete  X, 0), Y) -> sbb  0, Y
16580 //      (sub (setne X, 0), Y) -> adc -1, Y
16581 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16582   DebugLoc DL = N->getDebugLoc();
16583
16584   // Look through ZExts.
16585   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16586   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16587     return SDValue();
16588
16589   SDValue SetCC = Ext.getOperand(0);
16590   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16591     return SDValue();
16592
16593   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16594   if (CC != X86::COND_E && CC != X86::COND_NE)
16595     return SDValue();
16596
16597   SDValue Cmp = SetCC.getOperand(1);
16598   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16599       !X86::isZeroNode(Cmp.getOperand(1)) ||
16600       !Cmp.getOperand(0).getValueType().isInteger())
16601     return SDValue();
16602
16603   SDValue CmpOp0 = Cmp.getOperand(0);
16604   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16605                                DAG.getConstant(1, CmpOp0.getValueType()));
16606
16607   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16608   if (CC == X86::COND_NE)
16609     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16610                        DL, OtherVal.getValueType(), OtherVal,
16611                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16612   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16613                      DL, OtherVal.getValueType(), OtherVal,
16614                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16615 }
16616
16617 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16618 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16619                                  const X86Subtarget *Subtarget) {
16620   EVT VT = N->getValueType(0);
16621   SDValue Op0 = N->getOperand(0);
16622   SDValue Op1 = N->getOperand(1);
16623
16624   // Try to synthesize horizontal adds from adds of shuffles.
16625   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16626        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16627       isHorizontalBinOp(Op0, Op1, true))
16628     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16629
16630   return OptimizeConditionalInDecrement(N, DAG);
16631 }
16632
16633 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16634                                  const X86Subtarget *Subtarget) {
16635   SDValue Op0 = N->getOperand(0);
16636   SDValue Op1 = N->getOperand(1);
16637
16638   // X86 can't encode an immediate LHS of a sub. See if we can push the
16639   // negation into a preceding instruction.
16640   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16641     // If the RHS of the sub is a XOR with one use and a constant, invert the
16642     // immediate. Then add one to the LHS of the sub so we can turn
16643     // X-Y -> X+~Y+1, saving one register.
16644     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16645         isa<ConstantSDNode>(Op1.getOperand(1))) {
16646       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16647       EVT VT = Op0.getValueType();
16648       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16649                                    Op1.getOperand(0),
16650                                    DAG.getConstant(~XorC, VT));
16651       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16652                          DAG.getConstant(C->getAPIntValue()+1, VT));
16653     }
16654   }
16655
16656   // Try to synthesize horizontal adds from adds of shuffles.
16657   EVT VT = N->getValueType(0);
16658   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16659        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16660       isHorizontalBinOp(Op0, Op1, true))
16661     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16662
16663   return OptimizeConditionalInDecrement(N, DAG);
16664 }
16665
16666 /// performVZEXTCombine - Performs build vector combines
16667 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
16668                                         TargetLowering::DAGCombinerInfo &DCI,
16669                                         const X86Subtarget *Subtarget) {
16670   // (vzext (bitcast (vzext (x)) -> (vzext x)
16671   SDValue In = N->getOperand(0);
16672   while (In.getOpcode() == ISD::BITCAST)
16673     In = In.getOperand(0);
16674
16675   if (In.getOpcode() != X86ISD::VZEXT)
16676     return SDValue();
16677
16678   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
16679 }
16680
16681 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16682                                              DAGCombinerInfo &DCI) const {
16683   SelectionDAG &DAG = DCI.DAG;
16684   switch (N->getOpcode()) {
16685   default: break;
16686   case ISD::EXTRACT_VECTOR_ELT:
16687     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16688   case ISD::VSELECT:
16689   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16690   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16691   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16692   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16693   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16694   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16695   case ISD::SHL:
16696   case ISD::SRA:
16697   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16698   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16699   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16700   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16701   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16702   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16703   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16704   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16705   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16706   case X86ISD::FXOR:
16707   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16708   case X86ISD::FMIN:
16709   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16710   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16711   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16712   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16713   case ISD::ANY_EXTEND:
16714   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16715   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16716   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16717   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16718   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16719   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16720   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
16721   case X86ISD::SHUFP:       // Handle all target specific shuffles
16722   case X86ISD::PALIGN:
16723   case X86ISD::UNPCKH:
16724   case X86ISD::UNPCKL:
16725   case X86ISD::MOVHLPS:
16726   case X86ISD::MOVLHPS:
16727   case X86ISD::PSHUFD:
16728   case X86ISD::PSHUFHW:
16729   case X86ISD::PSHUFLW:
16730   case X86ISD::MOVSS:
16731   case X86ISD::MOVSD:
16732   case X86ISD::VPERMILP:
16733   case X86ISD::VPERM2X128:
16734   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16735   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16736   }
16737
16738   return SDValue();
16739 }
16740
16741 /// isTypeDesirableForOp - Return true if the target has native support for
16742 /// the specified value type and it is 'desirable' to use the type for the
16743 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16744 /// instruction encodings are longer and some i16 instructions are slow.
16745 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16746   if (!isTypeLegal(VT))
16747     return false;
16748   if (VT != MVT::i16)
16749     return true;
16750
16751   switch (Opc) {
16752   default:
16753     return true;
16754   case ISD::LOAD:
16755   case ISD::SIGN_EXTEND:
16756   case ISD::ZERO_EXTEND:
16757   case ISD::ANY_EXTEND:
16758   case ISD::SHL:
16759   case ISD::SRL:
16760   case ISD::SUB:
16761   case ISD::ADD:
16762   case ISD::MUL:
16763   case ISD::AND:
16764   case ISD::OR:
16765   case ISD::XOR:
16766     return false;
16767   }
16768 }
16769
16770 /// IsDesirableToPromoteOp - This method query the target whether it is
16771 /// beneficial for dag combiner to promote the specified node. If true, it
16772 /// should return the desired promotion type by reference.
16773 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16774   EVT VT = Op.getValueType();
16775   if (VT != MVT::i16)
16776     return false;
16777
16778   bool Promote = false;
16779   bool Commute = false;
16780   switch (Op.getOpcode()) {
16781   default: break;
16782   case ISD::LOAD: {
16783     LoadSDNode *LD = cast<LoadSDNode>(Op);
16784     // If the non-extending load has a single use and it's not live out, then it
16785     // might be folded.
16786     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16787                                                      Op.hasOneUse()*/) {
16788       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16789              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16790         // The only case where we'd want to promote LOAD (rather then it being
16791         // promoted as an operand is when it's only use is liveout.
16792         if (UI->getOpcode() != ISD::CopyToReg)
16793           return false;
16794       }
16795     }
16796     Promote = true;
16797     break;
16798   }
16799   case ISD::SIGN_EXTEND:
16800   case ISD::ZERO_EXTEND:
16801   case ISD::ANY_EXTEND:
16802     Promote = true;
16803     break;
16804   case ISD::SHL:
16805   case ISD::SRL: {
16806     SDValue N0 = Op.getOperand(0);
16807     // Look out for (store (shl (load), x)).
16808     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16809       return false;
16810     Promote = true;
16811     break;
16812   }
16813   case ISD::ADD:
16814   case ISD::MUL:
16815   case ISD::AND:
16816   case ISD::OR:
16817   case ISD::XOR:
16818     Commute = true;
16819     // fallthrough
16820   case ISD::SUB: {
16821     SDValue N0 = Op.getOperand(0);
16822     SDValue N1 = Op.getOperand(1);
16823     if (!Commute && MayFoldLoad(N1))
16824       return false;
16825     // Avoid disabling potential load folding opportunities.
16826     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16827       return false;
16828     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16829       return false;
16830     Promote = true;
16831   }
16832   }
16833
16834   PVT = MVT::i32;
16835   return Promote;
16836 }
16837
16838 //===----------------------------------------------------------------------===//
16839 //                           X86 Inline Assembly Support
16840 //===----------------------------------------------------------------------===//
16841
16842 namespace {
16843   // Helper to match a string separated by whitespace.
16844   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16845     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16846
16847     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16848       StringRef piece(*args[i]);
16849       if (!s.startswith(piece)) // Check if the piece matches.
16850         return false;
16851
16852       s = s.substr(piece.size());
16853       StringRef::size_type pos = s.find_first_not_of(" \t");
16854       if (pos == 0) // We matched a prefix.
16855         return false;
16856
16857       s = s.substr(pos);
16858     }
16859
16860     return s.empty();
16861   }
16862   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16863 }
16864
16865 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16866   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16867
16868   std::string AsmStr = IA->getAsmString();
16869
16870   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16871   if (!Ty || Ty->getBitWidth() % 16 != 0)
16872     return false;
16873
16874   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16875   SmallVector<StringRef, 4> AsmPieces;
16876   SplitString(AsmStr, AsmPieces, ";\n");
16877
16878   switch (AsmPieces.size()) {
16879   default: return false;
16880   case 1:
16881     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16882     // we will turn this bswap into something that will be lowered to logical
16883     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16884     // lower so don't worry about this.
16885     // bswap $0
16886     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16887         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16888         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16889         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16890         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16891         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16892       // No need to check constraints, nothing other than the equivalent of
16893       // "=r,0" would be valid here.
16894       return IntrinsicLowering::LowerToByteSwap(CI);
16895     }
16896
16897     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16898     if (CI->getType()->isIntegerTy(16) &&
16899         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16900         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16901          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16902       AsmPieces.clear();
16903       const std::string &ConstraintsStr = IA->getConstraintString();
16904       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16905       std::sort(AsmPieces.begin(), AsmPieces.end());
16906       if (AsmPieces.size() == 4 &&
16907           AsmPieces[0] == "~{cc}" &&
16908           AsmPieces[1] == "~{dirflag}" &&
16909           AsmPieces[2] == "~{flags}" &&
16910           AsmPieces[3] == "~{fpsr}")
16911       return IntrinsicLowering::LowerToByteSwap(CI);
16912     }
16913     break;
16914   case 3:
16915     if (CI->getType()->isIntegerTy(32) &&
16916         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16917         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16918         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16919         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16920       AsmPieces.clear();
16921       const std::string &ConstraintsStr = IA->getConstraintString();
16922       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16923       std::sort(AsmPieces.begin(), AsmPieces.end());
16924       if (AsmPieces.size() == 4 &&
16925           AsmPieces[0] == "~{cc}" &&
16926           AsmPieces[1] == "~{dirflag}" &&
16927           AsmPieces[2] == "~{flags}" &&
16928           AsmPieces[3] == "~{fpsr}")
16929         return IntrinsicLowering::LowerToByteSwap(CI);
16930     }
16931
16932     if (CI->getType()->isIntegerTy(64)) {
16933       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16934       if (Constraints.size() >= 2 &&
16935           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16936           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16937         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16938         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16939             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16940             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16941           return IntrinsicLowering::LowerToByteSwap(CI);
16942       }
16943     }
16944     break;
16945   }
16946   return false;
16947 }
16948
16949
16950
16951 /// getConstraintType - Given a constraint letter, return the type of
16952 /// constraint it is for this target.
16953 X86TargetLowering::ConstraintType
16954 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16955   if (Constraint.size() == 1) {
16956     switch (Constraint[0]) {
16957     case 'R':
16958     case 'q':
16959     case 'Q':
16960     case 'f':
16961     case 't':
16962     case 'u':
16963     case 'y':
16964     case 'x':
16965     case 'Y':
16966     case 'l':
16967       return C_RegisterClass;
16968     case 'a':
16969     case 'b':
16970     case 'c':
16971     case 'd':
16972     case 'S':
16973     case 'D':
16974     case 'A':
16975       return C_Register;
16976     case 'I':
16977     case 'J':
16978     case 'K':
16979     case 'L':
16980     case 'M':
16981     case 'N':
16982     case 'G':
16983     case 'C':
16984     case 'e':
16985     case 'Z':
16986       return C_Other;
16987     default:
16988       break;
16989     }
16990   }
16991   return TargetLowering::getConstraintType(Constraint);
16992 }
16993
16994 /// Examine constraint type and operand type and determine a weight value.
16995 /// This object must already have been set up with the operand type
16996 /// and the current alternative constraint selected.
16997 TargetLowering::ConstraintWeight
16998   X86TargetLowering::getSingleConstraintMatchWeight(
16999     AsmOperandInfo &info, const char *constraint) const {
17000   ConstraintWeight weight = CW_Invalid;
17001   Value *CallOperandVal = info.CallOperandVal;
17002     // If we don't have a value, we can't do a match,
17003     // but allow it at the lowest weight.
17004   if (CallOperandVal == NULL)
17005     return CW_Default;
17006   Type *type = CallOperandVal->getType();
17007   // Look at the constraint type.
17008   switch (*constraint) {
17009   default:
17010     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17011   case 'R':
17012   case 'q':
17013   case 'Q':
17014   case 'a':
17015   case 'b':
17016   case 'c':
17017   case 'd':
17018   case 'S':
17019   case 'D':
17020   case 'A':
17021     if (CallOperandVal->getType()->isIntegerTy())
17022       weight = CW_SpecificReg;
17023     break;
17024   case 'f':
17025   case 't':
17026   case 'u':
17027       if (type->isFloatingPointTy())
17028         weight = CW_SpecificReg;
17029       break;
17030   case 'y':
17031       if (type->isX86_MMXTy() && Subtarget->hasMMX())
17032         weight = CW_SpecificReg;
17033       break;
17034   case 'x':
17035   case 'Y':
17036     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17037         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
17038       weight = CW_Register;
17039     break;
17040   case 'I':
17041     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17042       if (C->getZExtValue() <= 31)
17043         weight = CW_Constant;
17044     }
17045     break;
17046   case 'J':
17047     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17048       if (C->getZExtValue() <= 63)
17049         weight = CW_Constant;
17050     }
17051     break;
17052   case 'K':
17053     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17054       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17055         weight = CW_Constant;
17056     }
17057     break;
17058   case 'L':
17059     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17060       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17061         weight = CW_Constant;
17062     }
17063     break;
17064   case 'M':
17065     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17066       if (C->getZExtValue() <= 3)
17067         weight = CW_Constant;
17068     }
17069     break;
17070   case 'N':
17071     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17072       if (C->getZExtValue() <= 0xff)
17073         weight = CW_Constant;
17074     }
17075     break;
17076   case 'G':
17077   case 'C':
17078     if (dyn_cast<ConstantFP>(CallOperandVal)) {
17079       weight = CW_Constant;
17080     }
17081     break;
17082   case 'e':
17083     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17084       if ((C->getSExtValue() >= -0x80000000LL) &&
17085           (C->getSExtValue() <= 0x7fffffffLL))
17086         weight = CW_Constant;
17087     }
17088     break;
17089   case 'Z':
17090     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17091       if (C->getZExtValue() <= 0xffffffff)
17092         weight = CW_Constant;
17093     }
17094     break;
17095   }
17096   return weight;
17097 }
17098
17099 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17100 /// with another that has more specific requirements based on the type of the
17101 /// corresponding operand.
17102 const char *X86TargetLowering::
17103 LowerXConstraint(EVT ConstraintVT) const {
17104   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17105   // 'f' like normal targets.
17106   if (ConstraintVT.isFloatingPoint()) {
17107     if (Subtarget->hasSSE2())
17108       return "Y";
17109     if (Subtarget->hasSSE1())
17110       return "x";
17111   }
17112
17113   return TargetLowering::LowerXConstraint(ConstraintVT);
17114 }
17115
17116 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17117 /// vector.  If it is invalid, don't add anything to Ops.
17118 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17119                                                      std::string &Constraint,
17120                                                      std::vector<SDValue>&Ops,
17121                                                      SelectionDAG &DAG) const {
17122   SDValue Result(0, 0);
17123
17124   // Only support length 1 constraints for now.
17125   if (Constraint.length() > 1) return;
17126
17127   char ConstraintLetter = Constraint[0];
17128   switch (ConstraintLetter) {
17129   default: break;
17130   case 'I':
17131     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17132       if (C->getZExtValue() <= 31) {
17133         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17134         break;
17135       }
17136     }
17137     return;
17138   case 'J':
17139     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17140       if (C->getZExtValue() <= 63) {
17141         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17142         break;
17143       }
17144     }
17145     return;
17146   case 'K':
17147     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17148       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
17149         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17150         break;
17151       }
17152     }
17153     return;
17154   case 'N':
17155     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17156       if (C->getZExtValue() <= 255) {
17157         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17158         break;
17159       }
17160     }
17161     return;
17162   case 'e': {
17163     // 32-bit signed value
17164     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17165       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17166                                            C->getSExtValue())) {
17167         // Widen to 64 bits here to get it sign extended.
17168         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17169         break;
17170       }
17171     // FIXME gcc accepts some relocatable values here too, but only in certain
17172     // memory models; it's complicated.
17173     }
17174     return;
17175   }
17176   case 'Z': {
17177     // 32-bit unsigned value
17178     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17179       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17180                                            C->getZExtValue())) {
17181         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17182         break;
17183       }
17184     }
17185     // FIXME gcc accepts some relocatable values here too, but only in certain
17186     // memory models; it's complicated.
17187     return;
17188   }
17189   case 'i': {
17190     // Literal immediates are always ok.
17191     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17192       // Widen to 64 bits here to get it sign extended.
17193       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17194       break;
17195     }
17196
17197     // In any sort of PIC mode addresses need to be computed at runtime by
17198     // adding in a register or some sort of table lookup.  These can't
17199     // be used as immediates.
17200     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17201       return;
17202
17203     // If we are in non-pic codegen mode, we allow the address of a global (with
17204     // an optional displacement) to be used with 'i'.
17205     GlobalAddressSDNode *GA = 0;
17206     int64_t Offset = 0;
17207
17208     // Match either (GA), (GA+C), (GA+C1+C2), etc.
17209     while (1) {
17210       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17211         Offset += GA->getOffset();
17212         break;
17213       } else if (Op.getOpcode() == ISD::ADD) {
17214         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17215           Offset += C->getZExtValue();
17216           Op = Op.getOperand(0);
17217           continue;
17218         }
17219       } else if (Op.getOpcode() == ISD::SUB) {
17220         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17221           Offset += -C->getZExtValue();
17222           Op = Op.getOperand(0);
17223           continue;
17224         }
17225       }
17226
17227       // Otherwise, this isn't something we can handle, reject it.
17228       return;
17229     }
17230
17231     const GlobalValue *GV = GA->getGlobal();
17232     // If we require an extra load to get this address, as in PIC mode, we
17233     // can't accept it.
17234     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17235                                                         getTargetMachine())))
17236       return;
17237
17238     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17239                                         GA->getValueType(0), Offset);
17240     break;
17241   }
17242   }
17243
17244   if (Result.getNode()) {
17245     Ops.push_back(Result);
17246     return;
17247   }
17248   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17249 }
17250
17251 std::pair<unsigned, const TargetRegisterClass*>
17252 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17253                                                 EVT VT) const {
17254   // First, see if this is a constraint that directly corresponds to an LLVM
17255   // register class.
17256   if (Constraint.size() == 1) {
17257     // GCC Constraint Letters
17258     switch (Constraint[0]) {
17259     default: break;
17260       // TODO: Slight differences here in allocation order and leaving
17261       // RIP in the class. Do they matter any more here than they do
17262       // in the normal allocation?
17263     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17264       if (Subtarget->is64Bit()) {
17265         if (VT == MVT::i32 || VT == MVT::f32)
17266           return std::make_pair(0U, &X86::GR32RegClass);
17267         if (VT == MVT::i16)
17268           return std::make_pair(0U, &X86::GR16RegClass);
17269         if (VT == MVT::i8 || VT == MVT::i1)
17270           return std::make_pair(0U, &X86::GR8RegClass);
17271         if (VT == MVT::i64 || VT == MVT::f64)
17272           return std::make_pair(0U, &X86::GR64RegClass);
17273         break;
17274       }
17275       // 32-bit fallthrough
17276     case 'Q':   // Q_REGS
17277       if (VT == MVT::i32 || VT == MVT::f32)
17278         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17279       if (VT == MVT::i16)
17280         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17281       if (VT == MVT::i8 || VT == MVT::i1)
17282         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17283       if (VT == MVT::i64)
17284         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17285       break;
17286     case 'r':   // GENERAL_REGS
17287     case 'l':   // INDEX_REGS
17288       if (VT == MVT::i8 || VT == MVT::i1)
17289         return std::make_pair(0U, &X86::GR8RegClass);
17290       if (VT == MVT::i16)
17291         return std::make_pair(0U, &X86::GR16RegClass);
17292       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17293         return std::make_pair(0U, &X86::GR32RegClass);
17294       return std::make_pair(0U, &X86::GR64RegClass);
17295     case 'R':   // LEGACY_REGS
17296       if (VT == MVT::i8 || VT == MVT::i1)
17297         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17298       if (VT == MVT::i16)
17299         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17300       if (VT == MVT::i32 || !Subtarget->is64Bit())
17301         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17302       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17303     case 'f':  // FP Stack registers.
17304       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17305       // value to the correct fpstack register class.
17306       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17307         return std::make_pair(0U, &X86::RFP32RegClass);
17308       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17309         return std::make_pair(0U, &X86::RFP64RegClass);
17310       return std::make_pair(0U, &X86::RFP80RegClass);
17311     case 'y':   // MMX_REGS if MMX allowed.
17312       if (!Subtarget->hasMMX()) break;
17313       return std::make_pair(0U, &X86::VR64RegClass);
17314     case 'Y':   // SSE_REGS if SSE2 allowed
17315       if (!Subtarget->hasSSE2()) break;
17316       // FALL THROUGH.
17317     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17318       if (!Subtarget->hasSSE1()) break;
17319
17320       switch (VT.getSimpleVT().SimpleTy) {
17321       default: break;
17322       // Scalar SSE types.
17323       case MVT::f32:
17324       case MVT::i32:
17325         return std::make_pair(0U, &X86::FR32RegClass);
17326       case MVT::f64:
17327       case MVT::i64:
17328         return std::make_pair(0U, &X86::FR64RegClass);
17329       // Vector types.
17330       case MVT::v16i8:
17331       case MVT::v8i16:
17332       case MVT::v4i32:
17333       case MVT::v2i64:
17334       case MVT::v4f32:
17335       case MVT::v2f64:
17336         return std::make_pair(0U, &X86::VR128RegClass);
17337       // AVX types.
17338       case MVT::v32i8:
17339       case MVT::v16i16:
17340       case MVT::v8i32:
17341       case MVT::v4i64:
17342       case MVT::v8f32:
17343       case MVT::v4f64:
17344         return std::make_pair(0U, &X86::VR256RegClass);
17345       }
17346       break;
17347     }
17348   }
17349
17350   // Use the default implementation in TargetLowering to convert the register
17351   // constraint into a member of a register class.
17352   std::pair<unsigned, const TargetRegisterClass*> Res;
17353   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17354
17355   // Not found as a standard register?
17356   if (Res.second == 0) {
17357     // Map st(0) -> st(7) -> ST0
17358     if (Constraint.size() == 7 && Constraint[0] == '{' &&
17359         tolower(Constraint[1]) == 's' &&
17360         tolower(Constraint[2]) == 't' &&
17361         Constraint[3] == '(' &&
17362         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17363         Constraint[5] == ')' &&
17364         Constraint[6] == '}') {
17365
17366       Res.first = X86::ST0+Constraint[4]-'0';
17367       Res.second = &X86::RFP80RegClass;
17368       return Res;
17369     }
17370
17371     // GCC allows "st(0)" to be called just plain "st".
17372     if (StringRef("{st}").equals_lower(Constraint)) {
17373       Res.first = X86::ST0;
17374       Res.second = &X86::RFP80RegClass;
17375       return Res;
17376     }
17377
17378     // flags -> EFLAGS
17379     if (StringRef("{flags}").equals_lower(Constraint)) {
17380       Res.first = X86::EFLAGS;
17381       Res.second = &X86::CCRRegClass;
17382       return Res;
17383     }
17384
17385     // 'A' means EAX + EDX.
17386     if (Constraint == "A") {
17387       Res.first = X86::EAX;
17388       Res.second = &X86::GR32_ADRegClass;
17389       return Res;
17390     }
17391     return Res;
17392   }
17393
17394   // Otherwise, check to see if this is a register class of the wrong value
17395   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17396   // turn into {ax},{dx}.
17397   if (Res.second->hasType(VT))
17398     return Res;   // Correct type already, nothing to do.
17399
17400   // All of the single-register GCC register classes map their values onto
17401   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
17402   // really want an 8-bit or 32-bit register, map to the appropriate register
17403   // class and return the appropriate register.
17404   if (Res.second == &X86::GR16RegClass) {
17405     if (VT == MVT::i8) {
17406       unsigned DestReg = 0;
17407       switch (Res.first) {
17408       default: break;
17409       case X86::AX: DestReg = X86::AL; break;
17410       case X86::DX: DestReg = X86::DL; break;
17411       case X86::CX: DestReg = X86::CL; break;
17412       case X86::BX: DestReg = X86::BL; break;
17413       }
17414       if (DestReg) {
17415         Res.first = DestReg;
17416         Res.second = &X86::GR8RegClass;
17417       }
17418     } else if (VT == MVT::i32) {
17419       unsigned DestReg = 0;
17420       switch (Res.first) {
17421       default: break;
17422       case X86::AX: DestReg = X86::EAX; break;
17423       case X86::DX: DestReg = X86::EDX; break;
17424       case X86::CX: DestReg = X86::ECX; break;
17425       case X86::BX: DestReg = X86::EBX; break;
17426       case X86::SI: DestReg = X86::ESI; break;
17427       case X86::DI: DestReg = X86::EDI; break;
17428       case X86::BP: DestReg = X86::EBP; break;
17429       case X86::SP: DestReg = X86::ESP; break;
17430       }
17431       if (DestReg) {
17432         Res.first = DestReg;
17433         Res.second = &X86::GR32RegClass;
17434       }
17435     } else if (VT == MVT::i64) {
17436       unsigned DestReg = 0;
17437       switch (Res.first) {
17438       default: break;
17439       case X86::AX: DestReg = X86::RAX; break;
17440       case X86::DX: DestReg = X86::RDX; break;
17441       case X86::CX: DestReg = X86::RCX; break;
17442       case X86::BX: DestReg = X86::RBX; break;
17443       case X86::SI: DestReg = X86::RSI; break;
17444       case X86::DI: DestReg = X86::RDI; break;
17445       case X86::BP: DestReg = X86::RBP; break;
17446       case X86::SP: DestReg = X86::RSP; break;
17447       }
17448       if (DestReg) {
17449         Res.first = DestReg;
17450         Res.second = &X86::GR64RegClass;
17451       }
17452     }
17453   } else if (Res.second == &X86::FR32RegClass ||
17454              Res.second == &X86::FR64RegClass ||
17455              Res.second == &X86::VR128RegClass) {
17456     // Handle references to XMM physical registers that got mapped into the
17457     // wrong class.  This can happen with constraints like {xmm0} where the
17458     // target independent register mapper will just pick the first match it can
17459     // find, ignoring the required type.
17460
17461     if (VT == MVT::f32 || VT == MVT::i32)
17462       Res.second = &X86::FR32RegClass;
17463     else if (VT == MVT::f64 || VT == MVT::i64)
17464       Res.second = &X86::FR64RegClass;
17465     else if (X86::VR128RegClass.hasType(VT))
17466       Res.second = &X86::VR128RegClass;
17467     else if (X86::VR256RegClass.hasType(VT))
17468       Res.second = &X86::VR256RegClass;
17469   }
17470
17471   return Res;
17472 }